From 5ae72093e2c1be3b68a4997d9711cf27806a40e9 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 06:41:50 -0800 Subject: [PATCH 01/28] fix(recipes): scope the recipe-host env warning to the recipe's passEnv The host panel's recipe warning summarized all of process.env, but a recipe that sets passEnv only gets buildRecipeInheritedEnv(process.env, passEnv). The IPC now takes the host's environmentId; main finds its runtime and resolves passEnv through getRuntimeRecipeContext (never from the renderer), falling back to the whole env when the recipe can't be resolved. The summary reports narrowed, and the panel says so with a new string. One classifier (isRecipeCredentialEnvName) now backs both this warning and listCredentialLikeEnvNames. Co-Authored-By: Claude --- .../ipc/ephemeral-vm-forwarded-env.test.ts | 94 +++++++++++++++++++ src/main/ipc/ephemeral-vm-forwarded-env.ts | 41 +++++++- src/main/ipc/ephemeral-vm.ts | 2 +- src/preload/api/ephemeral-vm-api.ts | 7 +- src/preload/api/ephemeral-vm-bridge.ts | 2 +- .../agent-host-panel/HostPanelBody.tsx | 15 ++- .../RecipeEnvForwardingWarning.fixture.tsx | 19 +++- .../RecipeEnvForwardingWarning.tsx | 18 ++-- .../agent-host-panel-host-fixtures.tsx | 3 +- src/renderer/src/i18n/locales/en.json | 3 +- src/shared/ephemeral-vm-recipe-env.ts | 33 ++++++- .../ephemeral-vm-recipe-forwarded-env.test.ts | 46 ++++++++- .../ephemeral-vm-recipe-forwarded-env.ts | 46 +++------ 13 files changed, 275 insertions(+), 54 deletions(-) create mode 100644 src/main/ipc/ephemeral-vm-forwarded-env.test.ts diff --git a/src/main/ipc/ephemeral-vm-forwarded-env.test.ts b/src/main/ipc/ephemeral-vm-forwarded-env.test.ts new file mode 100644 index 00000000000..6a59860b2c3 --- /dev/null +++ b/src/main/ipc/ephemeral-vm-forwarded-env.test.ts @@ -0,0 +1,94 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' + +const handlers = new Map unknown>() +const { listRuntimesMock, recipeContextMock } = vi.hoisted(() => ({ + listRuntimesMock: vi.fn(), + recipeContextMock: vi.fn() +})) + +vi.mock('electron', () => ({ + app: { getPath: () => '/tmp/orca-user-data' }, + ipcMain: { + handle: (channel: string, handler: never) => handlers.set(channel, handler), + removeHandler: vi.fn() + } +})) +vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({ + listEphemeralVmRuntimes: listRuntimesMock +})) +vi.mock('./ephemeral-vm-recipe-context', () => ({ + getRuntimeRecipeContext: recipeContextMock +})) + +import { registerRecipeForwardedEnvHandler } from './ephemeral-vm-forwarded-env' +import type { RecipeForwardedEnvSummary } from '../../shared/ephemeral-vm-recipe-forwarded-env' + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handler hands the store to the mocked recipe context only +const store = {} as never + +function summarize(args?: unknown): RecipeForwardedEnvSummary { + const handler = handlers.get('ephemeralVm:forwardedEnvSummary') + if (!handler) { + throw new Error('handler not registered') + } + return handler({}, args) as RecipeForwardedEnvSummary +} + +beforeEach(() => { + vi.stubEnv('AWS_SECRET_ACCESS_KEY', 'aws-secret') + vi.stubEnv('OPENAI_API_KEY', 'sk-openai') + listRuntimesMock.mockReturnValue([ + { id: 'runtime-1', recipeId: 'aws', runtimeEnvironmentId: 'env-recipe' } + ]) + recipeContextMock.mockReturnValue({ recipe: { id: 'aws', passEnv: ['AWS_*'] } }) + registerRecipeForwardedEnvHandler(store) +}) + +afterEach(() => { + vi.unstubAllEnvs() + vi.clearAllMocks() + handlers.clear() +}) + +it("applies the recipe's own passEnv, looked up from the host's runtime", () => { + const summary = summarize({ environmentId: 'env-recipe' }) + expect(recipeContextMock).toHaveBeenCalledWith(store, '/tmp/orca-user-data', 'runtime-1') + expect(summary.narrowed).toBe(true) + expect(summary.keyLike).toContain('AWS_SECRET_ACCESS_KEY') + expect(summary.keyLike).not.toContain('OPENAI_API_KEY') +}) + +it('ignores a passEnv sent from the renderer', () => { + const summary = summarize({ environmentId: 'env-recipe', passEnv: ['OPENAI_*'] }) + expect(summary.keyLike).toContain('AWS_SECRET_ACCESS_KEY') + expect(summary.keyLike).not.toContain('OPENAI_API_KEY') + + const withoutHost = summarize({ passEnv: ['AWS_*'] }) + expect(withoutHost.narrowed).toBe(false) + expect(withoutHost.keyLike).toContain('OPENAI_API_KEY') +}) + +it('falls back to the whole env for an unknown host or an unresolvable recipe', () => { + const unknown = summarize({ environmentId: 'env-missing' }) + expect(recipeContextMock).not.toHaveBeenCalled() + expect(unknown.narrowed).toBe(false) + expect(unknown.keyLike).toEqual( + expect.arrayContaining(['AWS_SECRET_ACCESS_KEY', 'OPENAI_API_KEY']) + ) + + recipeContextMock.mockImplementation(() => { + throw new Error('recipe not found') + }) + const unresolved = summarize({ environmentId: 'env-recipe' }) + expect(unresolved.narrowed).toBe(false) + expect(unresolved.keyLike).toContain('OPENAI_API_KEY') +}) + +it('summarizes the whole env when the recipe sets no passEnv', () => { + recipeContextMock.mockReturnValue({ recipe: { id: 'aws' } }) + const summary = summarize({ environmentId: 'env-recipe' }) + expect(summary.narrowed).toBe(false) + expect(summary.keyLike).toEqual( + expect.arrayContaining(['AWS_SECRET_ACCESS_KEY', 'OPENAI_API_KEY']) + ) +}) diff --git a/src/main/ipc/ephemeral-vm-forwarded-env.ts b/src/main/ipc/ephemeral-vm-forwarded-env.ts index 80c94261d92..cca2decb82d 100644 --- a/src/main/ipc/ephemeral-vm-forwarded-env.ts +++ b/src/main/ipc/ephemeral-vm-forwarded-env.ts @@ -1,13 +1,46 @@ -import { ipcMain } from 'electron' +import { app, ipcMain } from 'electron' +import type { Store } from '../persistence/loading-store/store' +import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store' import { summarizeRecipeForwardedEnv, type RecipeForwardedEnvSummary } from '../../shared/ephemeral-vm-recipe-forwarded-env' +import { getRuntimeRecipeContext } from './ephemeral-vm-recipe-context' + +/** Which recipe host the renderer asks about. Main looks its recipe up; it never takes a passEnv. */ +export type RecipeForwardedEnvSummaryArgs = { environmentId?: string } + +/** The recipe's passEnv as its lifecycle scripts get it; undefined (whole env) when unresolvable. */ +export function resolveRecipeHostPassEnv( + store: Store, + userDataPath: string, + environmentId: unknown +): readonly string[] | undefined { + if (typeof environmentId !== 'string' || environmentId.length === 0) { + return undefined + } + try { + const runtime = listEphemeralVmRuntimes(userDataPath).find( + (entry) => entry.runtimeEnvironmentId === environmentId + ) + return runtime + ? getRuntimeRecipeContext(store, userDataPath, runtime.id).recipe.passEnv + : undefined + } catch { + // Why: an unresolvable recipe falls back to the whole env, which can only over-warn. + return undefined + } +} /** Recipe scripts inherit this process's env (buildRecipeEnv); only the names cross to the renderer. */ -export function registerRecipeForwardedEnvHandler(): void { +export function registerRecipeForwardedEnvHandler(store: Store): void { ipcMain.removeHandler('ephemeralVm:forwardedEnvSummary') - ipcMain.handle('ephemeralVm:forwardedEnvSummary', (): RecipeForwardedEnvSummary => - summarizeRecipeForwardedEnv(process.env) + ipcMain.handle( + 'ephemeralVm:forwardedEnvSummary', + (_event, args?: RecipeForwardedEnvSummaryArgs): RecipeForwardedEnvSummary => + summarizeRecipeForwardedEnv( + process.env, + resolveRecipeHostPassEnv(store, app.getPath('userData'), args?.environmentId) + ) ) } diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index e29e15fdfb3..bae4d043a41 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -104,7 +104,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin return listPickerRecipes(store, args.repoId, pluginService) }) - registerRecipeForwardedEnvHandler() + registerRecipeForwardedEnvHandler(store) ipcMain.handle( 'ephemeralVm:listRecipeCatalog', diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/ephemeral-vm-api.ts index ddd892058bf..bdf4cda8b16 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/ephemeral-vm-api.ts @@ -47,8 +47,11 @@ export type EphemeralVmApi = { diagnostics: NonNullable }[] > - /** Names (never values) of this computer's env that recipe create scripts receive. */ - forwardedEnvSummary: () => Promise + /** + * Names (never values) of this computer's env that recipe scripts receive. Given a recipe host's + * environmentId, main applies that recipe's passEnv; otherwise the whole env. + */ + forwardedEnvSummary: (args?: { environmentId?: string }) => Promise /** Credential-like variable names (never values) recipe scripts would inherit from Orca. */ listCredentialEnvNames: () => Promise doctor: (args: { repoId: string; recipeId: string }) => Promise diff --git a/src/preload/api/ephemeral-vm-bridge.ts b/src/preload/api/ephemeral-vm-bridge.ts index 8b6bdd463c0..1f86524a010 100644 --- a/src/preload/api/ephemeral-vm-bridge.ts +++ b/src/preload/api/ephemeral-vm-bridge.ts @@ -14,7 +14,7 @@ import { export const ephemeralVmApi = { listRecipes: (args) => ipcRenderer.invoke('ephemeralVm:listRecipes', args), listRecipeCatalog: () => ipcRenderer.invoke('ephemeralVm:listRecipeCatalog'), - forwardedEnvSummary: () => ipcRenderer.invoke('ephemeralVm:forwardedEnvSummary'), + forwardedEnvSummary: (args) => ipcRenderer.invoke('ephemeralVm:forwardedEnvSummary', args), listCredentialEnvNames: () => ipcRenderer.invoke('ephemeralVm:listCredentialEnvNames'), doctor: (args) => ipcRenderer.invoke('ephemeralVm:doctor', args), provision: (args) => ipcRenderer.invoke('ephemeralVm:provision', args), diff --git a/src/renderer/src/components/agent-host-panel/HostPanelBody.tsx b/src/renderer/src/components/agent-host-panel/HostPanelBody.tsx index 195a7e167ce..056e6cefdab 100644 --- a/src/renderer/src/components/agent-host-panel/HostPanelBody.tsx +++ b/src/renderer/src/components/agent-host-panel/HostPanelBody.tsx @@ -45,20 +45,27 @@ function useHostKeys(hostId: ExecutionHostId): AgentApiKeySummary[] | null { return keys } -function useRecipeEnvSummary(enabled: boolean): RecipeForwardedEnvSummary | null | undefined { +/** Main resolves this recipe host's passEnv from its recipe; the renderer only names the host. */ +function useRecipeEnvSummary( + enabled: boolean, + environmentId: string | null +): RecipeForwardedEnvSummary | null | undefined { const [summary, setSummary] = useState(null) useEffect(() => { if (!enabled) { return } let cancelled = false - void (window.api.ephemeralVm?.forwardedEnvSummary() ?? Promise.resolve(undefined)) + void ( + window.api.ephemeralVm?.forwardedEnvSummary(environmentId ? { environmentId } : undefined) ?? + Promise.resolve(undefined) + ) .catch(() => undefined) .then((next) => !cancelled && setSummary(next)) return () => { cancelled = true } - }, [enabled]) + }, [enabled, environmentId]) return summary } @@ -132,7 +139,7 @@ export function useHostPanelBody( // A primitive snapshot so the selector stays stable between renders. return `${accounts.claude ?? ''}\u0000${accounts.codex ?? ''}` }) - const recipeSummary = useRecipeEnvSummary(host.kind === 'recipe') + const recipeSummary = useRecipeEnvSummary(host.kind === 'recipe', host.environmentId) const [signOutAgent, setSignOutAgent] = useState(null) const unavailable = host.availability !== 'available' const agents = ( diff --git a/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.fixture.tsx b/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.fixture.tsx index bd9169135f7..18bbb9582be 100644 --- a/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.fixture.tsx +++ b/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.fixture.tsx @@ -4,7 +4,8 @@ import { RecipeEnvForwardingWarning } from './RecipeEnvForwardingWarning' const summary = { count: 42, keyLike: ['ANTHROPIC_API_KEY', 'GITHUB_TOKEN', 'NPM_TOKEN'], - other: ['EDITOR', 'HOME', 'LANG', 'PATH', 'SHELL', 'TERM', 'USER'] + other: ['EDITOR', 'HOME', 'LANG', 'PATH', 'SHELL', 'TERM', 'USER'], + narrowed: false } export const warning = defineFixture({ @@ -29,6 +30,22 @@ export const manyKeys = defineFixture({ ) }) +// A recipe with `passEnv: ['AWS_*']`: only base variables plus the AWS ones reach its scripts. +export const narrowed = defineFixture({ + width: 420, + render: () => ( + + ) +}) + export const noKeys = defineFixture({ width: 420, render: () => diff --git a/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.tsx b/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.tsx index ae1ad165c35..abb228f99de 100644 --- a/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.tsx +++ b/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.tsx @@ -9,8 +9,9 @@ import type { RecipeForwardedEnvSummary } from '../../../../shared/ephemeral-vm- const NAMES_IN_LINE = 3 /** - * P-4 (agent accounts spec §4, Q9): recipe create scripts get this computer's whole environment. - * A warning only; names, never values. `summary` null while loading, undefined when unavailable. + * P-4 (agent accounts spec §4, Q9): recipe create scripts get this computer's environment, or only + * what the recipe's passEnv allows (`summary.narrowed`). A warning only; names, never values. + * `summary` null while loading, undefined when unavailable. */ export function RecipeEnvForwardingWarning({ summary, @@ -70,10 +71,15 @@ export function RecipeEnvForwardingWarning({

- {t( - 'agentHostPanel.recipeEnv', - "This recipe's create script gets this computer's environment." - )} + {summary?.narrowed + ? t( + 'agentHostPanel.recipeEnvNarrowed', + "This recipe's create script gets only the variables its passEnv allows." + ) + : t( + 'agentHostPanel.recipeEnv', + "This recipe's create script gets this computer's environment." + )}

{summary === null ? ( diff --git a/src/renderer/src/components/agent-host-panel/agent-host-panel-host-fixtures.tsx b/src/renderer/src/components/agent-host-panel/agent-host-panel-host-fixtures.tsx index 5e13ee0fae6..afc77113843 100644 --- a/src/renderer/src/components/agent-host-panel/agent-host-panel-host-fixtures.tsx +++ b/src/renderer/src/components/agent-host-panel/agent-host-panel-host-fixtures.tsx @@ -90,7 +90,8 @@ export function HostFixture({ summary={{ count: 42, keyLike: ['AWS_SECRET_ACCESS_KEY', 'OPENAI_API_KEY'], - other: ['HOME', 'PATH'] + other: ['HOME', 'PATH'], + narrowed: false }} /> ) : null diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 5b15fcece2f..e74f6cabd73 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -28467,7 +28467,8 @@ "codeLabel": "Code from claude.ai", "deviceStep": "Enter this code on auth.openai.com. The sign-in is saved on {{host}}.", "codePlaceholder": "Paste the code" - } + }, + "recipeEnvNarrowed": "This recipe's create script gets only the variables its passEnv allows." }, "cloudSecretsAsk": { "scopeLabel": "Scope for {{name}}", diff --git a/src/shared/ephemeral-vm-recipe-env.ts b/src/shared/ephemeral-vm-recipe-env.ts index 0f4f7bf5ec5..22a52e1c30e 100644 --- a/src/shared/ephemeral-vm-recipe-env.ts +++ b/src/shared/ephemeral-vm-recipe-env.ts @@ -1,5 +1,6 @@ // Recipe scripts run locally and inherit Orca's environment. These helpers let a recipe opt into a // narrower environment (`passEnv`) and let the UI name the credential-like variables a recipe sees. +import { AGENT_CREDENTIAL_NAMES } from './agent-credentials/agent-credential-names' /** Variables every recipe keeps even with `passEnv`, so shells and provider CLIs still start. */ export const RECIPE_BASE_ENV_NAMES: readonly string[] = [ @@ -63,6 +64,36 @@ export function isCredentialLikeEnvName(name: string): boolean { ) } +const AGENT_CREDENTIAL_NAME_SET = new Set(Object.values(AGENT_CREDENTIAL_NAMES).flat()) +const CREDENTIAL_SEGMENTS = new Set([ + 'KEY', + 'KEYS', + 'APIKEY', + 'TOKEN', + 'TOKENS', + 'SECRET', + 'SECRETS', + 'CREDENTIAL', + 'CREDENTIALS', + 'PAT' +]) +const CREDENTIAL_SUBSTRINGS = /PASSWORD|PASSWD|SECRET|TOKEN|PRIVATE_KEY|API_?KEY/ + +/** The host panel's classifier: agent credential names, plus key/token/secret-shaped segments. */ +export function looksLikeCredentialEnvName(name: string): boolean { + const upper = name.toUpperCase() + return ( + AGENT_CREDENTIAL_NAME_SET.has(upper) || + CREDENTIAL_SUBSTRINGS.test(upper) || + upper.split(/[_\-.]/).some((segment) => CREDENTIAL_SEGMENTS.has(segment)) + ) +} + +/** The one rule every recipe env warning uses, so the host panel and Settings name the same variables. */ +export function isRecipeCredentialEnvName(name: string): boolean { + return looksLikeCredentialEnvName(name) || isCredentialLikeEnvName(name) +} + /** `passEnv` entries are exact names or a prefix ending in `*` (e.g. `AWS_*`). */ export function isRecipeEnvNamePassed( name: string, @@ -104,7 +135,7 @@ export function buildRecipeInheritedEnv( /** Sorted credential-like names with a non-empty value in `source`. Never returns values. */ export function listCredentialLikeEnvNames(source: NodeJS.ProcessEnv): string[] { return Object.entries(source) - .filter(([name, value]) => Boolean(value) && isCredentialLikeEnvName(name)) + .filter(([name, value]) => Boolean(value) && isRecipeCredentialEnvName(name)) .map(([name]) => name) .sort((a, b) => a.localeCompare(b)) } diff --git a/src/shared/ephemeral-vm-recipe-forwarded-env.test.ts b/src/shared/ephemeral-vm-recipe-forwarded-env.test.ts index 303830a7f88..314ffaa98a6 100644 --- a/src/shared/ephemeral-vm-recipe-forwarded-env.test.ts +++ b/src/shared/ephemeral-vm-recipe-forwarded-env.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { listCredentialLikeEnvNames } from './ephemeral-vm-recipe-env' import { summarizeRecipeForwardedEnv } from './ephemeral-vm-recipe-forwarded-env' describe('summarizeRecipeForwardedEnv', () => { @@ -23,10 +24,53 @@ describe('summarizeRecipeForwardedEnv', () => { 'GITHUB_TOKEN', 'openai_api_key' ], - other: ['HOME', 'KEYCHAIN_PATH', 'PATH'] + other: ['HOME', 'KEYCHAIN_PATH', 'PATH'], + narrowed: false }) expect(JSON.stringify(summary)).not.toMatch( /ghp_secret_value|aws-secret-value|hunter2|sk-lower/ ) }) + + const env = { AWS_SECRET_ACCESS_KEY: 'aws', OPENAI_API_KEY: 'sk', PATH: '/usr/bin' } + + it("summarizes only what the recipe's passEnv lets through", () => { + expect(summarizeRecipeForwardedEnv(env, ['AWS_*'], 'linux')).toEqual({ + count: 2, + keyLike: ['AWS_SECRET_ACCESS_KEY'], + other: ['PATH'], + narrowed: true + }) + }) + + it('summarizes the whole env without passEnv', () => { + expect(summarizeRecipeForwardedEnv(env, undefined, 'linux')).toEqual({ + count: 3, + keyLike: ['AWS_SECRET_ACCESS_KEY', 'OPENAI_API_KEY'], + other: ['PATH'], + narrowed: false + }) + }) + + it('names the same credentials as the Settings credentials notice', () => { + const sample = { + OPENAI_API_KEY: 'v', + GITHUB_TOKEN: 'v', + AWS_REGION: 'v', + MY_PASSWORD: 'v', + ANTHROPIC_AUTH_TOKEN: 'v', + PRIVATE_KEY_PATH: 'v', + PATH: 'v' + } + const keyLike = summarizeRecipeForwardedEnv(sample).keyLike + expect(keyLike).toEqual(listCredentialLikeEnvNames(sample)) + expect(keyLike).toEqual([ + 'ANTHROPIC_AUTH_TOKEN', + 'AWS_REGION', + 'GITHUB_TOKEN', + 'MY_PASSWORD', + 'OPENAI_API_KEY', + 'PRIVATE_KEY_PATH' + ]) + }) }) diff --git a/src/shared/ephemeral-vm-recipe-forwarded-env.ts b/src/shared/ephemeral-vm-recipe-forwarded-env.ts index 2f083e23e8c..352f234b127 100644 --- a/src/shared/ephemeral-vm-recipe-forwarded-env.ts +++ b/src/shared/ephemeral-vm-recipe-forwarded-env.ts @@ -1,46 +1,30 @@ -import { AGENT_CREDENTIAL_NAMES } from './agent-credentials/agent-credential-names' +import { buildRecipeInheritedEnv, isRecipeCredentialEnvName } from './ephemeral-vm-recipe-env' -/** Names only: recipe create scripts get this computer's whole env, so values never leave main. */ +/** Names only: the env a recipe's scripts inherit (passEnv-narrowed or whole); values never leave main. */ export type RecipeForwardedEnvSummary = { count: number - /** Sorted names that look like credentials (key/token/secret/password, or an agent credential). */ + /** Sorted names that look like credentials (isRecipeCredentialEnvName). */ keyLike: string[] /** Every other forwarded name, sorted. */ other: string[] + /** True when the recipe's passEnv narrowed the env; false means this computer's whole env. */ + narrowed: boolean } -const AGENT_CREDENTIAL_NAME_SET = new Set(Object.values(AGENT_CREDENTIAL_NAMES).flat()) -const CREDENTIAL_SEGMENTS = new Set([ - 'KEY', - 'KEYS', - 'APIKEY', - 'TOKEN', - 'TOKENS', - 'SECRET', - 'SECRETS', - 'CREDENTIAL', - 'CREDENTIALS', - 'PAT' -]) -const CREDENTIAL_SUBSTRINGS = /PASSWORD|PASSWD|SECRET|TOKEN|PRIVATE_KEY|API_?KEY/ - -export function looksLikeCredentialEnvName(name: string): boolean { - // Windows env names are case-insensitive; match them the way agents would read them. - const upper = name.toUpperCase() - return ( - AGENT_CREDENTIAL_NAME_SET.has(upper) || - CREDENTIAL_SUBSTRINGS.test(upper) || - upper.split(/[_\-.]/).some((segment) => CREDENTIAL_SEGMENTS.has(segment)) - ) -} - -export function summarizeRecipeForwardedEnv(env: NodeJS.ProcessEnv): RecipeForwardedEnvSummary { +/** Summarizes what buildRecipeEnv would inherit: the whole env, or only what `passEnv` allows. */ +export function summarizeRecipeForwardedEnv( + source: NodeJS.ProcessEnv, + passEnv?: readonly string[], + platform: NodeJS.Platform = process.platform +): RecipeForwardedEnvSummary { + const env = buildRecipeInheritedEnv(source, passEnv, platform) const names = Object.keys(env) .filter((name) => name.length > 0 && env[name] !== undefined) .sort((a, b) => a.localeCompare(b)) return { count: names.length, - keyLike: names.filter(looksLikeCredentialEnvName), - other: names.filter((name) => !looksLikeCredentialEnvName(name)) + keyLike: names.filter(isRecipeCredentialEnvName), + other: names.filter((name) => !isRecipeCredentialEnvName(name)), + narrowed: passEnv !== undefined } } From 123ba0572d420926d09259b3ece823df4147a3b2 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 20:29:29 -0800 Subject: [PATCH 02/28] feat(cloud): MFA status column for team admins and two-factor row in Settings, Account --- .../orca-profile-org-members-handlers.ts | 7 ++ .../profile-cloud-mfa-service.test.ts | 27 ++++++ .../cloud-mfa/profile-cloud-mfa-service.ts | 78 ++++++++++++++++ .../profile-cloud-dev-org-members.ts | 14 ++- .../profile-cloud-org-members-client.ts | 20 ++++- .../profile-cloud-org-members-client.test.ts | 26 ++++++ src/preload/api/orca-profile-api.ts | 3 + src/preload/api/orca-profiles-bridge.ts | 1 + .../billing/team/TeamMemberList.test.tsx | 68 ++++++++++++++ .../billing/team/TeamMemberList.tsx | 17 ++++ .../billing/team/TeamPageView.fixture.tsx | 31 +++++++ .../billing/team/team-member-mfa.ts | 40 +++++++++ .../accounts/orca/AccountMfaRow.fixture.tsx | 43 +++++++++ .../settings/accounts/orca/AccountMfaRow.tsx | 72 +++++++++++++++ .../accounts/orca/OrcaAccountSettingsPane.tsx | 4 + .../settings/accounts/orca/use-account-mfa.ts | 90 +++++++++++++++++++ src/renderer/src/i18n/locales/en.json | 13 +++ .../web/preload-api/web-orca-profiles-api.ts | 1 + src/shared/orca-account-mfa.ts | 13 +++ src/shared/orca-profiles.ts | 10 +++ 20 files changed, 574 insertions(+), 4 deletions(-) create mode 100644 src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.test.ts create mode 100644 src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.ts create mode 100644 src/renderer/src/components/billing/team/team-member-mfa.ts create mode 100644 src/renderer/src/components/settings/accounts/orca/AccountMfaRow.fixture.tsx create mode 100644 src/renderer/src/components/settings/accounts/orca/AccountMfaRow.tsx create mode 100644 src/renderer/src/components/settings/accounts/orca/use-account-mfa.ts create mode 100644 src/shared/orca-account-mfa.ts diff --git a/src/main/ipc/profiles/orca-profile-org-members-handlers.ts b/src/main/ipc/profiles/orca-profile-org-members-handlers.ts index f8dc1c80713..02f12b3bc3a 100644 --- a/src/main/ipc/profiles/orca-profile-org-members-handlers.ts +++ b/src/main/ipc/profiles/orca-profile-org-members-handlers.ts @@ -11,6 +11,8 @@ import type { OrcaProfileOrgMembersListArgs, OrcaProfileOrgMembersListResult } from '../../../shared/orca-profiles' +import type { OrcaAccountMfaResult } from '../../../shared/orca-account-mfa' +import { getOrcaProfileAccountMfa } from '../../orca-profiles/cloud-mfa/profile-cloud-mfa-service' import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' import { changeOrcaProfileOrgMemberRole, @@ -144,6 +146,11 @@ export function registerOrcaProfileOrgMemberHandlers(): void { createOrcaProfileOrg(getProfileUserDataPath(), { name: orgCreateNameFromUnknown(rawArgs) }) ) + ipcMain.handle( + 'orcaProfiles:accountMfa', + async (): Promise => getOrcaProfileAccountMfa(getProfileUserDataPath()) + ) + ipcMain.handle( 'orcaProfiles:orgMembersList', async ( diff --git a/src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.test.ts b/src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.test.ts new file mode 100644 index 00000000000..ed894f914a3 --- /dev/null +++ b/src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { normalizeAccountMfa } from './profile-cloud-mfa-service' + +const API = 'https://cloud.orca.dev' + +describe('normalizeAccountMfa', () => { + it('keeps the status and a setup link on Orca Cloud', () => { + expect( + normalizeAccountMfa({ mfa: 'off', setupUrl: `${API}/v1/account/security` }, API) + ).toEqual({ mfa: 'off', setupUrl: `${API}/v1/account/security` }) + expect(normalizeAccountMfa({ mfa: 'on', setupUrl: `${API}/x` }, `${API}/`).mfa).toBe('on') + }) + + it.each([ + ['another site', { mfa: 'off', setupUrl: 'https://evil.example/v1/account/security' }], + ['a look-alike host', { mfa: 'off', setupUrl: 'https://cloud.orca.dev.evil.example/' }], + ['plain http', { mfa: 'off', setupUrl: 'http://cloud.orca.dev/v1/account/security' }], + ['credentials in the link', { mfa: 'off', setupUrl: 'https://user:pw@cloud.orca.dev/' }], + ['a script link', { mfa: 'off', setupUrl: 'javascript:alert(1)' }], + ['no link', { mfa: 'off' }], + ['an unknown status', { mfa: 'pending', setupUrl: `${API}/v1/account/security` }], + ['a boolean status', { mfa: true, setupUrl: `${API}/v1/account/security` }], + ['nothing', null] + ])('refuses %s', (_name, body) => { + expect(() => normalizeAccountMfa(body, API)).toThrow('invalid_orca_account_mfa') + }) +}) diff --git a/src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.ts b/src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.ts new file mode 100644 index 00000000000..a901526a3cb --- /dev/null +++ b/src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.ts @@ -0,0 +1,78 @@ +import type { OrcaAccountMfa, OrcaAccountMfaResult } from '../../../shared/orca-account-mfa' +import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config' +import { + getOrcaCloudAuthConfig, + isOrcaCloudDevAuthEnabled +} from '../cloud-auth/profile-cloud-auth-config' +import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client' +import type { OrcaCloudSession } from '../cloud-session/profile-cloud-session-store' +import { extractErrorCode, requestInit } from '../cloud-org/profile-cloud-org-members-client' +import { runOrgMemberCall } from '../cloud-org/profile-cloud-org-members-service' +import { ensureActiveOrcaProfile } from '../profile-index-store' + +/** + * The renderer opens `setupUrl` in the browser, so it must be a page on Orca Cloud's own origin: + * a compromised or misconfigured answer cannot send the person to another site to "set up MFA". + */ +export function normalizeAccountMfa(value: unknown, apiBaseUrl: string): OrcaAccountMfa { + const record = value && typeof value === 'object' ? (value as Record) : {} + const mfa = record.mfa === 'on' || record.mfa === 'off' ? record.mfa : null + let setupUrl: URL | null = null + try { + setupUrl = typeof record.setupUrl === 'string' ? new URL(record.setupUrl) : null + } catch { + setupUrl = null + } + if ( + !mfa || + !setupUrl || + setupUrl.origin !== new URL(apiBaseUrl).origin || + setupUrl.username || + setupUrl.password + ) { + throw new Error('invalid_orca_account_mfa') + } + return { mfa, setupUrl: setupUrl.toString() } +} + +async function fetchAccountMfa( + config: OrcaCloudAuthConfig, + session: OrcaCloudSession +): Promise { + const response = await fetch( + `${config.apiBaseUrl}/v1/desktop/auth/mfa`, + requestInit('GET', session.accessToken) + ) + if (!response.ok) { + throw new OrcaCloudRequestError(response.status, await extractErrorCode(response)) + } + return normalizeAccountMfa((await response.json()) as unknown, config.apiBaseUrl) +} + +export async function getOrcaProfileAccountMfa(userDataPath: string): Promise { + const active = ensureActiveOrcaProfile(userDataPath) + // Local dev auth has no server and no factor to enrol. + if (isOrcaCloudDevAuthEnabled()) { + return { status: 'unsupported' } + } + const configState = getOrcaCloudAuthConfig() + if (!configState.configured) { + return { status: 'unconfigured' } + } + const result = await runOrgMemberCall(configState.config, active, userDataPath, (session) => + fetchAccountMfa(configState.config, session) + ) + switch (result.status) { + case 'ok': + return { status: 'ok', ...result.value } + case 'reconnect-required': + return { status: 'reconnect-required' } + case 'request-error': + // 404: an auth deployment from before this route, or a provider with no MFA status. + return result.error.statusCode === 404 + ? { status: 'unsupported' } + : { status: 'failed', error: result.error.message } + case 'failed': + return { status: 'failed', error: result.error } + } +} diff --git a/src/main/orca-profiles/cloud-org/profile-cloud-dev-org-members.ts b/src/main/orca-profiles/cloud-org/profile-cloud-dev-org-members.ts index ed5671f15bd..452488e6305 100644 --- a/src/main/orca-profiles/cloud-org/profile-cloud-dev-org-members.ts +++ b/src/main/orca-profiles/cloud-org/profile-cloud-dev-org-members.ts @@ -32,7 +32,8 @@ function devSelf(): OrcaOrgMember { userId: cleanEnvString(process.env.ORCA_CLOUD_DEV_USER_ID, 'dev-user'), email: cleanEnvString(process.env.ORCA_CLOUD_DEV_EMAIL, 'dev@orca.local'), displayName: cleanEnvString(process.env.ORCA_CLOUD_DEV_DISPLAY_NAME, 'Orca Dev'), - role: 'owner' + role: 'owner', + mfa: 'on' } } @@ -44,10 +45,17 @@ function seedDevRoster(): DevOrgRoster { userId: 'dev-teammate-1', email: 'teammate@orca.local', displayName: 'Dev Teammate', - role: 'admin' + role: 'admin', + mfa: 'off' }, // Null user IDs exercise members who have not signed in yet. - { userId: null, email: 'invited-member@orca.local', displayName: undefined, role: 'member' } + { + userId: null, + email: 'invited-member@orca.local', + displayName: undefined, + role: 'member', + mfa: 'off' + } ], pendingInvites: [{ email: 'pending@orca.local', role: 'member', createdAt: Date.now() }] } diff --git a/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts index 4c34ef96bee..26ad8e230d3 100644 --- a/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts +++ b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts @@ -1,5 +1,6 @@ import type { OrcaOrgMember, + OrcaOrgMemberMfa, OrcaOrgMembersRoster, OrcaOrgPendingInvite, OrcaOrgRole @@ -53,6 +54,22 @@ function optionalPictureUrl(value: unknown): string | undefined { } } +const MEMBER_MFA: readonly OrcaOrgMemberMfa[] = ['on', 'off', 'pending'] + +// Absent for plain members (the server leaves it out); an unknown value is dropped, never guessed. +function normalizeMemberMfa( + record: Record +): Pick { + const mfa = MEMBER_MFA.find((status) => status === record.mfa) + if (!mfa) { + return {} + } + const deadline = record.mfaDeadline + return mfa === 'pending' && typeof deadline === 'number' && Number.isFinite(deadline) + ? { mfa, mfaDeadline: deadline } + : { mfa } +} + function normalizeMember(value: unknown): OrcaOrgMember | null { if (!value || typeof value !== 'object') { return null @@ -70,7 +87,8 @@ function normalizeMember(value: unknown): OrcaOrgMember | null { ...(optionalPictureUrl(record.pictureUrl) ? { pictureUrl: optionalPictureUrl(record.pictureUrl) } : {}), - role: normalizeRole(record.role, 'member') + role: normalizeRole(record.role, 'member'), + ...normalizeMemberMfa(record) } } diff --git a/src/main/orca-profiles/profile-cloud-org-members-client.test.ts b/src/main/orca-profiles/profile-cloud-org-members-client.test.ts index 3d7eb390fde..4c4751672ea 100644 --- a/src/main/orca-profiles/profile-cloud-org-members-client.test.ts +++ b/src/main/orca-profiles/profile-cloud-org-members-client.test.ts @@ -29,4 +29,30 @@ describe('normalizeRoster', () => { ]) expect('pictureUrl' in roster.members[4]!).toBe(false) }) + + it('keeps a known MFA status and drops anything else', () => { + const roster = normalizeRoster({ + viewerRole: 'owner', + canManageMembers: true, + pendingInvites: [], + members: [ + { userId: 'a', email: 'a@x.dev', role: 'owner', mfa: 'on' }, + { userId: 'b', email: 'b@x.dev', role: 'member', mfa: 'off', mfaDeadline: 5 }, + { userId: 'c', email: 'c@x.dev', role: 'member', mfa: 'pending', mfaDeadline: 1_800_000 }, + { userId: 'd', email: 'd@x.dev', role: 'member', mfa: 'pending', mfaDeadline: 'soon' }, + { userId: 'e', email: 'e@x.dev', role: 'member', mfa: true }, + { userId: 'f', email: 'f@x.dev', role: 'member' } + ] + }) + expect(roster.members.map((m) => [m.mfa, m.mfaDeadline])).toEqual([ + ['on', undefined], + // A deadline only means something while the member is pending. + ['off', undefined], + ['pending', 1_800_000], + ['pending', undefined], + [undefined, undefined], + [undefined, undefined] + ]) + expect('mfa' in roster.members[5]!).toBe(false) + }) }) diff --git a/src/preload/api/orca-profile-api.ts b/src/preload/api/orca-profile-api.ts index 71572197248..5592156e542 100644 --- a/src/preload/api/orca-profile-api.ts +++ b/src/preload/api/orca-profile-api.ts @@ -1,3 +1,4 @@ +import type { OrcaAccountMfaResult } from '../../shared/orca-account-mfa' import type { CloudSetupGetResult, CloudSetupLinkResult, @@ -84,6 +85,8 @@ export type OrcaProfileApi = { refreshAuth: () => Promise signOutCurrent: () => Promise selectOrg: (args: SelectOrcaProfileOrgArgs) => Promise + /** The signed-in person's own two-factor state and where to manage it. */ + accountMfa: () => Promise orgMembersList: (args: OrcaProfileOrgMembersListArgs) => Promise orgMemberInvite: ( args: OrcaProfileOrgMemberInviteArgs diff --git a/src/preload/api/orca-profiles-bridge.ts b/src/preload/api/orca-profiles-bridge.ts index 22837449f8d..ee8b8376f9b 100644 --- a/src/preload/api/orca-profiles-bridge.ts +++ b/src/preload/api/orca-profiles-bridge.ts @@ -73,6 +73,7 @@ export const orcaProfilesApi = { refreshAuth: () => ipcRenderer.invoke('orcaProfiles:refreshAuth'), signOutCurrent: () => ipcRenderer.invoke('orcaProfiles:signOutCurrent'), selectOrg: (args) => ipcRenderer.invoke('orcaProfiles:selectOrg', args), + accountMfa: () => ipcRenderer.invoke('orcaProfiles:accountMfa'), orgMembersList: (args) => ipcRenderer.invoke('orcaProfiles:orgMembersList', args), orgMemberInvite: (args) => ipcRenderer.invoke('orcaProfiles:orgMemberInvite', args), orgInviteRevoke: (args) => ipcRenderer.invoke('orcaProfiles:orgInviteRevoke', args), diff --git a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx index 57411710e07..8448c9c81e6 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx @@ -44,3 +44,71 @@ it('marks a busy row with aria-busy and a spinner, without dimming it', () => { expect(busy.querySelector('.animate-spin')).not.toBeNull() expect(idle.querySelector('.animate-spin')).toBeNull() }) + +function renderList( + listRoster: OrcaOrgMembersRoster, + viewerUserId: string +): ReturnType { + return render( + + ) +} + +const rosterWithMfa: OrcaOrgMembersRoster = { + ...roster, + members: [ + { ...roster.members[0]!, mfa: 'on' }, + { ...roster.members[1]!, mfa: 'pending', mfaDeadline: Date.UTC(2026, 10, 24, 12) } + ], + pendingInvites: [{ email: 'alex@acme.dev', role: 'member', createdAt: Date.UTC(2026, 10, 17) }] +} + +it.each(['owner', 'admin'] as const)('shows the MFA column to an %s', (viewerRole) => { + const { container } = renderList({ ...rosterWithMfa, viewerRole }, 'u-neil') + const cell = (key: string): Element => + container.querySelector(`[data-team-row="${key}"] [data-team-mfa]`)! + expect(cell('member:u-neil').textContent).toBe('MFA on') + expect(cell('member:u-grace').textContent).toBe('MFA due Nov 24') + // Invites keep an empty cell so the role column stays aligned. + expect(cell('invite:alex@acme.dev').textContent).toBe('') +}) + +it('hides the MFA column from a plain member, even if a roster carried the status', () => { + const { container } = renderList( + { ...rosterWithMfa, viewerRole: 'member', canManageMembers: false }, + 'u-grace' + ) + expect(container.querySelector('[data-team-mfa]')).toBeNull() + expect(container.textContent).not.toContain('MFA') +}) + +it('shows no MFA column when the server sent no status', () => { + const { container } = renderList(roster, 'u-neil') + expect(container.querySelector('[data-team-mfa]')).toBeNull() +}) + +it('leaves the cell blank, not "off", for a member with no status', () => { + const { container } = renderList( + { + ...roster, + members: [{ ...roster.members[0]!, mfa: 'off' }, roster.members[1]!] + }, + 'u-neil' + ) + const cell = (key: string): Element => + container.querySelector(`[data-team-row="${key}"] [data-team-mfa]`)! + expect(cell('member:u-neil').textContent).toBe('MFA off') + expect(cell('member:u-grace').textContent).toBe('') +}) diff --git a/src/renderer/src/components/billing/team/TeamMemberList.tsx b/src/renderer/src/components/billing/team/TeamMemberList.tsx index 083d064cc2d..b464697560e 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.tsx @@ -25,10 +25,12 @@ import { SelectValue } from '@/components/ui/select' import { LoadingSpinner } from '@/components/LoadingSpinner' +import { cn } from '@/lib/class-names' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import type { OrcaOrgMember, OrcaOrgRole } from '../../../../../shared/orca-profiles' import { PersonAvatar } from './TeamAvatar' import { invitedAsCopy, memberStatusLabel, roleDescription } from './team-copy' +import { memberMfaLabel, showMfaColumn } from './team-member-mfa' import { assignableRoles, roleLabel } from './team-roles' import type { TeamRow } from './team-roster-rows' @@ -229,6 +231,7 @@ function RowMenu({ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element { const t = useTranslate() const locale = useIntlLocale() + const mfaColumn = showMfaColumn(props.rows, props.viewerRole) return (
    {state.busy ? : null} + {mfaColumn ? ( + // Rendered for every row, invites included, so the role column stays aligned. + + {row.kind === 'member' ? memberMfaLabel(row.member, locale, t) : null} + + ) : null} {row.kind === 'member' ? ( +}) + +export const adminSeesMfaColumn = defineFixture({ + width, + render: () => ( + + ) +}) + +export const mfaColumnNarrow = defineFixture({ + width: 640, + render: () => +}) + export const rowBusyAndError = defineFixture({ width, render: () => ( diff --git a/src/renderer/src/components/billing/team/team-member-mfa.ts b/src/renderer/src/components/billing/team/team-member-mfa.ts new file mode 100644 index 00000000000..c03e19d299a --- /dev/null +++ b/src/renderer/src/components/billing/team/team-member-mfa.ts @@ -0,0 +1,40 @@ +// The MFA column of the team list: who sees it and what each cell says. Pure, so the view and its +// tests share it. +import type { Translate } from '@/i18n/use-translate' +import type { OrcaOrgMember, OrcaOrgRole } from '../../../../../shared/orca-profiles' +import type { TeamRow } from './team-roster-rows' + +/** + * Owners and admins only. The server already leaves the status out for everyone else; the role + * check keeps the column hidden even if a roster carrying it ever reached a member's desktop. + */ +export function showMfaColumn(rows: readonly TeamRow[], viewerRole: OrcaOrgRole): boolean { + return ( + (viewerRole === 'owner' || viewerRole === 'admin') && + rows.some((row) => row.kind === 'member' && row.member.mfa !== undefined) + ) +} + +/** Null when the provider said nothing about this member: shown as blank, never as "off". */ +export function memberMfaLabel( + member: Pick, + locale: string, + t: Translate +): string | null { + switch (member.mfa) { + case 'on': + return t('auto.components.billing.team.mfaOn', 'MFA on') + case 'off': + return t('auto.components.billing.team.mfaOff', 'MFA off') + case 'pending': + return member.mfaDeadline === undefined + ? t('auto.components.billing.team.mfaPending', 'MFA pending') + : t('auto.components.billing.team.mfaPendingBy', 'MFA due {{value0}}', { + value0: new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric' }).format( + member.mfaDeadline + ) + }) + case undefined: + return null + } +} diff --git a/src/renderer/src/components/settings/accounts/orca/AccountMfaRow.fixture.tsx b/src/renderer/src/components/settings/accounts/orca/AccountMfaRow.fixture.tsx new file mode 100644 index 00000000000..13c52f32d3c --- /dev/null +++ b/src/renderer/src/components/settings/accounts/orca/AccountMfaRow.fixture.tsx @@ -0,0 +1,43 @@ +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import { AccountMfaRowView } from './AccountMfaRow' +import type { AccountMfaState } from './use-account-mfa' + +const width = 760 +const noop = (): void => {} +const setupUrl = 'https://cloud.orca.dev/v1/account/security' + +/** The row as it sits under the signed-in identity in Settings, Account. */ +function row(state: AccountMfaState, frameWidth = width) { + return defineFixture({ + width: frameWidth, + render: () => ( +
    + +
    + ) + }) +} + +/** No second factor yet: why to add one, and Set up in browser (chevron: Copy link). */ +export const off = row({ kind: 'known', mfa: 'off', setupUrl }) + +/** Enrolled: Manage in browser, for a new authenticator or the backup codes. */ +export const on = row({ kind: 'known', mfa: 'on', setupUrl }) + +/** A narrow settings pane: the button wraps under the text. */ +export const offNarrow = row({ kind: 'known', mfa: 'off', setupUrl }, 420) + +/** The chevron's menu, open on Copy link. */ +export const copyLinkMenu = defineFixture({ + width, + render: () => ( +
    + +
    + ), + interact: async (frame) => { + const chevron = frame.querySelector('button[aria-haspopup="menu"]') + chevron?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 })) + await new Promise((resolve) => setTimeout(resolve, 50)) + } +}) diff --git a/src/renderer/src/components/settings/accounts/orca/AccountMfaRow.tsx b/src/renderer/src/components/settings/accounts/orca/AccountMfaRow.tsx new file mode 100644 index 00000000000..de9dc4f2b62 --- /dev/null +++ b/src/renderer/src/components/settings/accounts/orca/AccountMfaRow.tsx @@ -0,0 +1,72 @@ +import { ShieldCheck } from 'lucide-react' +import { Badge } from '@/components/ui/badge' +import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' +import { useTranslate } from '@/i18n/use-translate' +import { useAccountMfa, type AccountMfaState } from './use-account-mfa' + +export type AccountMfaRowViewProps = { + state: AccountMfaState + onOpenSetup: () => void +} + +/** One state of the row; renders nothing until the first status read answers. */ +export function AccountMfaRowView({ + state, + onOpenSetup +}: AccountMfaRowViewProps): React.JSX.Element | null { + const t = useTranslate() + if (state.kind === 'unknown') { + return null + } + const on = state.mfa === 'on' + return ( +
    +
    + +
    +
    +
    +

    + {t('auto.components.settings.orcaAccount.mfa.title', 'Two-factor authentication')} +

    + + {on + ? t('auto.components.settings.orcaAccount.mfa.on', 'On') + : t('auto.components.settings.orcaAccount.mfa.off', 'Off')} + +
    +

    + {on + ? t( + 'auto.components.settings.orcaAccount.mfa.onDescription', + 'Signing in asks for a code from your authenticator app. Keep your backup codes somewhere safe.' + ) + : t( + 'auto.components.settings.orcaAccount.mfa.offDescription', + 'Add an authenticator app so a stolen password is not enough to sign in. You get backup codes too.' + )} +

    +
    + {/* Opens the account page in the browser; the chevron copies that link instead. */} + + {on + ? t('auto.components.settings.orcaAccount.mfa.manage', 'Manage in browser') + : t('auto.components.settings.orcaAccount.mfa.setUp', 'Set up in browser')} + +
    + ) +} + +/** + * "Two-factor authentication" under the signed-in identity. Mount it only while signed in to Orca + * Cloud. + */ +export function AccountMfaRow(): React.JSX.Element | null { + const mfa = useAccountMfa() + return +} diff --git a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx index 723a7654bbd..d787c7cf87e 100644 --- a/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx +++ b/src/renderer/src/components/settings/accounts/orca/OrcaAccountSettingsPane.tsx @@ -11,6 +11,7 @@ import { useAppStore } from '@/store/index' import { OrcaProfileSignOutConfirmDialog } from '../../../orca-profiles/OrcaProfileSignOutConfirmDialog' import { OrcaSignInButton, OrcaSignInWaitNotice } from '../../../OrcaSignInProgress' import { useOrcaCloudApiAvailable } from '@/hooks/useOrcaCloudApiAvailability' +import { AccountMfaRow } from './AccountMfaRow' import { GitHubIdentityRow } from './GitHubIdentityRow' function accountStatusCopy( @@ -135,6 +136,9 @@ export function OrcaAccountSettingsPane(): React.JSX.Element { {/* The person's own GitHub for cloud commits; only signed in to Orca Cloud. */} {connected && cloudAvailable ? : null} + {/* Their own second factor: status, and a link to the account page that manages it. */} + {connected && cloudAvailable ? : null} + {/* JA-16: with Orca Cloud the page is identity + Sign out only; plan, team and agents have their own entries in the Orca Cloud group right beside it. */} {cloudAvailable ? null : ( diff --git a/src/renderer/src/components/settings/accounts/orca/use-account-mfa.ts b/src/renderer/src/components/settings/accounts/orca/use-account-mfa.ts new file mode 100644 index 00000000000..0168f4ec334 --- /dev/null +++ b/src/renderer/src/components/settings/accounts/orca/use-account-mfa.ts @@ -0,0 +1,90 @@ +import { useCallback, useEffect, useState } from 'react' +import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' +import type { OrcaAccountMfa } from '../../../../../../shared/orca-account-mfa' + +/** Re-check every few seconds after the browser opened, for at most five minutes. */ +export const ACCOUNT_MFA_POLL_MS = 3_000 +export const ACCOUNT_MFA_WATCH_MAX_MS = 5 * 60_000 + +export type AccountMfaState = + /** Not read yet, every read failed, or this deployment has no MFA status: the row is hidden. */ + | { kind: 'unknown' } + | ({ kind: 'known' } & OrcaAccountMfa) + +export type AccountMfa = { + state: AccountMfaState + /** Opens the account's security page in the browser, then watches for the change. */ + openSetup: () => void +} + +/** + * The signed-in person's own two-factor state (mount only while signed in to Orca Cloud). Read on + * mount and when the window regains focus; polled lightly after the browser was opened, since the + * person enrols there and comes back. + */ +export function useAccountMfa(): AccountMfa { + const [state, setState] = useState({ kind: 'unknown' }) + const [watching, setWatching] = useState<'on' | 'off' | null>(null) + + const refresh = useCallback(async (): Promise => { + let result: Awaited> | null + try { + result = (await window.api.orcaProfiles.accountMfa()) ?? null + } catch { + result = null + } + // A failed read keeps what the row shows; the next focus or poll tries again. + if (result?.status === 'ok') { + setState({ kind: 'known', mfa: result.mfa, setupUrl: result.setupUrl }) + } + }, []) + + useEffect(() => { + void refresh() + const onFocus = (): void => void refresh() + const onVisibility = (): void => { + if (document.visibilityState === 'visible') { + void refresh() + } + } + window.addEventListener('focus', onFocus) + document.addEventListener('visibilitychange', onVisibility) + return () => { + window.removeEventListener('focus', onFocus) + document.removeEventListener('visibilitychange', onVisibility) + } + }, [refresh]) + + // Stop watching once the state differs from what it was when the browser opened. + const changed = watching !== null && state.kind === 'known' && state.mfa !== watching + useEffect(() => { + if (changed) { + setWatching(null) + } + }, [changed]) + + useEffect(() => { + if (watching === null) { + return + } + const stopPolling = installWindowVisibilityInterval({ + run: () => void refresh(), + intervalMs: ACCOUNT_MFA_POLL_MS + }) + const expire = setTimeout(() => setWatching(null), ACCOUNT_MFA_WATCH_MAX_MS) + return () => { + stopPolling() + clearTimeout(expire) + } + }, [watching, refresh]) + + const openSetup = useCallback((): void => { + if (state.kind !== 'known') { + return + } + void window.api.shell.openUrl(state.setupUrl) + setWatching(state.mfa) + }, [state]) + + return { state, openSetup } +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 71bd33d56ca..069072a01e9 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -13934,6 +13934,15 @@ "keywordSignOut": "sign out", "keywordRelay": "relay", "keywordCloud": "cloud", + "mfa": { + "title": "Two-factor authentication", + "on": "On", + "off": "Off", + "onDescription": "Signing in asks for a code from your authenticator app. Keep your backup codes somewhere safe.", + "offDescription": "Add an authenticator app so a stolen password is not enough to sign in. You get backup codes too.", + "manage": "Manage in browser", + "setUp": "Set up in browser" + }, "github": { "disconnectTitle": "Disconnect GitHub?", "disconnectBody": "Commits in cloud workspaces will use Orca Cloud's name again.", @@ -21139,6 +21148,10 @@ "makeOwnerTitle": "Make {{value0}} an owner?", "members": "Members", "membersList": "Team members and invites", + "mfaOn": "MFA on", + "mfaOff": "MFA off", + "mfaPending": "MFA pending", + "mfaPendingBy": "MFA due {{value0}}", "nextInvoice": "Next invoice (est.)", "nextInvoiceOn": "{{value0}} · {{value1}}", "notAnEmail": "Not an email address", diff --git a/src/renderer/src/web/preload-api/web-orca-profiles-api.ts b/src/renderer/src/web/preload-api/web-orca-profiles-api.ts index 4fa1c22b21e..99d7016d68b 100644 --- a/src/renderer/src/web/preload-api/web-orca-profiles-api.ts +++ b/src/renderer/src/web/preload-api/web-orca-profiles-api.ts @@ -65,6 +65,7 @@ export function createWebOrcaProfilesApi(): Partial { status: 'unconfigured', auth: await webOrcaProfileAuthStatus() }), + accountMfa: async () => ({ status: 'unconfigured' }), orgMembersList: async () => ({ status: 'unconfigured' }), orgMemberInvite: async () => ({ status: 'unconfigured' }), orgInviteRevoke: async () => ({ status: 'unconfigured' }), diff --git a/src/shared/orca-account-mfa.ts b/src/shared/orca-account-mfa.ts new file mode 100644 index 00000000000..12596bc0cda --- /dev/null +++ b/src/shared/orca-account-mfa.ts @@ -0,0 +1,13 @@ +// The signed-in person's own two-factor state for their Orca account. The identity provider owns +// the factor; Orca only reads whether one is set and where to manage it. +export type OrcaAccountMfa = { + mfa: 'on' | 'off' + /** Opens the account's security page in the browser. Checked in main: Orca Cloud's own origin. */ + setupUrl: string +} + +export type OrcaAccountMfaResult = + | ({ status: 'ok' } & OrcaAccountMfa) + /** `unsupported`: this Orca Cloud deployment (or local dev auth) has no MFA status. */ + | { status: 'unconfigured' | 'reconnect-required' | 'unsupported' } + | { status: 'failed'; error: string } diff --git a/src/shared/orca-profiles.ts b/src/shared/orca-profiles.ts index 7704c8aee72..4ce8ec0bdc8 100644 --- a/src/shared/orca-profiles.ts +++ b/src/shared/orca-profiles.ts @@ -258,8 +258,18 @@ export type OrcaOrgMember = { /** Profile picture from the identity provider (https only); avatars fall back to initials. */ pictureUrl?: string role: OrcaOrgRole + /** + * Whether the member has two-factor authentication. The server sends it to owners and admins + * only, so it is absent for everyone else, and for a member the provider said nothing about. + * 'pending': a team policy requires it by `mfaDeadline` and the member has not set it up. + */ + mfa?: OrcaOrgMemberMfa + /** Epoch ms the member must have MFA by; only with `mfa: 'pending'`. */ + mfaDeadline?: number } +export type OrcaOrgMemberMfa = 'on' | 'off' | 'pending' + export type OrcaOrgPendingInvite = { email: string role: OrcaOrgRole From 3a7d02e4ee32a3b854a59bc4eada7458c1e91e4b Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 20:33:26 -0800 Subject: [PATCH 03/28] feat(cloud): team MFA policy plumbing, banner, blocked screen and Require MFA row (views) --- .../orca-profile-org-members-handlers.ts | 52 ++++ .../profile-cloud-team-mfa-service.test.ts | 85 ++++++ .../profile-cloud-team-mfa-service.ts | 271 +++++++++++++++++ src/preload/api/orca-profile-api.ts | 14 + src/preload/api/orca-profiles-bridge.ts | 4 + .../src/components/team-mfa/RequireMfaRow.tsx | 276 ++++++++++++++++++ .../components/team-mfa/TeamMfa.fixture.tsx | 128 ++++++++ .../src/components/team-mfa/TeamMfaBanner.tsx | 48 +++ .../team-mfa/TeamMfaBlockedScreen.tsx | 93 ++++++ .../src/components/team-mfa/team-mfa-copy.ts | 59 ++++ .../src/components/team-mfa/team-mfa.test.tsx | 203 +++++++++++++ src/renderer/src/i18n/locales/en.json | 39 +++ .../web/preload-api/web-orca-profiles-api.ts | 4 + src/shared/orca-team-mfa-policy.ts | 66 +++++ 14 files changed, 1342 insertions(+) create mode 100644 src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.test.ts create mode 100644 src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts create mode 100644 src/renderer/src/components/team-mfa/RequireMfaRow.tsx create mode 100644 src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx create mode 100644 src/renderer/src/components/team-mfa/TeamMfaBanner.tsx create mode 100644 src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx create mode 100644 src/renderer/src/components/team-mfa/team-mfa-copy.ts create mode 100644 src/renderer/src/components/team-mfa/team-mfa.test.tsx create mode 100644 src/shared/orca-team-mfa-policy.ts diff --git a/src/main/ipc/profiles/orca-profile-org-members-handlers.ts b/src/main/ipc/profiles/orca-profile-org-members-handlers.ts index 02f12b3bc3a..455bdc47600 100644 --- a/src/main/ipc/profiles/orca-profile-org-members-handlers.ts +++ b/src/main/ipc/profiles/orca-profile-org-members-handlers.ts @@ -13,6 +13,20 @@ import type { } from '../../../shared/orca-profiles' import type { OrcaAccountMfaResult } from '../../../shared/orca-account-mfa' import { getOrcaProfileAccountMfa } from '../../orca-profiles/cloud-mfa/profile-cloud-mfa-service' +import { + ORCA_TEAM_MFA_GRACE_CHOICES, + type OrcaTeamMfaGrace, + type OrcaTeamMfaPendingResult, + type OrcaTeamMfaPolicyResult, + type OrcaTeamMfaPolicySetResult, + type OrcaTeamMfaRemindResult +} from '../../../shared/orca-team-mfa-policy' +import { + getOrcaTeamMfaPolicy, + listOrcaTeamMfaPending, + remindOrcaTeamMfa, + setOrcaTeamMfaPolicy +} from '../../orca-profiles/cloud-mfa/profile-cloud-team-mfa-service' import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' import { changeOrcaProfileOrgMemberRole, @@ -151,6 +165,44 @@ export function registerOrcaProfileOrgMemberHandlers(): void { async (): Promise => getOrcaProfileAccountMfa(getProfileUserDataPath()) ) + ipcMain.handle( + 'orcaProfiles:teamMfaPolicy', + async (_event, rawArgs: unknown): Promise => + getOrcaTeamMfaPolicy(getProfileUserDataPath(), orgMembersScopedArgs(rawArgs).orgId) + ) + + ipcMain.handle( + 'orcaProfiles:teamMfaPolicySet', + async (_event, rawArgs: unknown): Promise => { + const { orgId, record } = orgMembersScopedArgs(rawArgs) + const enforce = record.enforce + // Only the fixed choices cross to the server; anything else is refused here. + if (enforce !== 'off' && !ORCA_TEAM_MFA_GRACE_CHOICES.some((choice) => choice === enforce)) { + return { status: 'failed', error: 'invalid_enforce' } + } + return setOrcaTeamMfaPolicy(getProfileUserDataPath(), { + orgId, + enforce: enforce as OrcaTeamMfaGrace | 'off' + }) + } + ) + + ipcMain.handle( + 'orcaProfiles:teamMfaPending', + async (_event, rawArgs: unknown): Promise => + listOrcaTeamMfaPending(getProfileUserDataPath(), orgMembersScopedArgs(rawArgs).orgId) + ) + + ipcMain.handle( + 'orcaProfiles:teamMfaRemind', + async (_event, rawArgs: unknown): Promise => { + const { orgId, record } = orgMembersScopedArgs(rawArgs) + const userId = + typeof record.userId === 'string' && record.userId.length <= 128 ? record.userId : undefined + return remindOrcaTeamMfa(getProfileUserDataPath(), { orgId, ...(userId ? { userId } : {}) }) + } + ) + ipcMain.handle( 'orcaProfiles:orgMembersList', async ( diff --git a/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.test.ts b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.test.ts new file mode 100644 index 00000000000..bc6b69f7632 --- /dev/null +++ b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest' +import { + normalizePendingMembers, + normalizeTeamMfaPolicy, + sameOriginUrl +} from './profile-cloud-team-mfa-service' + +const API = 'https://cloud.orca.dev' +const setupUrl = `${API}/v1/account/security` + +describe('normalizeTeamMfaPolicy', () => { + it('reads a member answer: the deadline and their own state, no manager fields', () => { + expect( + normalizeTeamMfaPolicy( + { policy: { enforceAt: 200, setAt: 100 }, self: { mfa: 'pending' }, setupUrl }, + API + ) + ).toEqual({ policy: { enforceAt: 200, setAt: 100 }, self: 'pending', setupUrl }) + }) + + it('reads a manager answer, including a policy the plan no longer covers', () => { + expect( + normalizeTeamMfaPolicy( + { + policy: null, + self: { mfa: 'on' }, + setupUrl, + available: false, + pendingMembers: 3, + inactivePolicy: { enforceAt: 500 } + }, + API + ) + ).toEqual({ + policy: null, + self: 'on', + setupUrl, + manage: { available: false, pendingMembers: 3, inactiveEnforceAt: 500 } + }) + }) + + it('never turns a malformed state into blocked', () => { + for (const self of [undefined, null, {}, { mfa: 'BLOCKED' }, { mfa: true }, 'blocked']) { + expect(normalizeTeamMfaPolicy({ policy: null, self, setupUrl }, API).self).toBe('unknown') + } + }) + + it('drops a half-formed deadline rather than guessing one', () => { + expect( + normalizeTeamMfaPolicy({ policy: { enforceAt: 'soon' }, self: { mfa: 'off' }, setupUrl }, API) + .policy + ).toBeNull() + }) + + it('refuses an answer whose setup link is not on Orca Cloud', () => { + for (const link of ['https://evil.example/x', 'javascript:alert(1)', undefined, 7]) { + expect(() => + normalizeTeamMfaPolicy({ policy: null, self: { mfa: 'off' }, setupUrl: link }, API) + ).toThrow('invalid_orca_team_mfa_policy') + } + expect(sameOriginUrl('https://user:pw@cloud.orca.dev/x', API)).toBeNull() + expect(sameOriginUrl('http://cloud.orca.dev/x', API)).toBeNull() + }) +}) + +describe('normalizePendingMembers', () => { + it('keeps members with an email and maps unknown states to off', () => { + expect( + normalizePendingMembers({ + members: [ + { userId: 'u1', email: 'a@x.dev', displayName: 'Ada', mfa: 'pending' }, + { userId: null, email: 'b@x.dev', mfa: 'blocked' }, + { userId: 'u3', email: 'c@x.dev', mfa: 'whatever' }, + { userId: 'u4' }, + 'nope' + ] + }) + ).toEqual([ + { userId: 'u1', email: 'a@x.dev', displayName: 'Ada', mfa: 'pending' }, + { userId: null, email: 'b@x.dev', mfa: 'blocked' }, + { userId: 'u3', email: 'c@x.dev', mfa: 'off' } + ]) + expect(normalizePendingMembers(null)).toEqual([]) + }) +}) diff --git a/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts new file mode 100644 index 00000000000..5462ad2b15b --- /dev/null +++ b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts @@ -0,0 +1,271 @@ +import { + ORCA_TEAM_MFA_GRACE_CHOICES, + type OrcaTeamMfaGrace, + type OrcaTeamMfaPendingMember, + type OrcaTeamMfaPendingResult, + type OrcaTeamMfaPolicy, + type OrcaTeamMfaPolicyResult, + type OrcaTeamMfaPolicySetResult, + type OrcaTeamMfaRemindResult, + type OrcaTeamMfaSelfState +} from '../../../shared/orca-team-mfa-policy' +import { + getOrcaCloudAuthConfig, + isOrcaCloudDevAuthEnabled +} from '../cloud-auth/profile-cloud-auth-config' +import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client' +import { + extractErrorCode, + orgMembersUrl, + requestInit +} from '../cloud-org/profile-cloud-org-members-client' +import { runOrgMemberCall, type OrgCallResult } from '../cloud-org/profile-cloud-org-members-service' +import { ensureActiveOrcaProfile } from '../profile-index-store' + +const SELF_STATES: readonly OrcaTeamMfaSelfState[] = ['on', 'off', 'pending', 'blocked', 'unknown'] + +function finiteNumber(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) ? value : null +} + +/** The setup link is opened in the browser, so only a page on Orca Cloud's own origin is kept. */ +export function sameOriginUrl(value: unknown, apiBaseUrl: string): string | null { + if (typeof value !== 'string') { + return null + } + try { + const url = new URL(value) + return url.origin === new URL(apiBaseUrl).origin && !url.username && !url.password + ? url.toString() + : null + } catch { + return null + } +} + +function normalizeDeadline(value: unknown): { enforceAt: number; setAt: number } | null { + const record = value && typeof value === 'object' ? (value as Record) : null + const enforceAt = finiteNumber(record?.enforceAt) + const setAt = finiteNumber(record?.setAt) + return enforceAt !== null && setAt !== null ? { enforceAt, setAt } : null +} + +export function normalizeTeamMfaPolicy(value: unknown, apiBaseUrl: string): OrcaTeamMfaPolicy { + const record = value && typeof value === 'object' ? (value as Record) : null + const setupUrl = sameOriginUrl(record?.setupUrl, apiBaseUrl) + if (!record || !setupUrl) { + throw new Error('invalid_orca_team_mfa_policy') + } + const selfRecord = + record.self && typeof record.self === 'object' ? (record.self as Record) : {} + // An unrecognized state is "unknown", never "blocked": only the server's word blocks anyone. + const self = SELF_STATES.find((state) => state === selfRecord.mfa) ?? 'unknown' + const pendingMembers = finiteNumber(record.pendingMembers) + const inactive = + record.inactivePolicy && typeof record.inactivePolicy === 'object' + ? finiteNumber((record.inactivePolicy as Record).enforceAt) + : null + return { + policy: normalizeDeadline(record.policy), + self, + setupUrl, + // Present only when the server sent the manager fields; a member's answer has none. + ...(typeof record.available === 'boolean' + ? { + manage: { + available: record.available, + pendingMembers: pendingMembers ?? 0, + ...(inactive !== null ? { inactiveEnforceAt: inactive } : {}) + } + } + : {}) + } +} + +export function normalizePendingMembers(value: unknown): OrcaTeamMfaPendingMember[] { + const record = value && typeof value === 'object' ? (value as Record) : null + const members = Array.isArray(record?.members) ? record.members : [] + return members.flatMap((entry): OrcaTeamMfaPendingMember[] => { + const member = entry && typeof entry === 'object' ? (entry as Record) : null + const email = typeof member?.email === 'string' ? member.email.trim() : '' + if (!member || !email) { + return [] + } + const displayName = typeof member.displayName === 'string' ? member.displayName.trim() : '' + return [ + { + userId: typeof member.userId === 'string' && member.userId ? member.userId : null, + email, + ...(displayName ? { displayName } : {}), + mfa: member.mfa === 'blocked' ? 'blocked' : member.mfa === 'pending' ? 'pending' : 'off' + } + ] + }) +} + +async function request(url: string, init: RequestInit): Promise { + const response = await fetch(url, init) + if (!response.ok) { + throw new OrcaCloudRequestError(response.status, await extractErrorCode(response)) + } + return (await response.json()) as unknown +} + +type Unavailable = Extract< + OrcaTeamMfaPolicyResult, + { status: 'unconfigured' | 'reconnect-required' | 'unsupported' | 'forbidden' | 'rate-limited' | 'failed' } +> + +function unavailable(result: Exclude, { status: 'ok' }>): Unavailable { + if (result.status === 'reconnect-required') { + return { status: 'reconnect-required' } + } + if (result.status === 'failed') { + return { status: 'failed', error: result.error } + } + const { statusCode, errorCode, message } = result.error + if (statusCode === 404 && !errorCode) { + // No JSON error: an auth deployment from before these routes. + return { status: 'unsupported' } + } + if (statusCode === 403) { + return { status: 'forbidden' } + } + if (statusCode === 429) { + return { status: 'rate-limited' } + } + return { status: 'failed', error: message } +} + +async function call( + userDataPath: string, + run: (apiBaseUrl: string, accessToken: string, url: (path: string) => string) => Promise, + orgId: string +): Promise | { status: 'unconfigured' | 'unsupported' }> { + const active = ensureActiveOrcaProfile(userDataPath) + // Local dev auth has no server, so no policy. + if (isOrcaCloudDevAuthEnabled()) { + return { status: 'unsupported' } + } + const configState = getOrcaCloudAuthConfig() + if (!configState.configured) { + return { status: 'unconfigured' } + } + const { config } = configState + return runOrgMemberCall(config, active, userDataPath, (session) => + run(config.apiBaseUrl, session.accessToken, (path) => orgMembersUrl(config, orgId, path)) + ) +} + +export async function getOrcaTeamMfaPolicy( + userDataPath: string, + orgId: string +): Promise { + const result = await call( + userDataPath, + async (apiBaseUrl, token, url) => + normalizeTeamMfaPolicy( + await request(url('/mfa-policy'), requestInit('GET', token)), + apiBaseUrl + ), + orgId + ) + if (result.status === 'ok') { + return { status: 'ok', ...result.value } + } + return result.status === 'unconfigured' || result.status === 'unsupported' + ? result + : unavailable(result) +} + +export async function setOrcaTeamMfaPolicy( + userDataPath: string, + args: { orgId: string; enforce: OrcaTeamMfaGrace | 'off' } +): Promise { + if (args.enforce !== 'off' && !ORCA_TEAM_MFA_GRACE_CHOICES.includes(args.enforce)) { + return { status: 'failed', error: 'invalid_enforce' } + } + const result = await call( + userDataPath, + async (_apiBaseUrl, token, url) => { + const init = + args.enforce === 'off' + ? { ...requestInit('GET', token), method: 'DELETE' } + : { ...requestInit('POST', token, { enforce: args.enforce }), method: 'PUT' } + const body = (await request(url('/mfa-policy'), init)) as Record | null + return { + policy: normalizeDeadline(body?.policy), + pendingMembers: finiteNumber(body?.pendingMembers) ?? 0 + } + }, + args.orgId + ) + if (result.status === 'ok') { + return { status: 'ok', ...result.value } + } + if (result.status === 'unconfigured' || result.status === 'unsupported') { + return result + } + if (result.status === 'request-error') { + const { errorCode } = result.error + if (errorCode === 'actor_needs_mfa') { + return { status: 'actor-needs-mfa' } + } + if (errorCode === 'mfa_enforcement_not_entitled') { + return { status: 'not-entitled' } + } + } + return unavailable(result) +} + +export async function listOrcaTeamMfaPending( + userDataPath: string, + orgId: string +): Promise { + const result = await call( + userDataPath, + async (_apiBaseUrl, token, url) => + normalizePendingMembers(await request(url('/mfa-policy/pending'), requestInit('GET', token))), + orgId + ) + if (result.status === 'ok') { + return { status: 'ok', members: result.value } + } + return result.status === 'unconfigured' || result.status === 'unsupported' + ? result + : unavailable(result) +} + +export async function remindOrcaTeamMfa( + userDataPath: string, + args: { orgId: string; userId?: string } +): Promise { + const result = await call( + userDataPath, + async (_apiBaseUrl, token, url) => { + const body = (await request( + url('/mfa-policy/remind'), + requestInit('POST', token, args.userId ? { userId: args.userId } : {}) + )) as Record | null + const delivery: 'log' | 'test-inbox' | 'unknown' = + body?.delivery === 'log' || body?.delivery === 'test-inbox' ? body.delivery : 'unknown' + return { recipients: finiteNumber(body?.recipients) ?? 0, delivery } + }, + args.orgId + ) + if (result.status === 'ok') { + return { status: 'ok', ...result.value } + } + if (result.status === 'unconfigured' || result.status === 'unsupported') { + return result + } + if (result.status === 'request-error') { + if (result.error.errorCode === 'no_policy') { + return { status: 'no-policy' } + } + if (result.error.errorCode === 'member_not_found') { + return { status: 'not-found' } + } + } + return unavailable(result) +} diff --git a/src/preload/api/orca-profile-api.ts b/src/preload/api/orca-profile-api.ts index 5592156e542..4b5a8781244 100644 --- a/src/preload/api/orca-profile-api.ts +++ b/src/preload/api/orca-profile-api.ts @@ -1,3 +1,12 @@ +import type { + OrcaTeamMfaPendingResult, + OrcaTeamMfaPolicyArgs, + OrcaTeamMfaPolicyResult, + OrcaTeamMfaPolicySetArgs, + OrcaTeamMfaPolicySetResult, + OrcaTeamMfaRemindArgs, + OrcaTeamMfaRemindResult +} from '../../shared/orca-team-mfa-policy' import type { OrcaAccountMfaResult } from '../../shared/orca-account-mfa' import type { CloudSetupGetResult, @@ -87,6 +96,11 @@ export type OrcaProfileApi = { selectOrg: (args: SelectOrcaProfileOrgArgs) => Promise /** The signed-in person's own two-factor state and where to manage it. */ accountMfa: () => Promise + /** The team's "require MFA" policy and the person's own state in it. */ + teamMfaPolicy: (args: OrcaTeamMfaPolicyArgs) => Promise + teamMfaPolicySet: (args: OrcaTeamMfaPolicySetArgs) => Promise + teamMfaPending: (args: OrcaTeamMfaPolicyArgs) => Promise + teamMfaRemind: (args: OrcaTeamMfaRemindArgs) => Promise orgMembersList: (args: OrcaProfileOrgMembersListArgs) => Promise orgMemberInvite: ( args: OrcaProfileOrgMemberInviteArgs diff --git a/src/preload/api/orca-profiles-bridge.ts b/src/preload/api/orca-profiles-bridge.ts index ee8b8376f9b..ad1efe93822 100644 --- a/src/preload/api/orca-profiles-bridge.ts +++ b/src/preload/api/orca-profiles-bridge.ts @@ -74,6 +74,10 @@ export const orcaProfilesApi = { signOutCurrent: () => ipcRenderer.invoke('orcaProfiles:signOutCurrent'), selectOrg: (args) => ipcRenderer.invoke('orcaProfiles:selectOrg', args), accountMfa: () => ipcRenderer.invoke('orcaProfiles:accountMfa'), + teamMfaPolicy: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaPolicy', args), + teamMfaPolicySet: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaPolicySet', args), + teamMfaPending: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaPending', args), + teamMfaRemind: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaRemind', args), orgMembersList: (args) => ipcRenderer.invoke('orcaProfiles:orgMembersList', args), orgMemberInvite: (args) => ipcRenderer.invoke('orcaProfiles:orgMemberInvite', args), orgInviteRevoke: (args) => ipcRenderer.invoke('orcaProfiles:orgInviteRevoke', args), diff --git a/src/renderer/src/components/team-mfa/RequireMfaRow.tsx b/src/renderer/src/components/team-mfa/RequireMfaRow.tsx new file mode 100644 index 00000000000..8e45a9b8d25 --- /dev/null +++ b/src/renderer/src/components/team-mfa/RequireMfaRow.tsx @@ -0,0 +1,276 @@ +import { useState } from 'react' +import { Loader2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { InlineError } from '@/components/ui/inline-error' +import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue +} from '@/components/ui/select' +import { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { + ORCA_TEAM_MFA_GRACE_CHOICES, + type OrcaTeamMfaGrace, + type OrcaTeamMfaPendingMember, + type OrcaTeamMfaPolicy +} from '../../../../shared/orca-team-mfa-policy' +import { mfaCountdownLabel, mfaDeadlineDate, mfaGraceLabel } from './team-mfa-copy' + +export type RequireMfaRowNotice = + | { kind: 'error'; message: string } + /** `emailed` false: the server recorded the reminder but its email delivery is off. */ + | { kind: 'reminded'; recipients: number; emailed: boolean } + +export type RequireMfaRowProps = { + /** The policy read for an owner or admin (`manage` present). */ + policy: OrcaTeamMfaPolicy + /** Null until the pending list is read; shown only while a policy is in force. */ + pending: OrcaTeamMfaPendingMember[] | null + now: number + busy: boolean + notice: RequireMfaRowNotice | null + onRequire: (grace: OrcaTeamMfaGrace) => void + onTurnOff: () => void + onRemind: (userId?: string) => void + onSetUpOwn: () => void +} + +/** + * "Require MFA" in Settings, Enterprise, Multi-factor authentication. Rendered only for a team + * whose plan includes it; the pane shows its shared upsell otherwise. + */ +export function RequireMfaRow({ + policy, + pending, + now, + busy, + notice, + onRequire, + onTurnOff, + onRemind, + onSetUpOwn +}: RequireMfaRowProps): React.JSX.Element { + const t = useTranslate() + const locale = useIntlLocale() + const [grace, setGrace] = useState(14) + const active = policy.policy + const pendingCount = policy.manage?.pendingMembers ?? 0 + // The server refuses a change from someone without MFA; say so before they try. + const needsOwnMfa = policy.self !== 'on' + const enforced = active !== null && active.enforceAt <= now + + return ( +
    +
    +
    +

    + {t('auto.components.teamMfa.rowTitle', 'Require two-factor authentication')} +

    +

    + {active === null + ? t( + 'auto.components.teamMfa.rowOff', + 'Members without it lose access to this team’s workspaces after the date you pick, until they set it up. They get an email now and reminders before the date.' + ) + : enforced + ? t( + 'auto.components.teamMfa.rowEnforced', + 'Required since {{value0}}. Members without it can’t use this team until they set it up.', + { value0: mfaDeadlineDate(active.enforceAt, locale) } + ) + : t( + 'auto.components.teamMfa.rowScheduled', + 'Required from {{value0}}. {{value1}}.', + { + value0: mfaDeadlineDate(active.enforceAt, locale), + value1: mfaCountdownLabel(active.enforceAt, now, t) + } + )} +

    +
    + {active === null ? ( +
    + + +
    + ) : ( + + )} +
    + + {needsOwnMfa ? ( + + {t('auto.components.teamMfa.setUp', 'Set up MFA')} + + } + /> + ) : null} + + {active === null && grace === 'now' && pendingCount > 0 && !needsOwnMfa ? ( +

    + {t( + 'auto.components.teamMfa.nowWarning', + '{{count}} members don’t have it yet and will lose access to this team right away.', + { + count: pendingCount, + defaultValue_one: + '{{count}} member doesn’t have it yet and will lose access to this team right away.' + } + )} +

    + ) : null} + + {active !== null ? ( +
    +
    +

    + {pendingCount === 0 + ? t('auto.components.teamMfa.allSet', 'Every member has it set up.') + : t('auto.components.teamMfa.pendingCount', '{{count}} members still need it', { + count: pendingCount, + defaultValue_one: '{{count}} member still needs it' + })} +

    + {pendingCount > 0 ? ( + + ) : null} +
    + {pending && pending.length > 0 ? ( +
      + {pending.map((member) => ( +
    • +
      +

      {member.displayName ?? member.email}

      + {member.displayName ? ( +

      {member.email}

      + ) : null} +
      + + {member.mfa === 'blocked' + ? t('auto.components.teamMfa.memberBlocked', 'No access') + : t('auto.components.teamMfa.memberPending', 'Pending')} + + {member.userId ? ( + + ) : null} +
    • + ))} +
    + ) : null} +
    + ) : null} + + {notice?.kind === 'error' ? : null} + {notice?.kind === 'reminded' ? ( +

    + {notice.emailed + ? t('auto.components.teamMfa.reminded', 'Reminder sent to {{count}} members.', { + count: notice.recipients, + defaultValue_one: 'Reminder sent to {{count}} member.' + }) + : t( + 'auto.components.teamMfa.remindedNoEmail', + 'Reminder recorded, but email delivery is off on this server, so nothing was sent.' + )} +

    + ) : null} +
    + ) +} diff --git a/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx b/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx new file mode 100644 index 00000000000..0ee240a5a28 --- /dev/null +++ b/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx @@ -0,0 +1,128 @@ +import { defineFixture } from '../../component-fixtures/component-fixture' +import type { + OrcaTeamMfaPendingMember, + OrcaTeamMfaPolicy +} from '../../../../shared/orca-team-mfa-policy' +import { RequireMfaRow, type RequireMfaRowProps } from './RequireMfaRow' +import { TeamMfaBanner } from './TeamMfaBanner' +import { TeamMfaBlockedScreen } from './TeamMfaBlockedScreen' + +const NOW = Date.UTC(2026, 10, 18, 15) +const DAY = 86_400_000 +const setupUrl = 'https://cloud.orca.dev/v1/account/security' +const noop = (): void => {} +const width = 760 + +function frame(children: React.ReactNode, frameWidth = width) { + return defineFixture({ + width: frameWidth, + render: () =>
    {children}
    + }) +} + +// ---- Banner: a member without MFA, before the deadline ---- + +const banner = (daysLeft: number, frameWidth = width) => + frame( + , + frameWidth + ) + +export const bannerTwoWeeks = banner(14) +export const bannerOneDay = banner(1) +export const bannerNarrow = banner(6, 420) + +// ---- Blocked screen: after the deadline ---- + +const blocked = (props: { checking?: boolean; stillMissing?: boolean; personal?: boolean }) => + frame( + + ) + +export const blockedScreen = blocked({}) +export const blockedChecking = blocked({ checking: true }) +/** "I've set it up" found no MFA yet. */ +export const blockedStillMissing = blocked({ stillMissing: true }) + +// ---- Settings, Enterprise, Multi-factor authentication ---- + +const pendingMembers: OrcaTeamMfaPendingMember[] = [ + { userId: 'u-ada', email: 'ada@acme.dev', displayName: 'Ada Lovelace', mfa: 'pending' }, + { userId: 'u-grace', email: 'grace@acme.dev', displayName: 'Grace Hopper', mfa: 'pending' }, + { userId: null, email: 'linus@acme.dev', mfa: 'pending' } +] + +const off: OrcaTeamMfaPolicy = { + policy: null, + self: 'on', + setupUrl, + manage: { available: true, pendingMembers: 3 } +} +const scheduled: OrcaTeamMfaPolicy = { + ...off, + policy: { enforceAt: NOW + 6 * DAY, setAt: NOW - 8 * DAY } +} + +const row = (props: Partial) => + frame( + + ) + +/** Not required yet: pick when, then Require MFA. */ +export const rowOff = row({}) +/** The admin has no MFA themselves: the change is held back until they add it. */ +export const rowAdminNeedsOwnMfa = row({ policy: { ...off, self: 'off' } }) +/** Scheduled: the date, the countdown, who is pending, and Remind. */ +export const rowScheduled = row({ policy: scheduled, pending: pendingMembers }) +/** Past the deadline: pending members have no access. */ +export const rowEnforced = row({ + policy: { ...off, policy: { enforceAt: NOW - 2 * DAY, setAt: NOW - 16 * DAY } }, + pending: pendingMembers.map((member) => ({ ...member, mfa: 'blocked' as const })) +}) +export const rowEveryoneSet = row({ + policy: { ...scheduled, manage: { available: true, pendingMembers: 0 } }, + pending: [] +}) +export const rowSaving = row({ policy: scheduled, pending: pendingMembers, busy: true }) +export const rowReminded = row({ + policy: scheduled, + pending: pendingMembers, + notice: { kind: 'reminded', recipients: 3, emailed: true } +}) +/** The server is in log mode: say plainly that no email went out. */ +export const rowRemindedNoEmail = row({ + policy: scheduled, + pending: pendingMembers, + notice: { kind: 'reminded', recipients: 3, emailed: false } +}) +export const rowError = row({ + policy: scheduled, + pending: pendingMembers, + notice: { kind: 'error', message: 'Couldn’t save the change. Try again.' } +}) diff --git a/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx b/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx new file mode 100644 index 00000000000..5fac6fbd8b9 --- /dev/null +++ b/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx @@ -0,0 +1,48 @@ +import { InlineError } from '@/components/ui/inline-error' +import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' +import { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { mfaCountdownLabel, mfaDeadlineDate } from './team-mfa-copy' + +export type TeamMfaBannerProps = { + teamName: string + /** Epoch ms from which the team is closed to members without MFA. */ + enforceAt: number + now: number + setupUrl: string + onSetUp: () => void +} + +/** + * Shown to a member whose team requires MFA and who has none yet, until the deadline: how long + * is left and the way to set it up. After the deadline the blocked screen takes over. + */ +export function TeamMfaBanner({ + teamName, + enforceAt, + now, + setupUrl, + onSetUp +}: TeamMfaBannerProps): React.JSX.Element { + const t = useTranslate() + const locale = useIntlLocale() + return ( + + {t('auto.components.teamMfa.setUp', 'Set up MFA')} + + } + /> + ) +} diff --git a/src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx b/src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx new file mode 100644 index 00000000000..b2ea07b51ce --- /dev/null +++ b/src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx @@ -0,0 +1,93 @@ +import { Loader2, ShieldAlert } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' +import { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { mfaDeadlineDate } from './team-mfa-copy' + +export type TeamMfaBlockedScreenProps = { + teamName: string + enforceAt: number + setupUrl: string + /** A re-check is running (after "I've set it up", or on returning from the browser). */ + checking: boolean + /** The last re-check still found no MFA. */ + stillMissing: boolean + onSetUp: () => void + onRecheck: () => void + /** Switch to the personal account, which the team's policy does not affect. */ + onUsePersonal?: () => void +} + +/** + * In place of a team's content once its MFA deadline has passed for a member without MFA: what + * happened, the one thing to do, and a way to keep working outside the team meanwhile. + */ +export function TeamMfaBlockedScreen({ + teamName, + enforceAt, + setupUrl, + checking, + stillMissing, + onSetUp, + onRecheck, + onUsePersonal +}: TeamMfaBlockedScreenProps): React.JSX.Element { + const t = useTranslate() + const locale = useIntlLocale() + return ( +
    +
    + +
    +
    +

    + {t( + 'auto.components.teamMfa.blockedTitle', + 'Set up two-factor authentication to use {{value0}}', + { value0: teamName } + )} +

    +

    + {t( + 'auto.components.teamMfa.blockedBody', + '{{value0}} has required it for all members since {{value1}}. Your workspaces and files are safe, and open again as soon as you add an authenticator app.', + { value0: teamName, value1: mfaDeadlineDate(enforceAt, locale) } + )} +

    +
    +
    + + {t('auto.components.teamMfa.setUp', 'Set up MFA')} + + +
    +

    + {stillMissing && !checking + ? t( + 'auto.components.teamMfa.stillMissing', + 'Your account still has no two-factor authentication. Finish the setup in your browser, then try again.' + ) + : null} +

    + {onUsePersonal ? ( + + ) : null} +
    + ) +} diff --git a/src/renderer/src/components/team-mfa/team-mfa-copy.ts b/src/renderer/src/components/team-mfa/team-mfa-copy.ts new file mode 100644 index 00000000000..417d0974d06 --- /dev/null +++ b/src/renderer/src/components/team-mfa/team-mfa-copy.ts @@ -0,0 +1,59 @@ +// Copy and small rules shared by the MFA banner, the blocked screen and the Enterprise row. Pure, +// so the views and their tests agree on every boundary. +import type { Translate } from '@/i18n/use-translate' +import type { OrcaTeamMfaGrace, OrcaTeamMfaPolicy } from '../../../../shared/orca-team-mfa-policy' + +const DAY_MS = 24 * 60 * 60 * 1000 + +/** Whole days left, rounded up; 0 once the deadline has passed. Matches the server and the emails. */ +export function mfaDaysLeft(enforceAt: number, now: number): number { + return Math.max(0, Math.ceil((enforceAt - now) / DAY_MS)) +} + +/** + * What the person should see for this team: + * - `banner`: the team requires MFA, they have none, and there is still time. + * - `blocked`: the deadline passed; the team is closed to them until they set it up. + * - `none`: nothing to show (no policy, they have MFA, or their state is unknown). + * Only the server's `blocked` blocks: the desktop never decides that from the clock. + */ +export function teamMfaSurface(policy: OrcaTeamMfaPolicy | null): 'none' | 'banner' | 'blocked' { + if (!policy?.policy) { + return 'none' + } + if (policy.self === 'blocked') { + return 'blocked' + } + return policy.self === 'pending' ? 'banner' : 'none' +} + +/** "6 days left", "1 day left", "Due now". i18next plurals, never ternaries on the count. */ +export function mfaCountdownLabel(enforceAt: number, now: number, t: Translate): string { + const days = mfaDaysLeft(enforceAt, now) + if (days <= 0) { + return t('auto.components.teamMfa.dueNow', 'Due now') + } + return t('auto.components.teamMfa.daysLeft', '{{count}} days left', { + count: days, + defaultValue_one: '{{count}} day left' + }) +} + +export function mfaDeadlineDate(enforceAt: number, locale: string): string { + return new Intl.DateTimeFormat(locale, { month: 'long', day: 'numeric', year: 'numeric' }).format( + enforceAt + ) +} + +export function mfaGraceLabel(grace: OrcaTeamMfaGrace, t: Translate): string { + switch (grace) { + case 'now': + return t('auto.components.teamMfa.graceNow', 'Immediately') + case 7: + return t('auto.components.teamMfa.grace7', 'In 7 days') + case 14: + return t('auto.components.teamMfa.grace14', 'In 14 days') + case 30: + return t('auto.components.teamMfa.grace30', 'In 30 days') + } +} diff --git a/src/renderer/src/components/team-mfa/team-mfa.test.tsx b/src/renderer/src/components/team-mfa/team-mfa.test.tsx new file mode 100644 index 00000000000..90a77e21667 --- /dev/null +++ b/src/renderer/src/components/team-mfa/team-mfa.test.tsx @@ -0,0 +1,203 @@ +// @vitest-environment happy-dom +import { cleanup, fireEvent, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { translate } from '@/i18n/i18n' +import type { OrcaTeamMfaPolicy } from '../../../../shared/orca-team-mfa-policy' +import { RequireMfaRow, type RequireMfaRowProps } from './RequireMfaRow' +import { TeamMfaBanner } from './TeamMfaBanner' +import { TeamMfaBlockedScreen } from './TeamMfaBlockedScreen' +import { mfaCountdownLabel, mfaDaysLeft, teamMfaSurface } from './team-mfa-copy' + +afterEach(cleanup) + +const DAY = 86_400_000 +const NOW = Date.UTC(2026, 10, 18, 15) +const setupUrl = 'https://cloud.orca.dev/v1/account/security' + +const policy = (over: Partial = {}): OrcaTeamMfaPolicy => ({ + policy: { enforceAt: NOW + 6 * DAY, setAt: NOW - DAY }, + self: 'pending', + setupUrl, + ...over +}) + +describe('countdown', () => { + it('rounds up to whole days and stops at zero', () => { + expect(mfaDaysLeft(NOW + 7 * DAY, NOW)).toBe(7) + expect(mfaDaysLeft(NOW + 6 * DAY + 1, NOW)).toBe(7) + expect(mfaDaysLeft(NOW + DAY / 2, NOW)).toBe(1) + expect(mfaDaysLeft(NOW, NOW)).toBe(0) + expect(mfaDaysLeft(NOW - DAY, NOW)).toBe(0) + }) + + it('reads as days left, one day left, then due now', () => { + expect(mfaCountdownLabel(NOW + 6 * DAY, NOW, translate)).toBe('6 days left') + expect(mfaCountdownLabel(NOW + DAY, NOW, translate)).toBe('1 day left') + expect(mfaCountdownLabel(NOW, NOW, translate)).toBe('Due now') + }) +}) + +describe('what the member sees', () => { + it('is the banner while pending and the blocked screen only on the server’s word', () => { + expect(teamMfaSurface(policy())).toBe('banner') + expect(teamMfaSurface(policy({ self: 'blocked' }))).toBe('blocked') + // Past the deadline by the local clock, but the server still says pending: not blocked. + expect( + teamMfaSurface(policy({ policy: { enforceAt: NOW - DAY, setAt: NOW - 8 * DAY } })) + ).toBe('banner') + }) + + it('is nothing with MFA on, an unknown state, or no policy', () => { + expect(teamMfaSurface(policy({ self: 'on' }))).toBe('none') + expect(teamMfaSurface(policy({ self: 'unknown' }))).toBe('none') + expect(teamMfaSurface(policy({ policy: null, self: 'off' }))).toBe('none') + expect(teamMfaSurface(policy({ policy: null, self: 'blocked' }))).toBe('none') + expect(teamMfaSurface(null)).toBe('none') + }) +}) + +describe('banner', () => { + it('names the team, the countdown and the date, and offers the setup action', () => { + const onSetUp = vi.fn() + const { container, getByRole } = render( + + ) + expect(container.textContent).toContain('Acme requires two-factor authentication. 6 days left.') + expect(container.textContent).toContain('November 24, 2026') + fireEvent.click(getByRole('button', { name: 'Set up MFA' })) + expect(onSetUp).toHaveBeenCalledTimes(1) + }) +}) + +describe('blocked screen', () => { + const screen = (props: { checking?: boolean; stillMissing?: boolean } = {}) => { + const handlers = { onSetUp: vi.fn(), onRecheck: vi.fn(), onUsePersonal: vi.fn() } + const view = render( + + ) + return { ...view, ...handlers } + } + + it('says what to do, not a generic error, and keeps the personal account reachable', () => { + const view = screen() + expect(view.container.textContent).toContain('Set up two-factor authentication to use Acme') + expect(view.container.textContent).toContain('Your workspaces and files are safe') + fireEvent.click(view.getByRole('button', { name: 'Set up MFA' })) + fireEvent.click(view.getByRole('button', { name: 'I’ve set it up' })) + fireEvent.click(view.getByRole('button', { name: 'Use my personal account for now' })) + expect(view.onSetUp).toHaveBeenCalledTimes(1) + expect(view.onRecheck).toHaveBeenCalledTimes(1) + expect(view.onUsePersonal).toHaveBeenCalledTimes(1) + }) + + it('ignores a second re-check while one runs, and says when MFA is still missing', () => { + const checking = screen({ checking: true }) + fireEvent.click(checking.getByRole('button', { name: 'I’ve set it up' })) + expect(checking.onRecheck).not.toHaveBeenCalled() + cleanup() + expect(screen({ stillMissing: true }).container.textContent).toContain( + 'Your account still has no two-factor authentication' + ) + }) +}) + +describe('Require MFA row', () => { + const manage = { available: true, pendingMembers: 2 } + const row = (props: Partial = {}) => { + const handlers = { + onRequire: vi.fn(), + onTurnOff: vi.fn(), + onRemind: vi.fn(), + onSetUpOwn: vi.fn() + } + const view = render( + + ) + return { ...view, ...handlers } + } + + it('requires MFA with the chosen grace period, 14 days by default', () => { + const view = row() + fireEvent.click(view.getByRole('button', { name: 'Require MFA' })) + expect(view.onRequire).toHaveBeenCalledWith(14) + }) + + it('holds the change back from an admin without MFA, and points them to setup', () => { + const view = row({ policy: policy({ policy: null, self: 'off', manage }) }) + fireEvent.click(view.getByRole('button', { name: 'Require MFA' })) + expect(view.onRequire).not.toHaveBeenCalled() + expect(view.container.textContent).toContain( + 'Set up two-factor authentication on your own account first' + ) + fireEvent.click(view.getByRole('button', { name: 'Set up MFA' })) + expect(view.onSetUpOwn).toHaveBeenCalledTimes(1) + }) + + it('holds turning it off back from an admin without MFA too', () => { + const view = row({ policy: policy({ self: 'pending', manage }) }) + fireEvent.click(view.getByRole('button', { name: 'Stop requiring' })) + expect(view.onTurnOff).not.toHaveBeenCalled() + }) + + it('shows the date, who is pending, and reminds everyone or one member', () => { + const view = row({ + policy: policy({ self: 'on', manage }), + pending: [ + { userId: 'u-ada', email: 'ada@acme.dev', displayName: 'Ada Lovelace', mfa: 'pending' }, + { userId: null, email: 'linus@acme.dev', mfa: 'pending' } + ] + }) + expect(view.container.textContent).toContain('Required from November 24, 2026. 6 days left.') + expect(view.container.textContent).toContain('2 members still need it') + fireEvent.click(view.getByRole('button', { name: 'Remind everyone' })) + expect(view.onRemind).toHaveBeenLastCalledWith() + // A member who never signed in to Orca has no id to remind by; only Ada gets a button. + const single = view.getAllByRole('button', { name: 'Remind' }) + expect(single).toHaveLength(1) + fireEvent.click(single[0]!) + expect(view.onRemind).toHaveBeenLastCalledWith('u-ada') + }) + + it('says members have no access once the deadline passed', () => { + const view = row({ + policy: policy({ + self: 'on', + manage, + policy: { enforceAt: NOW - DAY, setAt: NOW - 8 * DAY } + }), + pending: [{ userId: 'u-ada', email: 'ada@acme.dev', mfa: 'blocked' }] + }) + expect(view.container.textContent).toContain('Required since November 17, 2026') + expect(view.container.textContent).toContain('No access') + }) + + it('says plainly when a reminder was recorded but not emailed', () => { + const view = row({ + policy: policy({ self: 'on', manage }), + notice: { kind: 'reminded', recipients: 2, emailed: false } + }) + expect(view.container.textContent).toContain('nothing was sent') + expect(view.container.textContent).not.toContain('Reminder sent') + }) +}) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 069072a01e9..1b6b7909019 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -21700,6 +21700,45 @@ }, "NewWorkspaceComposerFooter": { "create": "Create" + }, + "teamMfa": { + "dueNow": "Due now", + "daysLeft_one": "{{count}} day left", + "daysLeft_other": "{{count}} days left", + "graceNow": "Immediately", + "grace7": "In 7 days", + "grace14": "In 14 days", + "grace30": "In 30 days", + "bannerTitle": "{{value0}} requires two-factor authentication. {{value1}}.", + "bannerBody": "Set it up by {{value0}}. After that you can’t use this team’s workspaces until you do.", + "setUp": "Set up MFA", + "blockedTitle": "Set up two-factor authentication to use {{value0}}", + "blockedBody": "{{value0}} has required it for all members since {{value1}}. Your workspaces and files are safe, and open again as soon as you add an authenticator app.", + "recheck": "I’ve set it up", + "stillMissing": "Your account still has no two-factor authentication. Finish the setup in your browser, then try again.", + "usePersonal": "Use my personal account for now", + "rowTitle": "Require two-factor authentication", + "rowOff": "Members without it lose access to this team’s workspaces after the date you pick, until they set it up. They get an email now and reminders before the date.", + "rowEnforced": "Required since {{value0}}. Members without it can’t use this team until they set it up.", + "rowScheduled": "Required from {{value0}}. {{value1}}.", + "graceLabel": "When to start requiring it", + "require": "Require MFA", + "turnOff": "Stop requiring", + "ownMfaTitle": "Set up two-factor authentication on your own account first", + "ownMfaBody": "Only someone who already has it can change this, so nobody locks the team out.", + "nowWarning_one": "{{count}} member doesn’t have it yet and will lose access to this team right away.", + "nowWarning_other": "{{count}} members don’t have it yet and will lose access to this team right away.", + "allSet": "Every member has it set up.", + "pendingCount_one": "{{count}} member still needs it", + "pendingCount_other": "{{count}} members still need it", + "remindAll": "Remind everyone", + "pendingList": "Members without MFA", + "memberBlocked": "No access", + "memberPending": "Pending", + "remindOne": "Remind", + "reminded_one": "Reminder sent to {{count}} member.", + "reminded_other": "Reminder sent to {{count}} members.", + "remindedNoEmail": "Reminder recorded, but email delivery is off on this server, so nothing was sent." } }, "i18n": { diff --git a/src/renderer/src/web/preload-api/web-orca-profiles-api.ts b/src/renderer/src/web/preload-api/web-orca-profiles-api.ts index 99d7016d68b..32bd36d44d1 100644 --- a/src/renderer/src/web/preload-api/web-orca-profiles-api.ts +++ b/src/renderer/src/web/preload-api/web-orca-profiles-api.ts @@ -66,6 +66,10 @@ export function createWebOrcaProfilesApi(): Partial { auth: await webOrcaProfileAuthStatus() }), accountMfa: async () => ({ status: 'unconfigured' }), + teamMfaPolicy: async () => ({ status: 'unconfigured' }), + teamMfaPolicySet: async () => ({ status: 'unconfigured' }), + teamMfaPending: async () => ({ status: 'unconfigured' }), + teamMfaRemind: async () => ({ status: 'unconfigured' }), orgMembersList: async () => ({ status: 'unconfigured' }), orgMemberInvite: async () => ({ status: 'unconfigured' }), orgInviteRevoke: async () => ({ status: 'unconfigured' }), diff --git a/src/shared/orca-team-mfa-policy.ts b/src/shared/orca-team-mfa-policy.ts new file mode 100644 index 00000000000..7e86956b4ed --- /dev/null +++ b/src/shared/orca-team-mfa-policy.ts @@ -0,0 +1,66 @@ +// A team's "require MFA" policy (Enterprise). The auth service owns it; the desktop reads the +// deadline and the person's own state for the banner and the blocked screen, and owners and +// admins set it from Settings, Enterprise. + +/** Enforce now, or after a grace period in days. Mirrors the server's fixed choices. */ +export const ORCA_TEAM_MFA_GRACE_CHOICES = ['now', 7, 14, 30] as const +export type OrcaTeamMfaGrace = (typeof ORCA_TEAM_MFA_GRACE_CHOICES)[number] + +/** + * The person's own state in this team: + * - `pending`: the team requires MFA, they have none, the deadline has not passed. + * - `blocked`: the deadline passed; the team's workspaces and settings are closed to them. + * - `unknown`: the identity provider did not say; never treated as blocked. + */ +export type OrcaTeamMfaSelfState = 'on' | 'off' | 'pending' | 'blocked' | 'unknown' + +export type OrcaTeamMfaPolicy = { + /** Null when the team has no policy in force. */ + policy: { enforceAt: number; setAt: number } | null + self: OrcaTeamMfaSelfState + /** The account's security page, on Orca Cloud's own origin (checked in main). */ + setupUrl: string + /** Owners and admins only. */ + manage?: { + /** The team's plan includes MFA enforcement. */ + available: boolean + pendingMembers: number + /** A stored policy the plan no longer covers: it enforces nothing. */ + inactiveEnforceAt?: number + } +} + +export type OrcaTeamMfaPendingMember = { + userId: string | null + email: string + displayName?: string + mfa: 'pending' | 'blocked' | 'off' +} + +type Unavailable = + | { status: 'unconfigured' | 'reconnect-required' | 'unsupported' | 'forbidden' | 'rate-limited' } + | { status: 'failed'; error: string } + +export type OrcaTeamMfaPolicyResult = ({ status: 'ok' } & OrcaTeamMfaPolicy) | Unavailable + +export type OrcaTeamMfaPolicySetResult = + | { status: 'ok'; policy: { enforceAt: number; setAt: number } | null; pendingMembers: number } + /** The person changing the policy has no MFA themselves; the policy read has the setup link. */ + | { status: 'actor-needs-mfa' } + /** The team's plan does not include MFA enforcement. */ + | { status: 'not-entitled' } + | Unavailable + +export type OrcaTeamMfaPendingResult = + | { status: 'ok'; members: OrcaTeamMfaPendingMember[] } + | Unavailable + +export type OrcaTeamMfaRemindResult = + /** `delivery: 'log'` means the server recorded the reminder but sent no email. */ + | { status: 'ok'; recipients: number; delivery: 'log' | 'test-inbox' | 'unknown' } + | { status: 'no-policy' | 'not-found' } + | Unavailable + +export type OrcaTeamMfaPolicyArgs = { orgId: string } +export type OrcaTeamMfaPolicySetArgs = { orgId: string; enforce: OrcaTeamMfaGrace | 'off' } +export type OrcaTeamMfaRemindArgs = { orgId: string; userId?: string } From 62c606c4060dfa05b9fd9b8ce588812bf5f45035 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 20:43:36 -0800 Subject: [PATCH 04/28] feat(cloud): wire the team MFA banner, setup screen and mfa_required refusal into cloud workspaces and the team page --- .../hosted-sandbox-config.test.ts | 20 ++++- .../hosted-sandbox/hosted-sandbox-config.ts | 22 ++++++ .../billing/team/TeamDialogHost.tsx | 3 + .../components/billing/team/TeamPageView.tsx | 3 + .../cloud-workspaces/CloudWorkspacesHome.tsx | 14 ++++ .../CloudWorkspacesStates.tsx | 2 +- .../cloud-workspace-errors.ts | 14 ++++ .../src/components/team-mfa/TeamMfaGate.tsx | 77 +++++++++++++++++++ .../src/components/team-mfa/team-mfa.test.tsx | 13 ++++ .../team-mfa/use-team-mfa-policy.ts | 70 +++++++++++++++++ src/renderer/src/i18n/locales/en.json | 3 +- 11 files changed, 238 insertions(+), 3 deletions(-) create mode 100644 src/renderer/src/components/team-mfa/TeamMfaGate.tsx create mode 100644 src/renderer/src/components/team-mfa/use-team-mfa-policy.ts diff --git a/src/main/hosted-sandbox/hosted-sandbox-config.test.ts b/src/main/hosted-sandbox/hosted-sandbox-config.test.ts index 2ff15926d7a..143960b1ab1 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-config.test.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-config.test.ts @@ -12,7 +12,7 @@ import { unlinkOrcaProfileFromCloud } from '../orca-profiles/cloud-auth/profile-cloud-index' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' -import { getHostedSandboxConfig } from './hosted-sandbox-config' +import { getHostedSandboxConfig, isMfaRequiredRefusal } from './hosted-sandbox-config' const state = { dir: '' } installFakeAppEnvironment({ getPath: () => state.dir }) @@ -118,3 +118,21 @@ describe('getHostedSandboxConfig sandbox tokens', () => { expect(claims(await b.getAccessToken()).sub).toBe('user-b') }) }) + +describe('isMfaRequiredRefusal', () => { + it('recognizes the team MFA refusal and leaves the body readable', async () => { + const response = Response.json( + { error: 'mfa_required', orgId: 'org_1', enforceAt: 5 }, + { status: 403 } + ) + expect(await isMfaRequiredRefusal(response)).toBe(true) + expect(((await response.json()) as { orgId: string }).orgId).toBe('org_1') + }) + + it('is false for other refusals and for bodies that are not JSON', async () => { + for (const body of [{ error: 'not_a_member' }, { error: 'sandbox_not_entitled' }, {}, null]) { + expect(await isMfaRequiredRefusal(Response.json(body, { status: 403 }))).toBe(false) + } + expect(await isMfaRequiredRefusal(new Response('', { status: 403 }))).toBe(false) + }) +}) diff --git a/src/main/hosted-sandbox/hosted-sandbox-config.ts b/src/main/hosted-sandbox/hosted-sandbox-config.ts index a85ed77e2b7..973ab6596e5 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-config.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-config.ts @@ -22,6 +22,19 @@ export type HostedSandboxConfig = { invalidateAccessToken?: () => void } +/** `reason` on the provider error when the team's MFA policy refused the token. */ +export const MFA_REQUIRED_REASON = 'mfa_required' + +/** Reads a copy of the body, so the caller can still read the response. */ +export async function isMfaRequiredRefusal(response: Response): Promise { + try { + const body = (await response.clone().json()) as { error?: unknown } | null + return body?.error === MFA_REQUIRED_REASON + } catch { + return false + } +} + const SandboxTokenBody = z.object({ sandboxToken: z.string().min(1).max(8192), expiresAt: z.number().int().positive() @@ -161,6 +174,15 @@ async function mintSandboxToken( redirect: 'error', signal: AbortSignal.timeout(15_000) }) + if (response.status === 403 && (await isMfaRequiredRefusal(response))) { + // The team requires MFA and this person has none past the deadline. Signing in again + // would not help, so this is not a session error: the reason lets the UI show setup. + throw new EnvironmentProviderError( + 'unauthorized', + 'Your team requires two-factor authentication. Set it up to use its cloud workspaces.', + MFA_REQUIRED_REASON + ) + } if (response.status === 401 || response.status === 403) { throw new OrcaCloudRequestError(response.status) } diff --git a/src/renderer/src/components/billing/team/TeamDialogHost.tsx b/src/renderer/src/components/billing/team/TeamDialogHost.tsx index 8b17fb6737d..f84ece0adf5 100644 --- a/src/renderer/src/components/billing/team/TeamDialogHost.tsx +++ b/src/renderer/src/components/billing/team/TeamDialogHost.tsx @@ -1,3 +1,4 @@ +import { useTeamMfaGate } from '@/components/team-mfa/TeamMfaGate' import { useCallback, useEffect, useRef, useState } from 'react' import { toast } from 'sonner' import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog' @@ -36,6 +37,7 @@ export function TeamPageBody({ const cloud = authStatus?.cloud const orgId = cloud?.activeOrgId ?? null const roster = useOrgRoster(orgId) + const mfa = useTeamMfaGate() const billing = useOrcaBillingStatus(true) const [userRefreshing, setUserRefreshing] = useState(false) const [billingBusy, setBillingBusy] = useState(false) @@ -183,6 +185,7 @@ export function TeamPageBody({ <> + {props.mfaNotice ?? null}
    diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index fb899cecf65..d2436fcea66 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -4,6 +4,7 @@ import { useHomeWorkspaces } from './cloud-workspace-local-titles' import React, { useCallback, useEffect, useMemo, useState } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store' +import { useTeamMfaGate } from '@/components/team-mfa/TeamMfaGate' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/class-names' import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' @@ -121,6 +122,10 @@ export function CloudWorkspacesHome({ archivedOn: filters.archived, enabled: Boolean(cloud) }) + // The team's MFA requirement: a countdown banner before the deadline, the setup screen after. + const mfa = useTeamMfaGate({ + forceBlocked: state.status === 'error' && state.reason === 'mfa_required' + }) const showFilters = shouldShowCloudHomeFilters(all.length, filters, Boolean(orgId)) const { directory, canAdmin } = useMemberDirectory(orgId, all) const repos = useMemo( @@ -302,8 +307,17 @@ export function CloudWorkspacesHome({ archivedCount={archivedCount} /> + {mfa.banner ?
    {mfa.banner}
    : null} + + {mfa.blocked ? ( +
    {mfa.blocked}
    + ) : null} + )}
    + {/* The active team requires MFA and this person has none: a countdown, then + "no access". Renders nothing for almost everyone. */} + {layout.shouldMountTerminalWorkbench ? ( diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index d2436fcea66..fb899cecf65 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -4,7 +4,6 @@ import { useHomeWorkspaces } from './cloud-workspace-local-titles' import React, { useCallback, useEffect, useMemo, useState } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store' -import { useTeamMfaGate } from '@/components/team-mfa/TeamMfaGate' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/class-names' import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' @@ -122,10 +121,6 @@ export function CloudWorkspacesHome({ archivedOn: filters.archived, enabled: Boolean(cloud) }) - // The team's MFA requirement: a countdown banner before the deadline, the setup screen after. - const mfa = useTeamMfaGate({ - forceBlocked: state.status === 'error' && state.reason === 'mfa_required' - }) const showFilters = shouldShowCloudHomeFilters(all.length, filters, Boolean(orgId)) const { directory, canAdmin } = useMemberDirectory(orgId, all) const repos = useMemo( @@ -307,17 +302,8 @@ export function CloudWorkspacesHome({ archivedCount={archivedCount} /> - {mfa.banner ?
    {mfa.banner}
    : null} - - {mfa.blocked ? ( -
    {mfa.blocked}
    - ) : null} - )}
    - {/* The active team requires MFA and this person has none: a countdown, then - "no access". Renders nothing for almost everyone. */} - {layout.shouldMountTerminalWorkbench ? ( diff --git a/src/renderer/src/components/sidebar/index.tsx b/src/renderer/src/components/sidebar/index.tsx index 829cc4890ad..5b22a0a219c 100644 --- a/src/renderer/src/components/sidebar/index.tsx +++ b/src/renderer/src/components/sidebar/index.tsx @@ -22,6 +22,7 @@ import { lazyWithRetry } from '@/app-shell/startup/lazy-with-retry' import { LocalGitToolchainScanBanner } from './LocalGitToolchainScanBanner' import { SeveredTerminalDaemonBanner } from './SeveredTerminalDaemonBanner' import { StalledTerminalDaemonBanner } from './StalledTerminalDaemonBanner' +import { TeamMfaSidebarBanner } from '@/components/team-mfa/TeamMfaAppBanner' import { StartupWorktreeRefreshStatus } from './StartupWorktreeRefreshStatus' // Load the shared Activity badge/list pipeline after the sidebar shell. @@ -193,6 +194,7 @@ function Sidebar({ /> + : null} > diff --git a/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx b/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx index eb5207f10d7..61e8216329e 100644 --- a/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx @@ -37,17 +37,32 @@ const banner = (daysLeft: number, frameWidth = width) => export const bannerTwoWeeks = banner(14) export const bannerOneDay = banner(1) export const bannerNarrow = banner(6, 420) -/** The app-level line once the deadline has passed. */ -export const bannerBlocked = frame( - -) +// ---- Sidebar banner stack: the app-level reminder, at sidebar widths ---- + +const sidebar = (daysLeft: number, sidebarWidth: number) => + defineFixture({ + width: sidebarWidth, + render: () => ( +
    + +
    + ) + }) + +export const sidebarTwoWeeks = sidebar(14, 280) +export const sidebarOneDay = sidebar(1, 280) +/** After the deadline: no access until set up. */ +export const sidebarBlocked = sidebar(-2, 280) +/** The narrowest sidebar. */ +export const sidebarBlockedNarrow = sidebar(-2, 220) // ---- Blocked screen: after the deadline ---- diff --git a/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx b/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx index e9cb6df591a..a7b881aaab3 100644 --- a/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx @@ -1,13 +1,16 @@ import { useTeamMfaGate } from './TeamMfaGate' /** - * The app-level MFA notice for the active team: a countdown while there is still time, and "no - * access until you set it up" after the deadline. Renders nothing for a personal account, a team - * with no policy, or a member who already has MFA, which is almost everyone. + * The MFA notice in the sidebar's banner stack, for the active team: a countdown while there is + * still time, and "no access until you set it up" after the deadline. Renders nothing for a + * personal account, a team with no policy, or a member who already has MFA, which is almost + * everyone. + * + * The sidebar can be collapsed, so this is a reminder, not the enforcement surface: a refused + * team resource shows TeamMfaRefused in its own place whether or not the sidebar is visible. */ -export function TeamMfaAppBanner({ className }: { className?: string }): React.JSX.Element | null { - const { appBanner } = useTeamMfaGate() - return appBanner ?
    {appBanner}
    : null +export function TeamMfaSidebarBanner(): React.JSX.Element | null { + return useTeamMfaGate().sidebarBanner } /** diff --git a/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx b/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx index 6958c788852..6f6fa2055e3 100644 --- a/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx @@ -1,4 +1,6 @@ +import { ShieldAlert } from 'lucide-react' import { InlineError } from '@/components/ui/inline-error' +import { cn } from '@/lib/class-names' import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { mfaCountdownLabel, mfaDeadlineDate } from './team-mfa-copy' @@ -12,6 +14,8 @@ export type TeamMfaBannerProps = { onSetUp: () => void /** The deadline has passed and the team is closed to this person until they set MFA up. */ blocked?: boolean + /** `sidebar`: the narrow stacked layout of the sidebar's banner stack. */ + variant?: 'inline' | 'sidebar' className?: string } @@ -26,44 +30,74 @@ export function TeamMfaBanner({ setupUrl, onSetUp, blocked = false, + variant = 'inline', className }: TeamMfaBannerProps): React.JSX.Element { const t = useTranslate() const locale = useIntlLocale() + const title = blocked + ? t( + 'auto.components.teamMfa.bannerBlockedTitle', + '{{value0}} requires two-factor authentication', + { value0: teamName } + ) + : t( + 'auto.components.teamMfa.bannerTitle', + '{{value0}} requires two-factor authentication. {{value1}}.', + { value0: teamName, value1: mfaCountdownLabel(enforceAt, now, t) } + ) + const detail = blocked + ? t( + 'auto.components.teamMfa.bannerBlockedBody', + 'You can’t use this team’s workspaces until you set it up. Your personal account is not affected.' + ) + : t( + 'auto.components.teamMfa.bannerBody', + 'Set it up by {{value0}}. After that you can’t use this team’s workspaces until you do.', + { value0: mfaDeadlineDate(enforceAt, locale) } + ) + const action = ( + + {t('auto.components.teamMfa.setUp', 'Set up MFA')} + + ) + if (variant === 'sidebar') { + // Same shape as the other banners in the sidebar stack (StalledTerminalDaemonBanner): the + // column is narrow, so the action sits under the text. + return ( +
    +
    +
    +
    + ) + } return ( - {t('auto.components.teamMfa.setUp', 'Set up MFA')} - - } + title={title} + detail={detail} + action={action} /> ) } diff --git a/src/renderer/src/components/team-mfa/TeamMfaGate.tsx b/src/renderer/src/components/team-mfa/TeamMfaGate.tsx index fada7961372..21c4ab21f48 100644 --- a/src/renderer/src/components/team-mfa/TeamMfaGate.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfaGate.tsx @@ -19,8 +19,8 @@ import { useTeamMfaPolicy } from './use-team-mfa-policy' export function useTeamMfaGate(options: { forceBlocked?: boolean } = {}): { banner: React.JSX.Element | null blocked: React.JSX.Element | null - /** One line for the app-level notice: the countdown, or "no access" once blocked. */ - appBanner: React.JSX.Element | null + /** The sidebar notice: the countdown, or "no access" once blocked. */ + sidebarBanner: React.JSX.Element | null } { const cloud = useAppStore((state) => state.orcaProfileAuthStatus?.cloud) const selectOrg = useAppStore((state) => state.selectOrcaProfileOrg) @@ -31,7 +31,7 @@ export function useTeamMfaGate(options: { forceBlocked?: boolean } = {}): { const [stillMissing, setStillMissing] = useState(false) if (!orgId || !policy?.policy) { - return { banner: null, blocked: null, appBanner: null } + return { banner: null, blocked: null, sidebarBanner: null } } const surface = teamMfaSurface(policy) const openSetup = (): void => { @@ -41,8 +41,9 @@ export function useTeamMfaGate(options: { forceBlocked?: boolean } = {}): { // The server's refusal wins over a policy read that has not caught up, unless that read now // says the member has MFA (they just set it up; the next request will go through). const isBlocked = surface === 'blocked' || (options.forceBlocked === true && policy.self !== 'on') - const line = (blocked: boolean): React.JSX.Element => ( + const line = (blocked: boolean, variant: 'inline' | 'sidebar' = 'inline'): React.JSX.Element => ( { setupUrl={setupUrl} onSetUp={() => {}} blocked + variant="sidebar" /> ) + // An alert once blocked; a quiet status while there is still time. + expect(container.querySelector('[data-team-mfa-banner="blocked"]')?.getAttribute('role')).toBe( + 'alert' + ) expect(container.textContent).toContain('Acme requires two-factor authentication') expect(container.textContent).toContain('until you set it up') expect(container.textContent).toContain('Your personal account is not affected') From 70888d86aaae388a4e00cdbd9ab49cfab3cc5a7a Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 20:53:17 -0800 Subject: [PATCH 07/28] feat(cloud): MFA notice escalates in the last three days, a one-time toast per deadline, badge in the members list --- .../billing/team/TeamMemberList.test.tsx | 2 + .../billing/team/TeamMemberList.tsx | 12 +-- .../components/team-mfa/TeamMfa.fixture.tsx | 22 ++++++ .../components/team-mfa/TeamMfaAppBanner.tsx | 55 +++++++++++++- .../src/components/team-mfa/TeamMfaBanner.tsx | 35 +++++++-- .../src/components/team-mfa/TeamMfaGate.tsx | 8 +- .../src/components/team-mfa/team-mfa-copy.ts | 57 ++++++++++++++ .../src/components/team-mfa/team-mfa.test.tsx | 75 ++++++++++++++++++- src/renderer/src/i18n/locales/en.json | 4 + 9 files changed, 252 insertions(+), 18 deletions(-) diff --git a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx index 8448c9c81e6..961ad751716 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx @@ -81,6 +81,8 @@ it.each(['owner', 'admin'] as const)('shows the MFA column to an %s', (viewerRol container.querySelector(`[data-team-row="${key}"] [data-team-mfa]`)! expect(cell('member:u-neil').textContent).toBe('MFA on') expect(cell('member:u-grace').textContent).toBe('MFA due Nov 24') + // A small muted badge, not bare text. + expect(cell('member:u-neil').querySelector('[data-slot="badge"]')).not.toBeNull() // Invites keep an empty cell so the role column stays aligned. expect(cell('invite:alex@acme.dev').textContent).toBe('') }) diff --git a/src/renderer/src/components/billing/team/TeamMemberList.tsx b/src/renderer/src/components/billing/team/TeamMemberList.tsx index b464697560e..822d366283c 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.tsx @@ -25,7 +25,6 @@ import { SelectValue } from '@/components/ui/select' import { LoadingSpinner } from '@/components/LoadingSpinner' -import { cn } from '@/lib/class-names' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import type { OrcaOrgMember, OrcaOrgRole } from '../../../../../shared/orca-profiles' import { PersonAvatar } from './TeamAvatar' @@ -307,14 +306,11 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element { // Rendered for every row, invites included, so the role column stays aligned. - {row.kind === 'member' ? memberMfaLabel(row.member, locale, t) : null} + {row.kind === 'member' && memberMfaLabel(row.member, locale, t) ? ( + {memberMfaLabel(row.member, locale, t)} + ) : null} ) : null} {row.kind === 'member' ? ( diff --git a/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx b/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx index 61e8216329e..fd4509e29fe 100644 --- a/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx @@ -3,6 +3,7 @@ import type { OrcaTeamMfaPendingMember, OrcaTeamMfaPolicy } from '../../../../shared/orca-team-mfa-policy' +import { CloudToastCard } from '@/components/orca-cloud/cloud-toast-stack' import { RequireMfaRow, type RequireMfaRowProps } from './RequireMfaRow' import { TeamMfaBanner } from './TeamMfaBanner' import { TeamMfaBlockedScreen } from './TeamMfaBlockedScreen' @@ -58,12 +59,33 @@ const sidebar = (daysLeft: number, sidebarWidth: number) => }) export const sidebarTwoWeeks = sidebar(14, 280) +/** Three days or fewer: the warning look. */ +export const sidebarThreeDays = sidebar(3, 280) export const sidebarOneDay = sidebar(1, 280) /** After the deadline: no access until set up. */ export const sidebarBlocked = sidebar(-2, 280) /** The narrowest sidebar. */ export const sidebarBlockedNarrow = sidebar(-2, 220) +// ---- The one-time toast, for people who keep the sidebar collapsed ---- + +export const toast = frame( + , + 420 +) + // ---- Blocked screen: after the deadline ---- const blocked = (props: { checking?: boolean; stillMissing?: boolean; personal?: boolean }) => diff --git a/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx b/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx index a7b881aaab3..f2d02d290be 100644 --- a/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx @@ -1,3 +1,7 @@ +import { useEffect } from 'react' +import { hideCloudToast, showCloudToast } from '@/components/orca-cloud/cloud-toast-stack' +import { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { claimMfaToast, mfaDeadlineDate } from './team-mfa-copy' import { useTeamMfaGate } from './TeamMfaGate' /** @@ -10,7 +14,56 @@ import { useTeamMfaGate } from './TeamMfaGate' * team resource shows TeamMfaRefused in its own place whether or not the sidebar is visible. */ export function TeamMfaSidebarBanner(): React.JSX.Element | null { - return useTeamMfaGate().sidebarBanner + const gate = useTeamMfaGate() + const t = useTranslate() + const locale = useIntlLocale() + const toast = gate.pendingToast + const orgId = toast?.orgId + const enforceAt = toast?.enforceAt + // One toast per team and deadline, for people who keep the sidebar collapsed. Not tied to any + // workspace, so it shows wherever they are; the sidebar card stays as the lasting reminder. + useEffect(() => { + if (!toast || orgId === undefined || enforceAt === undefined) { + return + } + if (!claimMfaToast(readLocalStorage(), orgId, enforceAt)) { + return + } + const id = `team-mfa:${orgId}` + showCloudToast(id, { + priority: 'action', + lines: [ + { + key: 'mfa', + text: t('auto.components.teamMfa.toast', '{{value0}} requires MFA from {{value1}}.', { + value0: toast.teamName, + value1: mfaDeadlineDate(enforceAt, locale) + }), + action: { + label: t('auto.components.teamMfa.setUp', 'Set up MFA'), + primary: true, + // Opens the account page in the browser, so the chevron offers Copy link. + link: toast.setupUrl, + onClick: () => { + void window.api.shell.openUrl(toast.setupUrl) + hideCloudToast(id) + } + } + } + ] + }) + // Deliberately keyed on the team and deadline only: copy or locale changes must not re-show. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [orgId, enforceAt]) + return gate.sidebarBanner +} + +function readLocalStorage(): Storage | null { + try { + return window.localStorage + } catch { + return null + } } /** diff --git a/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx b/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx index 6f6fa2055e3..cd03511e892 100644 --- a/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx @@ -3,7 +3,8 @@ import { InlineError } from '@/components/ui/inline-error' import { cn } from '@/lib/class-names' import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' -import { mfaCountdownLabel, mfaDeadlineDate } from './team-mfa-copy' +import { BANNER_BODY_TEXT, BANNER_TONE } from '@/components/ui/banner-tone' +import { mfaCountdownLabel, mfaDeadlineDate, mfaSoonTitle, mfaUrgency } from './team-mfa-copy' export type TeamMfaBannerProps = { teamName: string @@ -35,7 +36,10 @@ export function TeamMfaBanner({ }: TeamMfaBannerProps): React.JSX.Element { const t = useTranslate() const locale = useIntlLocale() - const title = blocked + const urgency = mfaUrgency(enforceAt, now, blocked) + const title = urgency === 'soon' + ? mfaSoonTitle(teamName, enforceAt, now, t) + : blocked ? t( 'auto.components.teamMfa.bannerBlockedTitle', '{{value0}} requires two-factor authentication', @@ -67,10 +71,16 @@ export function TeamMfaBanner({ return (
    @@ -78,13 +88,24 @@ export function TeamMfaBanner({
    diff --git a/src/renderer/src/components/team-mfa/TeamMfaGate.tsx b/src/renderer/src/components/team-mfa/TeamMfaGate.tsx index 21c4ab21f48..b7cdf9657ef 100644 --- a/src/renderer/src/components/team-mfa/TeamMfaGate.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfaGate.tsx @@ -21,6 +21,8 @@ export function useTeamMfaGate(options: { forceBlocked?: boolean } = {}): { blocked: React.JSX.Element | null /** The sidebar notice: the countdown, or "no access" once blocked. */ sidebarBanner: React.JSX.Element | null + /** Set while the member still has time: what the one-time toast needs. */ + pendingToast: { orgId: string; teamName: string; enforceAt: number; setupUrl: string } | null } { const cloud = useAppStore((state) => state.orcaProfileAuthStatus?.cloud) const selectOrg = useAppStore((state) => state.selectOrcaProfileOrg) @@ -31,7 +33,7 @@ export function useTeamMfaGate(options: { forceBlocked?: boolean } = {}): { const [stillMissing, setStillMissing] = useState(false) if (!orgId || !policy?.policy) { - return { banner: null, blocked: null, sidebarBanner: null } + return { banner: null, blocked: null, sidebarBanner: null, pendingToast: null } } const surface = teamMfaSurface(policy) const openSetup = (): void => { @@ -56,6 +58,7 @@ export function useTeamMfaGate(options: { forceBlocked?: boolean } = {}): { return { banner: null, sidebarBanner: line(true, 'sidebar'), + pendingToast: null, blocked: ( | null, + orgId: string, + enforceAt: number +): boolean { + const key = mfaToastSeenKey(orgId, enforceAt) + try { + if (storage?.getItem(key) === '1') { + return false + } + storage?.setItem(key, '1') + } catch { + // Private mode or a full quota: showing it again next launch is the lesser problem. + } + return true +} + /** "6 days left", "1 day left", "Due now". i18next plurals, never ternaries on the count. */ export function mfaCountdownLabel(enforceAt: number, now: number, t: Translate): string { const days = mfaDaysLeft(enforceAt, now) diff --git a/src/renderer/src/components/team-mfa/team-mfa.test.tsx b/src/renderer/src/components/team-mfa/team-mfa.test.tsx index 482b037ca01..6a07012637c 100644 --- a/src/renderer/src/components/team-mfa/team-mfa.test.tsx +++ b/src/renderer/src/components/team-mfa/team-mfa.test.tsx @@ -6,7 +6,14 @@ import type { OrcaTeamMfaPolicy } from '../../../../shared/orca-team-mfa-policy' import { RequireMfaRow, type RequireMfaRowProps } from './RequireMfaRow' import { TeamMfaBanner } from './TeamMfaBanner' import { TeamMfaBlockedScreen } from './TeamMfaBlockedScreen' -import { mfaCountdownLabel, mfaDaysLeft, teamMfaSurface } from './team-mfa-copy' +import { + claimMfaToast, + mfaCountdownLabel, + mfaDaysLeft, + mfaSoonTitle, + mfaUrgency, + teamMfaSurface +} from './team-mfa-copy' import { describeError, describeInlineError } from '../cloud-workspaces/cloud-workspace-errors' afterEach(cleanup) @@ -239,3 +246,69 @@ describe('banner after the deadline', () => { expect(getByRole('button', { name: 'Set up MFA' })).toBeTruthy() }) }) + +describe('escalation', () => { + it('is quiet with more than three days left, a warning in the last three, blocked on the server', () => { + expect(mfaUrgency(NOW + 14 * DAY, NOW, false)).toBe('quiet') + expect(mfaUrgency(NOW + 3 * DAY + 1, NOW, false)).toBe('quiet') + expect(mfaUrgency(NOW + 3 * DAY, NOW, false)).toBe('soon') + expect(mfaUrgency(NOW + DAY, NOW, false)).toBe('soon') + // Past the deadline by the clock but not blocked by the server: still only a warning. + expect(mfaUrgency(NOW - DAY, NOW, false)).toBe('soon') + expect(mfaUrgency(NOW + 14 * DAY, NOW, true)).toBe('blocked') + }) + + it('names the days in the title once it is close', () => { + expect(mfaSoonTitle('Acme', NOW + 2 * DAY, NOW, translate)).toBe('Acme requires MFA in 2 days') + expect(mfaSoonTitle('Acme', NOW + DAY, NOW, translate)).toBe('Acme requires MFA in 1 day') + expect(mfaSoonTitle('Acme', NOW - 1, NOW, translate)).toBe('Acme requires MFA now') + }) + + it('marks the sidebar card with its urgency', () => { + const card = (daysLeft: number, blocked = false): string | null | undefined => + render( + {}} + blocked={blocked} + /> + ) + .container.querySelector('[data-team-mfa-banner]') + ?.getAttribute('data-team-mfa-banner') + expect(card(14)).toBe('quiet') + cleanup() + expect(card(2)).toBe('soon') + cleanup() + expect(card(-2, true)).toBe('blocked') + }) +}) + +describe('one-time toast', () => { + const memory = (): Pick => { + const map = new Map() + return { getItem: (key) => map.get(key) ?? null, setItem: (key, value) => void map.set(key, value) } + } + + it('shows once per team and deadline, and again when the date changes', () => { + const storage = memory() + expect(claimMfaToast(storage, 'org_1', 100)).toBe(true) + expect(claimMfaToast(storage, 'org_1', 100)).toBe(false) + expect(claimMfaToast(storage, 'org_1', 200)).toBe(true) + expect(claimMfaToast(storage, 'org_2', 100)).toBe(true) + }) + + it('shows rather than hides when storage is unavailable', () => { + expect(claimMfaToast(null, 'org_1', 100)).toBe(true) + const broken = { + getItem: () => { + throw new Error('denied') + }, + setItem: () => {} + } + expect(claimMfaToast(broken, 'org_1', 100)).toBe(true) + }) +}) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 8a8737a2325..817cc60f274 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -21712,6 +21712,10 @@ "bannerTitle": "{{value0}} requires two-factor authentication. {{value1}}.", "bannerBody": "Set it up by {{value0}}. After that you can’t use this team’s workspaces until you do.", "bannerBlockedTitle": "{{value0}} requires two-factor authentication", + "soonTitleNow": "{{value0}} requires MFA now", + "soonTitle_one": "{{value0}} requires MFA in {{count}} day", + "soonTitle_other": "{{value0}} requires MFA in {{count}} days", + "toast": "{{value0}} requires MFA from {{value1}}.", "bannerBlockedBody": "You can’t use this team’s workspaces until you set it up. Your personal account is not affected.", "setUp": "Set up MFA", "blockedTitle": "Set up two-factor authentication to use {{value0}}", From 25ba73d3286fc4f4f3b931634aa9373d73b42d16 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 21:47:06 -0800 Subject: [PATCH 08/28] fix(cloud): AUTH-ONLY-COPY-LINK Copy link only on sign-in pages Copy link (the split button's chevron) is for auth and sign-in pages, where people paste the URL into an incognito window. Billing, contact sales, help, support and the GitHub App install go back to plain buttons; the billing and App-install link-only IPCs are removed. --- src/main/billing/billing-hosted-links.ts | 21 ---- src/main/billing/billing-service.ts | 2 +- src/main/hosted-sandbox/hosted-account-ipc.ts | 10 -- .../hosted-github-link-ipc.test.ts | 25 ++--- .../profiles/orca-profile-billing-handlers.ts | 14 --- .../api/orca-cloud-workspace-bridge.ts | 1 - src/preload/api/orca-profile-api.ts | 5 - src/preload/api/orca-profiles-bridge.ts | 2 - .../components/billing/PaymentIssueNotice.tsx | 15 +-- .../components/billing/PlanBillingSection.tsx | 14 +-- .../components/billing/billing-link.test.ts | 56 ---------- .../src/components/billing/billing-link.ts | 35 ------ .../billing/checkout/CheckoutPanel.tsx | 22 +--- .../billing/checkout/use-checkout-flow.ts | 48 ++------- .../billing/plans/EnterprisePlanCard.tsx | 11 +- .../billing/plans/PlansDialogHost.tsx | 8 -- .../billing/plans/PlansView.test.tsx | 7 -- .../components/billing/plans/PlansView.tsx | 11 -- .../components/billing/plans/TeamPlanCard.tsx | 65 +++-------- .../components/billing/team/TeamPageView.tsx | 7 +- .../ProjectComboboxCloudAddProjectEntry.tsx | 23 +--- .../run-on/use-cloud-start-steps.ts | 4 +- .../copy-link-auth-only.test.tsx | 102 ++++++++++++++++++ .../CloudCapabilityOffActions.tsx | 9 +- .../CloudSetupPage.fixture.tsx | 3 +- .../orca-cloud-setup/CloudSetupPage.tsx | 2 +- .../orca-cloud-setup/use-cloud-setup-flow.ts | 14 +-- .../orca-cloud/CloudSetupNotices.tsx | 10 +- .../orca-cloud/cloud-toast-stack.tsx | 18 +--- .../VmBuildFailureActions.copy-links.test.tsx | 87 --------------- .../VmBuildFailureActions.tsx | 74 +++---------- .../VmBuildSheetCopyLinks.fixture.tsx | 58 ---------- src/renderer/src/i18n/locales/en.json | 4 +- .../orca-cloud/cloud-glossary-allowlist.json | 2 +- .../src/lib/orca-cloud/github-link-sources.ts | 16 +-- ...ca-cloud-workspace-store-git-setup.test.ts | 1 - .../orca-cloud-workspace-store-wake.test.ts | 1 - .../orca-cloud-workspace-store.test.ts | 1 - .../orca-cloud/use-orca-cloud-repo-access.ts | 22 +--- .../web/preload-api/web-orca-profiles-api.ts | 2 - .../hosted-sandbox/cloud-workspace-api.ts | 6 -- 41 files changed, 208 insertions(+), 630 deletions(-) delete mode 100644 src/main/billing/billing-hosted-links.ts delete mode 100644 src/renderer/src/components/billing/billing-link.test.ts delete mode 100644 src/renderer/src/components/billing/billing-link.ts create mode 100644 src/renderer/src/components/open-external/copy-link-auth-only.test.tsx delete mode 100644 src/renderer/src/components/worktree-creation/VmBuildFailureActions.copy-links.test.tsx delete mode 100644 src/renderer/src/components/worktree-creation/VmBuildSheetCopyLinks.fixture.tsx diff --git a/src/main/billing/billing-hosted-links.ts b/src/main/billing/billing-hosted-links.ts deleted file mode 100644 index 83072c8740c..00000000000 --- a/src/main/billing/billing-hosted-links.ts +++ /dev/null @@ -1,21 +0,0 @@ -// "Copy link" on billing buttons: the Stripe Checkout or Customer Portal URL the button would open, -// minted the same way (same account, same order, same setup-session fallback) but returned instead. -import type { OrcaBillingCheckoutArgs, OrcaBillingLinkResult } from '../../shared/orca-billing' -import { createCheckoutUrl, createPortalUrl } from './billing-client' -import { mintHosted } from './billing-service' -import { withSetupSessionFallback } from './billing-setup-session-fallback' - -export function getOrcaBillingCheckoutLink( - userDataPath: string, - args: OrcaBillingCheckoutArgs -): Promise { - return withSetupSessionFallback(args, (checkoutArgs) => - mintHosted(userDataPath, (token, endpoints) => - createCheckoutUrl(endpoints, token, checkoutArgs) - ) - ) -} - -export function getOrcaBillingPortalLink(userDataPath: string): Promise { - return mintHosted(userDataPath, (token, endpoints) => createPortalUrl(endpoints, token)) -} diff --git a/src/main/billing/billing-service.ts b/src/main/billing/billing-service.ts index c0845051b7a..9053f4402e8 100644 --- a/src/main/billing/billing-service.ts +++ b/src/main/billing/billing-service.ts @@ -222,7 +222,7 @@ export async function getOrcaBillingTeamPlans( type CreateHostedUrl = (token: string, endpoints: BillingEndpoints) => Promise /** Mints a Stripe-hosted Checkout/Portal URL for the active account without opening it. */ -export async function mintHosted( +async function mintHosted( userDataPath: string, createUrl: CreateHostedUrl ): Promise { diff --git a/src/main/hosted-sandbox/hosted-account-ipc.ts b/src/main/hosted-sandbox/hosted-account-ipc.ts index f31a122724c..30b7e1294db 100644 --- a/src/main/hosted-sandbox/hosted-account-ipc.ts +++ b/src/main/hosted-sandbox/hosted-account-ipc.ts @@ -23,7 +23,6 @@ const SETUP_SESSION_ID = /^cs_[A-Za-z0-9_-]{22}$/ export const HOSTED_ACCOUNT_CHANNELS = [ CH.getConfig, CH.connectGitHub, - CH.gitHubInstallLink, CH.getRepoAccess, CH.listGitHubRepositories, CH.createFromGitHub, @@ -107,15 +106,6 @@ export function registerHostedAccountHandlers( } }) - // "Copy link": the same install page, minted the same way, for another browser or profile. - ipcMain.handle(CH.gitHubInstallLink, async (_event, args?: RepoArgs) => { - try { - return { ok: true, value: await mintInstallUrl(args) } - } catch (error) { - return failure(error) - } - }) - ipcMain.handle(CH.getRepoAccess, async (_event, args?: RepoArgs) => { const target = repoTarget(args) if (!target) { diff --git a/src/main/hosted-sandbox/hosted-github-link-ipc.test.ts b/src/main/hosted-sandbox/hosted-github-link-ipc.test.ts index 3c2ab59b7bb..6d4b9421efa 100644 --- a/src/main/hosted-sandbox/hosted-github-link-ipc.test.ts +++ b/src/main/hosted-sandbox/hosted-github-link-ipc.test.ts @@ -1,5 +1,6 @@ -// "Copy link" twins of Connect GitHub (App install) and Connect your GitHub (OAuth): the same page, -// minted the same way, returned instead of opened, and still only ever a github.com page. +// "Copy link" for Connect your GitHub (OAuth sign-in): the same page, minted the same way, returned +// instead of opened, and still only ever a github.com page. The App install has no link channel: +// Copy link is for sign-in pages only. import { afterEach, expect, it, vi } from 'vitest' const handlers = new Map unknown>() @@ -56,25 +57,24 @@ function register(url: string) { return { connectGitHub, connectGitHubUser } } -it('registers the link channels with the window allowlist', () => { - expect(HOSTED_ACCOUNT_CHANNELS).toEqual( - expect.arrayContaining([CH.gitHubInstallLink, CH.gitHubUserConnectLink]) - ) +it('registers the OAuth link channel, and no App-install link channel', () => { + expect(HOSTED_ACCOUNT_CHANNELS).toContain(CH.gitHubUserConnectLink) + expect(HOSTED_ACCOUNT_CHANNELS).not.toContain('orcaCloudWorkspace:gitHubInstallLink') }) -it('returns the install page minted like Connect GitHub, without opening it', async () => { +it('Connect GitHub still opens the install page minted for the repository', async () => { const url = 'https://github.com/apps/x/installations/new?state=s' const { connectGitHub } = register(url) expect( - await handlers.get(CH.gitHubInstallLink)?.({}, { repoUrl: REPO, setupSessionId: SESSION }) - ).toEqual({ ok: true, value: url }) + await handlers.get(CH.connectGitHub)?.({}, { repoUrl: REPO, setupSessionId: SESSION }) + ).toEqual({ ok: true, value: null }) expect(connectGitHub).toHaveBeenLastCalledWith(undefined, { repo: REPO, setupSessionId: SESSION, repoId: 7, ownerId: 50 }) - expect(openExternal).not.toHaveBeenCalled() + expect(openExternal).toHaveBeenCalledWith(url) }) it('returns the OAuth page minted like Connect your GitHub, without opening it', async () => { @@ -84,7 +84,7 @@ it('returns the OAuth page minted like Connect your GitHub, without opening it', expect(openExternal).not.toHaveBeenCalled() }) -it('never hands out a page that is not on github.com', async () => { +it('never opens or hands out a page that is not on github.com', async () => { for (const url of [ 'https://github.com.evil.example/install', 'http://github.com/login/oauth/authorize', @@ -92,7 +92,7 @@ it('never hands out a page that is not on github.com', async () => { ]) { handlers.clear() register(url) - expect(await handlers.get(CH.gitHubInstallLink)?.({}, {})).toMatchObject({ + expect(await handlers.get(CH.connectGitHub)?.({}, {})).toMatchObject({ ok: false, code: 'failed' }) @@ -101,4 +101,5 @@ it('never hands out a page that is not on github.com', async () => { code: 'failed' }) } + expect(openExternal).not.toHaveBeenCalled() }) diff --git a/src/main/ipc/profiles/orca-profile-billing-handlers.ts b/src/main/ipc/profiles/orca-profile-billing-handlers.ts index 7b277f07486..cb8289c22cf 100644 --- a/src/main/ipc/profiles/orca-profile-billing-handlers.ts +++ b/src/main/ipc/profiles/orca-profile-billing-handlers.ts @@ -2,7 +2,6 @@ import { ipcMain } from 'electron' import { z } from 'zod' import type { OrcaBillingCheckoutArgs, - OrcaBillingLinkResult, OrcaBillingOpenResult, OrcaBillingOverageArgs, OrcaBillingOverageResult, @@ -27,10 +26,6 @@ import { openOrcaBillingPortal, setOrcaBillingOverage } from '../../billing/billing-service' -import { - getOrcaBillingCheckoutLink, - getOrcaBillingPortalLink -} from '../../billing/billing-hosted-links' import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' import { ensureActiveOrcaProfile } from '../../orca-profiles/profile-index-store' import { notifyUsageAlertIfDue } from '../../billing/usage-alert-notifier' @@ -222,13 +217,4 @@ export function registerOrcaProfileBillingHandlers(store: Store): void { ipcMain.handle('orcaProfiles:billingOpenPortal', async (): Promise => openOrcaBillingPortal(getProfileUserDataPath()) ) - // "Copy link": the same Stripe URLs, minted but not opened (paste into another browser profile). - ipcMain.handle('orcaProfiles:billingPortalLink', async (): Promise => - getOrcaBillingPortalLink(getProfileUserDataPath()) - ) - ipcMain.handle( - 'orcaProfiles:billingCheckoutLink', - async (_event, rawArgs: unknown): Promise => - getOrcaBillingCheckoutLink(getProfileUserDataPath(), billingCheckoutArgsFromUnknown(rawArgs)) - ) } diff --git a/src/preload/api/orca-cloud-workspace-bridge.ts b/src/preload/api/orca-cloud-workspace-bridge.ts index 891d4c7cbe7..86194e59d79 100644 --- a/src/preload/api/orca-cloud-workspace-bridge.ts +++ b/src/preload/api/orca-cloud-workspace-bridge.ts @@ -20,7 +20,6 @@ export const orcaCloudWorkspaceApi = { listCloudWorkspaceIds: () => ipcRenderer.invoke(CH.listCloudWorkspaceIds), getConfig: () => ipcRenderer.invoke(CH.getConfig), connectGitHub: (args) => ipcRenderer.invoke(CH.connectGitHub, args), - gitHubInstallLink: (args) => ipcRenderer.invoke(CH.gitHubInstallLink, args), getGitHubUser: () => ipcRenderer.invoke(CH.getGitHubUser), connectGitHubUser: () => ipcRenderer.invoke(CH.connectGitHubUser), gitHubUserConnectLink: () => ipcRenderer.invoke(CH.gitHubUserConnectLink), diff --git a/src/preload/api/orca-profile-api.ts b/src/preload/api/orca-profile-api.ts index 71572197248..e9b061d58d9 100644 --- a/src/preload/api/orca-profile-api.ts +++ b/src/preload/api/orca-profile-api.ts @@ -45,7 +45,6 @@ import type { } from '../../shared/orca-profiles' import type { OrcaBillingCheckoutArgs, - OrcaBillingLinkResult, OrcaBillingOpenResult, OrcaBillingOverageArgs, OrcaBillingOverageResult, @@ -129,10 +128,6 @@ export type OrcaProfileApi = { cloudSetupLink: (args: { sessionId: string }) => Promise /** Opens the Stripe Customer Portal in the browser. */ billingOpenPortal: () => Promise - /** "Copy link": a fresh Customer Portal URL, minted but not opened. */ - billingPortalLink: () => Promise - /** "Copy link": the Checkout URL billingOpenCheckout would open, minted but not opened. */ - billingCheckoutLink: (args: OrcaBillingCheckoutArgs) => Promise /** The last 30 days of sandbox hours (breakdowns for owners and admins only). */ billingUsageHistory: (args: { utcOffsetMinutes: number diff --git a/src/preload/api/orca-profiles-bridge.ts b/src/preload/api/orca-profiles-bridge.ts index 22837449f8d..497069b5105 100644 --- a/src/preload/api/orca-profiles-bridge.ts +++ b/src/preload/api/orca-profiles-bridge.ts @@ -102,8 +102,6 @@ export const orcaProfilesApi = { billingPlans: () => ipcRenderer.invoke('orcaProfiles:billingPlans'), billingOpenCheckout: (args) => ipcRenderer.invoke('orcaProfiles:billingOpenCheckout', args), billingOpenPortal: () => ipcRenderer.invoke('orcaProfiles:billingOpenPortal'), - billingPortalLink: () => ipcRenderer.invoke('orcaProfiles:billingPortalLink'), - billingCheckoutLink: (args) => ipcRenderer.invoke('orcaProfiles:billingCheckoutLink', args), billingTeamPlans: (args) => ipcRenderer.invoke('orcaProfiles:billingTeamPlans', args), billingUsageHistory: (args) => ipcRenderer.invoke('orcaProfiles:billingUsageHistory', args), cloudSetupStart: (args) => ipcRenderer.invoke('orcaProfiles:cloudSetupStart', args), diff --git a/src/renderer/src/components/billing/PaymentIssueNotice.tsx b/src/renderer/src/components/billing/PaymentIssueNotice.tsx index 7f7d9f8167f..88996b7aabf 100644 --- a/src/renderer/src/components/billing/PaymentIssueNotice.tsx +++ b/src/renderer/src/components/billing/PaymentIssueNotice.tsx @@ -1,7 +1,6 @@ import { ExternalLink } from 'lucide-react' +import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' -import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' -import { billingPortalLink } from './billing-link' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing' @@ -63,20 +62,16 @@ export function PaymentIssueNotice({ } action={ entitlement.canManageBilling ? ( - { - if (!busy) { - onUpdatePayment() - } - }} + onClick={busy ? undefined : onUpdatePayment} > {t('auto.components.billing.updatePayment', 'Update payment method')} - + ) : undefined } /> diff --git a/src/renderer/src/components/billing/PlanBillingSection.tsx b/src/renderer/src/components/billing/PlanBillingSection.tsx index a719d090fd6..322accf6cfa 100644 --- a/src/renderer/src/components/billing/PlanBillingSection.tsx +++ b/src/renderer/src/components/billing/PlanBillingSection.tsx @@ -14,8 +14,6 @@ import { } from '../../../../shared/orca-billing' import { openPlansPage } from './plans/plans-page-store' import { PaymentIssueNotice } from './PaymentIssueNotice' -import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' -import { billingPortalLink } from './billing-link' import { OverageControls, UsageSummary } from './PlanBillingUsage' import { denyReasonCopy, openFailureCopy, overageFailureCopy } from './plan-billing-copy' import { PlanStatusBadge } from './PlanStatusBadge' @@ -284,20 +282,16 @@ export function PlanBillingView({ )} {hasPlan && entitlement.canManageBilling && entitlement.payment.pastDueSince === null ? ( - { - if (!busy) { - onPortal() - } - }} + onClick={busy ? undefined : onPortal} > {t('auto.components.billing.manageBilling', 'Manage billing')} - + ) : null} {hasPlan ? ( // Members have no other action here, so it gets the button's chrome (and its alignment). diff --git a/src/renderer/src/components/billing/billing-link.test.ts b/src/renderer/src/components/billing/billing-link.test.ts deleted file mode 100644 index 8bca573d724..00000000000 --- a/src/renderer/src/components/billing/billing-link.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -const toastError = vi.fn() -vi.mock('sonner', () => ({ toast: { error: (...args: unknown[]) => toastError(...args) } })) - -import { billingCheckoutLink, billingPortalLink } from './billing-link' - -function stubApi(api: Record): void { - vi.stubGlobal('window', { api: { orcaProfiles: api } }) -} - -afterEach(() => { - toastError.mockReset() - vi.unstubAllGlobals() -}) - -describe('billing "Copy link"', () => { - it('returns the minted Portal URL without opening anything', async () => { - const billingPortalLink$ = vi.fn(async () => ({ - status: 'ok' as const, - url: 'https://billing.stripe.com/p/session/x' - })) - const billingOpenPortal = vi.fn() - stubApi({ billingPortalLink: billingPortalLink$, billingOpenPortal }) - await expect(billingPortalLink()).resolves.toBe('https://billing.stripe.com/p/session/x') - expect(billingOpenPortal).not.toHaveBeenCalled() - expect(toastError).not.toHaveBeenCalled() - }) - - it('mints Checkout for the same order the button would open', async () => { - const mint = vi.fn(async () => ({ - status: 'ok' as const, - url: 'https://checkout.stripe.com/c/pay/cs_1' - })) - stubApi({ billingCheckoutLink: mint }) - const args = { plan: 'team', interval: 'year' as const, seats: 5 } - await expect(billingCheckoutLink(args)).resolves.toBe('https://checkout.stripe.com/c/pay/cs_1') - expect(mint).toHaveBeenCalledWith(args) - }) - - it('says why there is no link with the open path’s copy, then yields null', async () => { - stubApi({ billingPortalLink: async () => ({ status: 'forbidden' }) }) - await expect(billingPortalLink()).resolves.toBeNull() - expect(toastError).toHaveBeenCalledWith('Only an owner or admin can manage billing.') - }) - - it('treats a rejected IPC as a failed billing read', async () => { - stubApi({ - billingPortalLink: async () => { - throw new Error('boom') - } - }) - await expect(billingPortalLink()).resolves.toBeNull() - expect(toastError).toHaveBeenCalledWith('Could not reach billing. Try again.') - }) -}) diff --git a/src/renderer/src/components/billing/billing-link.ts b/src/renderer/src/components/billing/billing-link.ts deleted file mode 100644 index 7bdae0ed29b..00000000000 --- a/src/renderer/src/components/billing/billing-link.ts +++ /dev/null @@ -1,35 +0,0 @@ -// "Copy link" for the Stripe buttons: mints the same Checkout/Portal URL the button opens, without -// opening it. A refusal (signed out, not an admin, no billing account…) is said in a toast with the -// open path's own copy, then null, so the split button adds nothing of its own. -import { toast } from 'sonner' -import { translate } from '@/i18n/i18n' -import type { - OrcaBillingCheckoutArgs, - OrcaBillingLinkResult -} from '../../../../shared/orca-billing' -import { openFailureCopy } from './plan-billing-copy' - -async function linkOrToast(mint: () => Promise): Promise { - const result = await mint().catch((error: unknown): OrcaBillingLinkResult => ({ - status: 'failed', - error: String(error) - })) - if (result.status === 'ok') { - return result.url - } - const failure = openFailureCopy(result, translate) - if (failure) { - toast.error(failure) - } - return null -} - -/** The Customer Portal URL "Manage billing" / "Update payment method" would open. */ -export function billingPortalLink(): Promise { - return linkOrToast(() => window.api.orcaProfiles.billingPortalLink()) -} - -/** The Checkout URL a plan's buy button would open for these args. */ -export function billingCheckoutLink(args: OrcaBillingCheckoutArgs): Promise { - return linkOrToast(() => window.api.orcaProfiles.billingCheckoutLink(args)) -} diff --git a/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx b/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx index 4794fc340e2..8ab5a50efe0 100644 --- a/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx +++ b/src/renderer/src/components/billing/checkout/CheckoutPanel.tsx @@ -2,7 +2,6 @@ import { useEffect, useId, useRef } from 'react' import { AlertCircle, Check, ExternalLink, Lock, RotateCcw, XCircle } from 'lucide-react' import { Button } from '@/components/ui/button' import { LoadingSpinner } from '@/components/LoadingSpinner' -import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/class-names' import { openFailureCopy } from '../plan-billing-copy' @@ -21,8 +20,6 @@ export type CheckoutPanelProps = { /** When the order was placed; the renewal date counts from it. */ now: number onReopen: () => void - /** "Copy link" on Reopen / Try again: a fresh Checkout URL for this order (absent: no chevron). */ - reopenLink?: () => Promise onKeepWaiting: () => void onBack: () => void /** Where "Contact us" goes when billing can't sell the plan (the plan's supportUrl, else Enterprise's contact). */ @@ -224,22 +221,13 @@ export function CheckoutPanel(props: CheckoutPanelProps): React.JSX.Element { break } - const reopenLabel = ( - <> + const reopen = ( + ) const back = ( @@ -287,14 +275,14 @@ export function CheckoutPanel(props: CheckoutPanelProps): React.JSX.Element { phase.result.status === 'plan-unavailable' && props.contactUrl && props.onContact ? ( - props.contactUrl && props.onContact?.(props.contactUrl)} > {t('auto.components.billing.checkout.contactUs', 'Contact us')} - + ) : null} {phase.kind === 'timed-out' ? (

    {t( 'auto.components.billing.plans.entHint', diff --git a/src/renderer/src/components/billing/plans/PlansDialogHost.tsx b/src/renderer/src/components/billing/plans/PlansDialogHost.tsx index 3bf8240ec1b..7d5619538f5 100644 --- a/src/renderer/src/components/billing/plans/PlansDialogHost.tsx +++ b/src/renderer/src/components/billing/plans/PlansDialogHost.tsx @@ -88,13 +88,6 @@ export function PlansDialogHost(): React.JSX.Element { setOrderedAt(Date.now()) checkout.start({ planId, interval, seats: count }) }} - checkoutLink={async ({ planId, interval, seats: count }) => { - const url = await checkout.copyLink({ planId, interval, seats: count }) - if (url) { - setOrderedAt(Date.now()) - } - return url - }} onManage={() => void openPortal()} onContactSales={(url) => void window.api.shell.openUrl(url)} onRetry={() => { @@ -126,7 +119,6 @@ export function PlansDialogHost(): React.JSX.Element { } checkout.reopen() }} - reopenLink={checkout.copyReopenLink} contactUrl={plans.state === 'ready' ? planContactUrl(plans.model) : null} onContact={(url) => void window.api.shell.openUrl(url)} onKeepWaiting={checkout.keepWaiting} diff --git a/src/renderer/src/components/billing/plans/PlansView.test.tsx b/src/renderer/src/components/billing/plans/PlansView.test.tsx index 4f5311c5299..397ad211a4d 100644 --- a/src/renderer/src/components/billing/plans/PlansView.test.tsx +++ b/src/renderer/src/components/billing/plans/PlansView.test.tsx @@ -49,13 +49,6 @@ describe("plans dialog from billing's catalog", () => { expect(props.onContactSales).toHaveBeenCalledWith('https://orca.dev/enterprise') }) - it('gives checkout and Contact sales a "Copy link" chevron for the same order', () => { - const checkoutLink = vi.fn(async () => 'https://checkout.stripe.com/c/pay/cs_1') - render() - // One chevron on the checkout button, one on Contact sales. - expect(screen.getAllByRole('button', { name: 'More link options' })).toHaveLength(2) - }) - it('offers only the intervals Stripe prices: no toggle with one', () => { render() expect(screen.queryByRole('radiogroup')).toBeNull() diff --git a/src/renderer/src/components/billing/plans/PlansView.tsx b/src/renderer/src/components/billing/plans/PlansView.tsx index e07ef549b3e..fa1786b4a72 100644 --- a/src/renderer/src/components/billing/plans/PlansView.tsx +++ b/src/renderer/src/components/billing/plans/PlansView.tsx @@ -36,12 +36,6 @@ export type PlansViewProps = { /** Seats Checkout will bill: org members, or 1 for a personal account. */ seats: number onCheckout: (args: { planId: string; interval: OrcaBillingInterval; seats: number }) => void - /** "Copy link" on the checkout button: the Checkout URL it would open (absent: no chevron). */ - checkoutLink?: (args: { - planId: string - interval: OrcaBillingInterval - seats: number - }) => Promise onManage: () => void onContactSales: (url: string) => void onRetry: () => void @@ -209,11 +203,6 @@ export function PlansView(props: PlansViewProps): React.JSX.Element { notice={props.notice} hideManage={paymentIssue} onCheckout={() => props.onCheckout({ planId: team.planId, interval, seats })} - checkoutLink={ - props.checkoutLink - ? () => props.checkoutLink!({ planId: team.planId, interval, seats }) - : undefined - } onManage={props.onManage} /> {enterprise ? ( diff --git a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx index ff2ecd1f74e..dbbde991a8b 100644 --- a/src/renderer/src/components/billing/plans/TeamPlanCard.tsx +++ b/src/renderer/src/components/billing/plans/TeamPlanCard.tsx @@ -2,8 +2,6 @@ import { ExternalLink, Lock, Users } from 'lucide-react' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' -import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' -import { billingPortalLink } from '../billing-link' import type { PlanBillingNotice } from '../PlanBillingSection' import { LoadingSpinner } from '@/components/LoadingSpinner' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' @@ -24,7 +22,6 @@ export function TeamPlanCard({ notice, hideManage, onCheckout, - checkoutLink, onManage }: { team: TeamPlanModel @@ -37,8 +34,6 @@ export function TeamPlanCard({ /** A payment banner already offers the same Portal action. */ hideManage: boolean onCheckout: () => void - /** "Copy link": mints the Checkout URL the button opens (absent: a plain button). */ - checkoutLink?: () => Promise onManage: () => void }): React.JSX.Element { const t = useTranslate() @@ -131,41 +126,20 @@ export function TeamPlanCard({

    ) } else if (mode === 'choose') { - const checkoutLabel = ( - <> - {busy ? : null} - {busy - ? t('auto.components.billing.plans.waiting', 'Waiting for checkout…') - : t('auto.components.billing.plans.checkout', 'Continue to checkout')} - {busy ? null : } - - ) footer = ( <> - {checkoutLink ? ( - { - if (!busy) { - onCheckout() - } - }} - > - {checkoutLabel} - - ) : ( - - )} + {notice?.kind === 'error' ? ( ) : ( @@ -189,21 +163,16 @@ export function TeamPlanCard({

    ) : ( <> - { - if (!busy) { - onManage() - } - }} + onClick={busy ? undefined : onManage} > {t('auto.components.billing.manageBilling', 'Manage billing')} - + {notice?.kind === 'error' ? ( ) : ( diff --git a/src/renderer/src/components/billing/team/TeamPageView.tsx b/src/renderer/src/components/billing/team/TeamPageView.tsx index c32779daf8f..288d555cd81 100644 --- a/src/renderer/src/components/billing/team/TeamPageView.tsx +++ b/src/renderer/src/components/billing/team/TeamPageView.tsx @@ -1,7 +1,6 @@ import { useEffect, useId, useRef } from 'react' import { CreditCard, ExternalLink, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' -import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' import { InlineError } from '@/components/ui/inline-error' import { Skeleton } from '@/components/ui/skeleton' import { useTranslate } from '@/i18n/use-translate' @@ -305,15 +304,15 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element {

    {t('auto.components.billing.team.ssoTitle', 'Single sign-on and provisioning')}

    - props.onContactSales(enterprise.contactUrl)} > {t('auto.components.billing.enterpriseContactSales', 'Contact sales')} - + ) : null} {props.dangerZone} diff --git a/src/renderer/src/components/new-workspace/ProjectComboboxCloudAddProjectEntry.tsx b/src/renderer/src/components/new-workspace/ProjectComboboxCloudAddProjectEntry.tsx index 55d5e1cf011..44ba26c0267 100644 --- a/src/renderer/src/components/new-workspace/ProjectComboboxCloudAddProjectEntry.tsx +++ b/src/renderer/src/components/new-workspace/ProjectComboboxCloudAddProjectEntry.tsx @@ -1,20 +1,12 @@ // PROJ-MENU part 2: "Give Orca Cloud access to more repositories" moves out of the project list into // the Add project menu, in its own "Orca Cloud" group: "Add a GitHub repository…". import React from 'react' -import { Github, Link2 } from 'lucide-react' +import { Github } from 'lucide-react' import { DropdownMenuItem, DropdownMenuSeparator } from '@/components/ui/dropdown-menu' import { useTranslate } from '@/i18n/use-translate' -import { copyExternalLink } from '@/components/open-external/copy-external-link' -import { gitHubInstallLinkSource } from '@/lib/orca-cloud/github-link-sources' import type { ProjectComboboxAddProjectMenu } from './ProjectComboboxAddProjectOption' -function FromGitHubItem({ - onSelect, - onCopyLink -}: { - onSelect: () => void - onCopyLink: () => void -}): React.JSX.Element { +function FromGitHubItem({ onSelect }: { onSelect: () => void }): React.JSX.Element { const t = useTranslate() return ( <> @@ -33,13 +25,6 @@ function FromGitHubItem({ {t('components.newWorkspace.cloudOnly.addRepositoryMenu', 'Add a GitHub repository…')} - {/* A menu row can't carry a chevron: the same GitHub page, copied for another browser. */} - - - - {t('components.newWorkspace.cloudOnly.copyAddRepositoryLink', 'Copy GitHub link')} - - ) } @@ -60,10 +45,6 @@ export function cloudAddProjectExtraItems( closeMenus() onMoreCloudAccess() }} - onCopyLink={() => { - closeMenus() - void copyExternalLink(gitHubInstallLinkSource()) - }} /> ) } diff --git a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-steps.ts b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-steps.ts index df7f18d4054..23aadd91bce 100644 --- a/src/renderer/src/components/new-workspace/run-on/use-cloud-start-steps.ts +++ b/src/renderer/src/components/new-workspace/run-on/use-cloud-start-steps.ts @@ -78,7 +78,7 @@ export function useCloudStartSteps({ onGranted: () => grantedRef.current?.(repoNameRef.current), ...(setupSessionId ? { setupSessionId } : {}) }) - const { state, access: grant, repoName, owner, loading, openInstall, installLink } = repoAccess + const { state, access: grant, repoName, owner, loading, openInstall } = repoAccess useEffect(() => { repoNameRef.current = repoName }, [repoName]) @@ -120,5 +120,5 @@ export function useCloudStartSteps({ ), [access, agentRow, availability, github, githubOverride, session, state] ) - return { steps, session, openInstall, installLink } + return { steps, session, openInstall } } diff --git a/src/renderer/src/components/open-external/copy-link-auth-only.test.tsx b/src/renderer/src/components/open-external/copy-link-auth-only.test.tsx new file mode 100644 index 00000000000..d47e57d793d --- /dev/null +++ b/src/renderer/src/components/open-external/copy-link-auth-only.test.tsx @@ -0,0 +1,102 @@ +// @vitest-environment happy-dom +// AUTH-ONLY-COPY-LINK: "Copy link" (the split's chevron) is for sign-in pages only, where people paste +// the URL into an incognito window. Billing, help, support and the GitHub App install keep a plain +// button, and nothing adds a "Copy … link" row next to them. +import { cleanup, render, screen, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { PaymentIssueNotice } from '@/components/billing/PaymentIssueNotice' +import { sampleTeam } from '@/components/billing/plan-billing-fixtures' +import { + FailureActionRow, + type VmBuildFailureActions +} from '@/components/worktree-creation/VmBuildFailureActions' +import { translate } from '@/i18n/i18n' +import { OpenExternalSplitButton } from './OpenExternalSplitButton' + +afterEach(cleanup) + +const chevrons = (): number => document.querySelectorAll('[data-open-external-chevron]').length + +const actions: VmBuildFailureActions = { + onFixWithAgent: vi.fn(), + onRetry: vi.fn(), + onEditRecipe: vi.fn(), + onOpenAnyway: vi.fn(), + onStartAgain: vi.fn(), + onDismiss: vi.fn(), + onSeePlans: vi.fn(), + onOpenBilling: vi.fn(), + onCreateLocally: vi.fn(), + onSignIn: vi.fn(), + onShowWorkspaces: vi.fn(), + onContactSupport: vi.fn(), + onConnectGitHub: vi.fn(), + onPushToGitHub: vi.fn() +} + +function failureRow(kind: 'githubNotConnected' | 'noGithubRemote' | 'snapshotMissing'): void { + render( + + + + ) +} + +it('keeps the chevron on a sign-in button', () => { + render( + {}}> + Open again + + ) + expect(chevrons()).toBe(1) +}) + +it('"Update payment method" is a plain button', () => { + render( + {}} + /> + ) + expect(screen.getByRole('button', { name: /Update payment method/ })).toBeTruthy() + expect(chevrons()).toBe(0) +}) + +it('Connect GitHub (App install) and "How to push to GitHub" are plain buttons', () => { + failureRow('githubNotConnected') + expect(screen.getByRole('button', { name: /Connect GitHub/ })).toBeTruthy() + expect(chevrons()).toBe(0) + cleanup() + failureRow('noGithubRemote') + expect(screen.getByRole('button', { name: /How to push to GitHub/ })).toBeTruthy() + expect(chevrons()).toBe(0) +}) + +it('"Contact support" has no "Copy support link" row beside it', async () => { + failureRow('snapshotMissing') + const more = screen.queryAllByRole('button').find((b) => b.getAttribute('aria-haspopup')) + expect(more).toBeTruthy() + await userEvent.setup().click(more!) + const menu = await screen.findByRole('menu') + const items = within(menu) + .getAllByRole('menuitem') + .map((item) => item.textContent?.trim()) + expect(items.some((label) => label?.includes('Contact support'))).toBe(true) + expect(items.some((label) => /copy/i.test(label ?? ''))).toBe(false) +}) diff --git a/src/renderer/src/components/orca-cloud-setup/CloudCapabilityOffActions.tsx b/src/renderer/src/components/orca-cloud-setup/CloudCapabilityOffActions.tsx index cb02a34cb8d..a8ae019622c 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudCapabilityOffActions.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudCapabilityOffActions.tsx @@ -1,7 +1,6 @@ import React from 'react' import { ExternalLink } from 'lucide-react' import { Button } from '@/components/ui/button' -import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton' import { openAppHttpLink } from '@/lib/browser/navigation/app-http-link-open' import { useTranslate } from '@/i18n/use-translate' @@ -24,14 +23,10 @@ export function CloudCapabilityOffActions({ {t('cloudSetupPage.capability.tryAgain', 'Try again')} {contactUrl ? ( - openAppHttpLink(contactUrl)} - > + ) : null}
    ) diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.fixture.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.fixture.tsx index 590ef8896b3..c8aa512131a 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.fixture.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.fixture.tsx @@ -35,8 +35,7 @@ function flow(rows: CloudSetupStep[], teamSwitch = false): CloudSetupFlow { checkAgain: noop, contactUrl: null, reopenBrowser: noop, - reopenLink: null, - installGitHubLink: null + reopenLink: null } } diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx index 8712c75a814..5eed336f99a 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -212,7 +212,7 @@ function StepActions({ ) case 'github-install': - return browser(continueLabel, flow.installGitHub, flow.installGitHubLink) + return browser(continueLabel, flow.installGitHub) case 'start-trial': return (
    - {line.action?.link ? ( - (line.action?.pending ? undefined : line.action?.onClick())} - aria-disabled={line.action.pending || undefined} - aria-busy={line.action.pending || undefined} - > - {line.action.icon} - {line.action.label} - - ) : line.action ? ( + {line.action ? ( - ) - )} + {primary.map((action, index) => ( + + ))} {more.length > 0 ? ( diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheetCopyLinks.fixture.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheetCopyLinks.fixture.tsx deleted file mode 100644 index dbf931dff20..00000000000 --- a/src/renderer/src/components/worktree-creation/VmBuildSheetCopyLinks.fixture.tsx +++ /dev/null @@ -1,58 +0,0 @@ -// COPY-LINK-RULE on the build sheet: "How to push to GitHub" as a split button (its chevron menu -// open), and "Copy support link" right below "Contact support" in the More menu. -import { defineFixture } from '../../component-fixtures/component-fixture' -import { - CLOUD_RECIPE, - FAILED_LOG, - T0, - entry, - seedFixtureRepo, - sheet -} from './vm-build-sheet-fixture-support' - -const settle = (): Promise => new Promise((resolve) => setTimeout(resolve, 120)) - -// Radix menus open on pointerdown, not click. -function openMenu(selector: string) { - return async (frame: HTMLElement): Promise => { - frame - .querySelector(selector) - ?.dispatchEvent( - new PointerEvent('pointerdown', { bubbles: true, button: 0, pointerType: 'mouse' }) - ) - await settle() - } -} - -function failed(errorCode: string, error: string, log: string) { - return { - value: entry( - { status: 'error', errorCode, provisioningLog: log, errorAt: T0 + 2_000 }, - CLOUD_RECIPE - ), - error - } -} - -const noRemote = failed( - 'cloudNoGithubRemote', - 'Orca Cloud clones your code from GitHub, and this repository has no GitHub remote.', - '' -) -const snapshot = failed('recipeExited', 'Recipe exited with code 1.', FAILED_LOG) - -/** "How to push to GitHub" with its chevron open: Copy link. */ -export const pushToGitHubCopyLink = defineFixture({ - width: 760, - setup: () => seedFixtureRepo(null), - render: () => sheet(noRemote.value, noRemote.error, T0 + 2_000), - interact: openMenu('button[aria-label="More link options"]') -}) - -/** "Contact support" in More, with "Copy support link" right below it. */ -export const contactSupportCopyLink = defineFixture({ - width: 760, - setup: () => seedFixtureRepo(), - render: () => sheet(snapshot.value, snapshot.error, T0 + 2_000), - interact: openMenu('[data-vm-build-sheet] button[aria-haspopup="menu"]') -}) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b396585c676..501174779ba 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -4577,8 +4577,7 @@ "trialLimitBodyCount_other": "Your trial can run {{count}} sandboxes at once. Put one to sleep or delete it, then try again. Nothing was created, and you weren’t charged.", "teamLimitBodyNoSeatCount_one": "Your team can run {{count}} sandbox at once. Put it to sleep or delete it, then try again. Nothing was created, and you weren’t charged.", "teamLimitBodyNoSeatCount_other": "Your team can run {{count}} sandboxes at once. Put one to sleep or delete it, then try again. Nothing was created, and you weren’t charged.", - "trialLimitTitle": "You’re at your trial’s limit of running sandboxes", - "copySupportLink": "Copy support link" + "trialLimitTitle": "You’re at your trial’s limit of running sandboxes" }, "VmBuildLog": { "jumpToError": "Jump to first error", @@ -23926,7 +23925,6 @@ "privateLabel": "Private", "menuGroup": "Orca Cloud", "addRepositoryMenu": "Add a GitHub repository…", - "copyAddRepositoryLink": "Copy GitHub link", "waitingForGitHubAccess": "Waiting for GitHub access…", "noNewRepositoryYet": "No new repository yet.", "checkAgain": "Check again", diff --git a/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json index e9a169b5dae..450bc63eb3b 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json +++ b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json @@ -13,7 +13,7 @@ }, { "path": "src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx", - "line": 412, + "line": 372, "term": "VM", "reason": "recipe-VM branch; cloud branch says sandbox" }, diff --git a/src/renderer/src/lib/orca-cloud/github-link-sources.ts b/src/renderer/src/lib/orca-cloud/github-link-sources.ts index 33030df09d7..40709c97956 100644 --- a/src/renderer/src/lib/orca-cloud/github-link-sources.ts +++ b/src/renderer/src/lib/orca-cloud/github-link-sources.ts @@ -1,19 +1,9 @@ -// "Copy link" for the GitHub handoffs: the same single-use page Connect GitHub (App install) and -// Connect your GitHub (OAuth) open, minted the same way in main but returned instead of opened. +// "Copy link" for connecting your GitHub identity (OAuth sign-in): the same single-use page Connect +// your GitHub opens, minted the same way in main but returned instead of opened. Copy link is for +// sign-in pages only; the GitHub App install keeps a plain button. import { requireLink, type ExternalLinkSource } from '@/components/open-external/copy-external-link' import { cloudWorkspaceApi } from './orca-cloud-workspace-store' -/** The GitHub App install page; with a repository, GitHub preselects it (and a setup session returns). */ -export function gitHubInstallLinkSource(args?: { - repoUrl?: string - setupSessionId?: string -}): ExternalLinkSource { - return async () => { - const result = await cloudWorkspaceApi()?.gitHubInstallLink(args) - return requireLink(result?.ok ? result.value : null) - } -} - /** GitHub's OAuth page for connecting the person's own GitHub identity. */ export function gitHubUserConnectLinkSource(): ExternalLinkSource { return async () => { diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-git-setup.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-git-setup.test.ts index 0e6b72d3618..911e85d51a9 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-git-setup.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-git-setup.test.ts @@ -47,7 +47,6 @@ function stub( connectGitHub: vi.fn(unused), getGitHubUser: vi.fn(unused), connectGitHubUser: vi.fn(unused), - gitHubInstallLink: vi.fn(unused), gitHubUserConnectLink: vi.fn(unused), disconnectGitHubUser: vi.fn(unused), getRepoAccess: vi.fn(unused), diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts index 2eaf4be43a6..f6c889b15f4 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store-wake.test.ts @@ -37,7 +37,6 @@ function stub( connectGitHub: vi.fn(unused), getGitHubUser: vi.fn(unused), connectGitHubUser: vi.fn(unused), - gitHubInstallLink: vi.fn(unused), gitHubUserConnectLink: vi.fn(unused), disconnectGitHubUser: vi.fn(unused), getRepoAccess: vi.fn(unused), diff --git a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts index 2cb54706641..8b440d8b65f 100644 --- a/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts +++ b/src/renderer/src/lib/orca-cloud/orca-cloud-workspace-store.test.ts @@ -42,7 +42,6 @@ function stubApi(overrides: Partial = {}): OrcaCloudWorks connectGitHub: vi.fn(async () => ok(null)), getGitHubUser: vi.fn(async () => ok({ connected: false as const })), connectGitHubUser: vi.fn(async () => ok(null)), - gitHubInstallLink: vi.fn(async () => ok('https://github.com/apps/x/installations/new')), gitHubUserConnectLink: vi.fn(async () => ok('https://github.com/login/oauth/authorize')), disconnectGitHubUser: vi.fn(async () => ok({ connected: false as const })), getRepoAccess: vi.fn(async () => diff --git a/src/renderer/src/lib/orca-cloud/use-orca-cloud-repo-access.ts b/src/renderer/src/lib/orca-cloud/use-orca-cloud-repo-access.ts index d07a6a21b45..04e74e0aa00 100644 --- a/src/renderer/src/lib/orca-cloud/use-orca-cloud-repo-access.ts +++ b/src/renderer/src/lib/orca-cloud/use-orca-cloud-repo-access.ts @@ -3,14 +3,12 @@ // network call; everything else comes from the control plane's GET /v1/github/repo-access (N2), // cached 5 minutes. While a repository is waiting (an install in the browser, or an org owner's // approval, D2), `poll` re-checks on the spec's cadence: every 2 s for 3 minutes, then every 10 s. -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import { useAppStore } from '@/store' import { normalizeGitRemoteUrl } from '../../../../shared/git/remotes/git-remote-identity' import type { HostedGithubRepoAccessResponse } from '../../../../shared/hosted-sandbox/hosted-github-wire' import type { Repo } from '../../../../shared/repo-types' -import type { ExternalLinkSource } from '@/components/open-external/copy-external-link' import { cloudWorkspaceApi } from './orca-cloud-workspace-store' -import { gitHubInstallLinkSource } from './github-link-sources' import { useOrcaCloudIdentityKey } from './orca-cloud-identity' export type OrcaCloudRepoAccessState = @@ -139,12 +137,7 @@ export function useOrcaCloudRepoAccess( /** Fired once when a repository that was waiting becomes reachable (D2's "access granted"). */ onGranted?: () => void } = {} -): OrcaCloudRepoAccess & { - refresh: () => void - openInstall: () => Promise - /** "Copy link" for openInstall: the same single-use install page, minted without opening. */ - installLink: ExternalLinkSource | null -} { +): OrcaCloudRepoAccess & { refresh: () => void; openInstall: () => Promise } { const repo = useAppStore((s) => repoId ? s.repos.find((entry) => entry.id === repoId) : undefined ) @@ -218,14 +211,6 @@ export function useOrcaCloudRepoAccess( return Boolean(result?.ok) }, [repoUrl, setupSessionId]) - const installLink = useMemo( - () => - repoUrl - ? gitHubInstallLinkSource({ repoUrl, ...(setupSessionId ? { setupSessionId } : {}) }) - : null, - [repoUrl, setupSessionId] - ) - return { state: enabled || !repoUrl ? state : 'unknown', ...(current?.installUrl ? { installUrl: current.installUrl } : {}), @@ -235,7 +220,6 @@ export function useOrcaCloudRepoAccess( repoUrl, loading: enabled && current === undefined, refresh, - openInstall, - installLink + openInstall } } diff --git a/src/renderer/src/web/preload-api/web-orca-profiles-api.ts b/src/renderer/src/web/preload-api/web-orca-profiles-api.ts index 4fa1c22b21e..b6c17f986d6 100644 --- a/src/renderer/src/web/preload-api/web-orca-profiles-api.ts +++ b/src/renderer/src/web/preload-api/web-orca-profiles-api.ts @@ -85,8 +85,6 @@ export function createWebOrcaProfilesApi(): Partial { cloudSetupGet: async () => ({ status: 'unconfigured' }), cloudSetupLink: async () => ({ status: 'unconfigured' }), billingOpenPortal: async () => ({ status: 'unconfigured' }), - billingPortalLink: async () => ({ status: 'unconfigured' }), - billingCheckoutLink: async () => ({ status: 'unconfigured' }), billingTeamPlans: async () => ({ status: 'unconfigured' }), billingUsageHistory: async () => ({ status: 'unconfigured' }), billingSetOverage: async () => ({ status: 'unconfigured' }), diff --git a/src/shared/hosted-sandbox/cloud-workspace-api.ts b/src/shared/hosted-sandbox/cloud-workspace-api.ts index d7eda6f51e3..a176c7a32ca 100644 --- a/src/shared/hosted-sandbox/cloud-workspace-api.ts +++ b/src/shared/hosted-sandbox/cloud-workspace-api.ts @@ -95,11 +95,6 @@ export type OrcaCloudWorkspaceApi = { repoUrl?: string setupSessionId?: string }) => Promise> - /** "Copy link" for connectGitHub: the same single-use GitHub install page, minted but not opened. */ - gitHubInstallLink: (args?: { - repoUrl?: string - setupSessionId?: string - }) => Promise> /** Whether the signed-in person connected their own GitHub (cloud commit attribution). */ getGitHubUser: () => Promise> /** Opens GitHub's OAuth page in the browser so the person connects their own GitHub identity. */ @@ -146,7 +141,6 @@ export const ORCA_CLOUD_WORKSPACE_CHANNELS = { listCloudWorkspaceIds: 'orcaCloudWorkspace:listIds', getConfig: 'orcaCloudWorkspace:getConfig', connectGitHub: 'orcaCloudWorkspace:connectGitHub', - gitHubInstallLink: 'orcaCloudWorkspace:gitHubInstallLink', getGitHubUser: 'orcaCloudWorkspace:getGitHubUser', connectGitHubUser: 'orcaCloudWorkspace:connectGitHubUser', gitHubUserConnectLink: 'orcaCloudWorkspace:gitHubUserConnectLink', From 747c389b680e02f762b524c96731ea427819ad5d Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 21:51:16 -0800 Subject: [PATCH 09/28] feat(billing): features answer says whether the account pays for a plan (PAID-TEAM-CHOOSE-PLAN) POST /v1/internal/entitlements/features now also returns subscribed: the account has a subscription that is active, trialing, past_due or unpaid. Auth counts it as Orca Cloud access, so a paying team that is not on the per-account rollout is no longer told to choose a plan (and then refused at checkout as already subscribed). Read from the subscription row Stripe's webhooks keep, in every ENTITLEMENTS_MODE. Canceled, incomplete, expired and paused subscriptions, the no-card trial and no subscription are false. Co-Authored-By: Claude --- cloud/apps/billing/src/entitlements.ts | 2 +- cloud/apps/billing/src/features.ts | 20 +++++++++- cloud/apps/billing/src/index.ts | 10 +++-- cloud/apps/billing/test/features.test.ts | 49 ++++++++++++++++++++++-- 4 files changed, 72 insertions(+), 9 deletions(-) diff --git a/cloud/apps/billing/src/entitlements.ts b/cloud/apps/billing/src/entitlements.ts index be4d89b4d8e..257823564bc 100644 --- a/cloud/apps/billing/src/entitlements.ts +++ b/cloud/apps/billing/src/entitlements.ts @@ -129,7 +129,7 @@ type AccountState = { export { entitlementsMode, type EntitlementsMode } from './entitlements-mode' -const LIVE_STATUSES = new Set(['active', 'trialing']) +export const LIVE_STATUSES = new Set(['active', 'trialing']) export function subscriptionWindow(subscription: SubscriptionRow, at: number): { start: number; end: number } { return allowanceWindow({ start: subscription.current_period_start, end: subscription.current_period_end }, at) diff --git a/cloud/apps/billing/src/features.ts b/cloud/apps/billing/src/features.ts index 5b85e515088..1448724f718 100644 --- a/cloud/apps/billing/src/features.ts +++ b/cloud/apps/billing/src/features.ts @@ -5,13 +5,19 @@ // live grants in every mode but 'off' (where nothing projects grants, so nothing is on). The // legacy computation has no features, so there is nothing for shadow mode to compare. // -// POST /v1/internal/entitlements/features {accountId} -> { features: { audit_log, sso, scim, mfa_enforcement } } +// POST /v1/internal/entitlements/features {accountId} +// -> { features: { audit_log, sso, scim, mfa_enforcement }, subscribed } +// `subscribed` (hasPaidSubscription) is what auth counts as Orca Cloud access for the account, so a +// paying team is never sent to "Choose a Team plan" because it isn't on the per-account rollout. // Callers: the control plane (CONTROL_PLANE_TOKEN) and auth (MEMBERSHIP_SYNC_TOKEN). Both fail closed. import { z } from 'zod' import { FEATURE_KEYS, type FeatureFlags } from './entitlement-keys' import { entitlementsMode } from './entitlements-mode' import type { Env } from './env' +import { LIVE_STATUSES } from './entitlements' import { grantsForSubject, liveAt } from './grants' +import { currentSubscription } from './store' +import { PAYMENT_FAILED_STATUSES } from './webhook' export const FeaturesRequestSchema = z.object({ accountId: z.string().min(1).max(160).regex(/^[A-Za-z0-9_.:-]+$/) }).strict() @@ -35,3 +41,15 @@ export async function featuresFor(env: Pick { + const subscription = await currentSubscription(db, accountId) + return subscription !== null && (LIVE_STATUSES.has(subscription.status) || PAYMENT_FAILED_STATUSES.has(subscription.status)) +} diff --git a/cloud/apps/billing/src/index.ts b/cloud/apps/billing/src/index.ts index 24cfc27063e..438e971fe0a 100644 --- a/cloud/apps/billing/src/index.ts +++ b/cloud/apps/billing/src/index.ts @@ -15,7 +15,7 @@ // POST /v1/stripe/webhook signed events // Sandbox control plane (CONTROL_PLANE_TOKEN): // POST /v1/internal/entitlements/check {accountId, machineSize, runningSandboxes} -// POST /v1/internal/entitlements/features {accountId} -> {features: {audit_log, sso, scim, mfa_enforcement}} plan feature flags (control plane or auth) +// POST /v1/internal/entitlements/features {accountId} -> {features: {audit_log, sso, scim, mfa_enforcement}, subscribed} plan feature flags and paid-subscription access (control plane or auth) // POST /v1/internal/usage {usageId, accountId, sandboxId, machineSize, startedAt, endedAt} // GET /v1/internal/suspensions accounts whose payment grace expired (suspend running) // POST /v1/internal/trial/github {accountId, githubUserId?, githubOwnerId?} GitHub binding -> trial abuse keys @@ -58,7 +58,7 @@ import { MACHINE_SIZES, PlanConfigError, planCatalog, publicOffers } from './pla import { OverageRequestSchema, updateOverage } from './overage' import { LiveModeRefusedError, StripeError, createStripeClient, type StripeClient } from './stripe' import { UsageReportSchema, flushMeterReports, recordUsage, validateSegment } from './usage' -import { FeaturesRequestSchema, featuresFor } from './features' +import { FeaturesRequestSchema, featuresFor, hasPaidSubscription } from './features' import { handleStripeWebhook } from './webhook' import { UsageHistoryQuerySchema, usageHistory } from './usage-history' import { renderReturnPage, returnOutcome } from './return-page' @@ -526,7 +526,11 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo if (!body.success) { return json({ error: 'invalid_request' }, 400) } - return json({ features: await featuresFor(env, body.data.accountId, now) }) + const [features, subscribed] = await Promise.all([ + featuresFor(env, body.data.accountId, now), + hasPaidSubscription(env.BILLING_DB, body.data.accountId) + ]) + return json({ features, subscribed }) } case 'POST /v1/internal/usage': { diff --git a/cloud/apps/billing/test/features.test.ts b/cloud/apps/billing/test/features.test.ts index 60e760d6bc2..7fe7cca7c41 100644 --- a/cloud/apps/billing/test/features.test.ts +++ b/cloud/apps/billing/test/features.test.ts @@ -7,6 +7,7 @@ import { featuresFor } from '../src/features' import { grantContactSalesPlan, grantsForSource, revokeManualGrant } from '../src/grants' import { repoCatalog } from './catalog-fixture' import { createHarness } from './harness' +import { checkoutCompleted } from './stripe-fake' const ALL_OFF = { audit_log: false, sso: false, scim: false, mfa_enforcement: false } const ALL_ON = { audit_log: true, sso: true, scim: true, mfa_enforcement: true } @@ -50,11 +51,11 @@ describe('catalog', () => { describe.each(['shadow', 'on'])('features (ENTITLEMENTS_MODE=%s)', (mode) => { it('are off for a team without Enterprise and on for one granted the plan', async () => { const h = await createHarness({ ENTITLEMENTS_MODE: mode }) - expect((await features(h)).body).toEqual({ features: ALL_OFF }) + expect((await features(h)).body).toEqual({ features: ALL_OFF, subscribed: false }) expect(await enterprise(h)).toEqual({ changed: true, planVersion: 2 }) - expect((await features(h)).body).toEqual({ features: ALL_ON }) + expect((await features(h)).body).toEqual({ features: ALL_ON, subscribed: false }) // Another team is unaffected. - expect((await features(h, 'org:o2')).body).toEqual({ features: ALL_OFF }) + expect((await features(h, 'org:o2')).body).toEqual({ features: ALL_OFF, subscribed: false }) }) it('the grant names the real plan and version, and stops when it ends or is revoked', async () => { @@ -76,7 +77,7 @@ describe('features', () => { const h = await createHarness({ ENTITLEMENTS_MODE: 'shadow' }) await enterprise(h) h.env.ENTITLEMENTS_MODE = 'off' - expect((await features(h)).body).toEqual({ features: ALL_OFF }) + expect((await features(h)).body).toEqual({ features: ALL_OFF, subscribed: false }) }) it('only a contact-sales plan can be granted this way', async () => { @@ -121,3 +122,43 @@ describe('features', () => { expect(body.grants.find((grant: { key: string }) => grant.key === 'audit_log')).toMatchObject({ value: true, source: 'manual', plan: { id: 'enterprise', version: 2 }, state: 'active' }) }) }) + +describe('subscribed', () => { + const PERIOD_START = Math.floor(Date.now() / 1000) - 5 * 24 * 3600 + const PERIOD_END = PERIOD_START + 30 * 24 * 3600 + + // A paid Team subscription for org:o1, through checkout and Stripe's webhook as in production. + async function paidTeam(mode = 'shadow') { + const h = await createHarness({ ENTITLEMENTS_MODE: mode }) + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' }) + const checkout = await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 2 }, headers: { authorization: `Bearer ${token}` } }) + expect(checkout.status).toBe(200) + const customer = [...h.stripe.customers.keys()][0]! + const subscription = h.stripe.putSubscription({ customer, accountId: 'org:o1', basePrice: 'price_team_month', quantity: 2, periodStart: PERIOD_START, periodEnd: PERIOD_END }) + await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' })) + return h + } + const setStatus = (h: Awaited>, status: string) => h.raw.prepare('UPDATE subscriptions SET status = ? WHERE account_id = ?').run(status, 'org:o1') + + it('is true for a team paying for a plan, whatever its hours, and false for everyone else', async () => { + for (const mode of ['off', 'shadow', 'on']) { + const h = await paidTeam(mode) + expect((await features(h)).body).toMatchObject({ subscribed: true }) + // Another team, and the owner's personal account, have no subscription. + expect((await features(h, 'org:o2')).body).toMatchObject({ subscribed: false }) + expect((await features(h, 'user:u1')).body).toMatchObject({ subscribed: false }) + } + }) + + it('stays true while a payment is being retried, and ends with the subscription', async () => { + const h = await paidTeam() + for (const status of ['trialing', 'past_due', 'unpaid']) { + setStatus(h, status) + expect((await features(h)).body, status).toMatchObject({ subscribed: true }) + } + for (const status of ['canceled', 'incomplete', 'incomplete_expired', 'paused']) { + setStatus(h, status) + expect((await features(h)).body, status).toMatchObject({ subscribed: false }) + } + }) +}) From ffc17e6a4ed9e291d48b130c3ca766702207c79f Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 22:03:23 -0800 Subject: [PATCH 10/28] fix(cloud): separate result members so the team MFA service narrows --- .../cloud-mfa/profile-cloud-team-mfa-service.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts index 5462ad2b15b..ae7f8101976 100644 --- a/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts +++ b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts @@ -19,7 +19,10 @@ import { orgMembersUrl, requestInit } from '../cloud-org/profile-cloud-org-members-client' -import { runOrgMemberCall, type OrgCallResult } from '../cloud-org/profile-cloud-org-members-service' +import { + runOrgMemberCall, + type OrgCallResult +} from '../cloud-org/profile-cloud-org-members-service' import { ensureActiveOrcaProfile } from '../profile-index-store' const SELF_STATES: readonly OrcaTeamMfaSelfState[] = ['on', 'off', 'pending', 'blocked', 'unknown'] @@ -113,7 +116,15 @@ async function request(url: string, init: RequestInit): Promise { type Unavailable = Extract< OrcaTeamMfaPolicyResult, - { status: 'unconfigured' | 'reconnect-required' | 'unsupported' | 'forbidden' | 'rate-limited' | 'failed' } + { + status: + | 'unconfigured' + | 'reconnect-required' + | 'unsupported' + | 'forbidden' + | 'rate-limited' + | 'failed' + } > function unavailable(result: Exclude, { status: 'ok' }>): Unavailable { @@ -141,7 +152,7 @@ async function call( userDataPath: string, run: (apiBaseUrl: string, accessToken: string, url: (path: string) => string) => Promise, orgId: string -): Promise | { status: 'unconfigured' | 'unsupported' }> { +): Promise | { status: 'unconfigured' } | { status: 'unsupported' }> { const active = ensureActiveOrcaProfile(userDataPath) // Local dev auth has no server, so no policy. if (isOrcaCloudDevAuthEnabled()) { From 3adf9a3b043646c389fde904ab03ea1debeecd2b Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 22:04:05 -0800 Subject: [PATCH 11/28] fix(cloud): SEC-5 a shared workspace gets none of its owner's personal secrets ownersForSandbox resolves no personal owner unless the row is private, so a workspace shared with the team gets team and repository secrets only (values and placeholders). The egress proxy's cached keys are keyed by visibility so sharing takes effect at once. Share toast and Personal tab say so. --- cloud/apps/sandbox-control/src/secrets.ts | 22 +- cloud/apps/sandbox-control/src/session-env.ts | 5 +- .../test/shared-workspace-secrets.test.ts | 216 ++++++++++++++++++ .../cloud-workspaces/CloudWorkspacesHome.tsx | 9 +- .../orca-cloud/CloudWorkspaceMenuItems.tsx | 25 +- .../CloudSecretsPane.fixture.tsx | 2 +- .../cloud-secrets/CloudSecretsPane.tsx | 4 +- src/renderer/src/i18n/locales/en.json | 6 +- 8 files changed, 269 insertions(+), 20 deletions(-) create mode 100644 cloud/apps/sandbox-control/test/shared-workspace-secrets.test.ts diff --git a/cloud/apps/sandbox-control/src/secrets.ts b/cloud/apps/sandbox-control/src/secrets.ts index 88f0b5d1fc4..1f7713324ad 100644 --- a/cloud/apps/sandbox-control/src/secrets.ts +++ b/cloud/apps/sandbox-control/src/secrets.ts @@ -165,12 +165,18 @@ function repoOwner(accountId: string, repo: string): string { return `${accountId}#${repo}` } -/** The owners whose secrets a sandbox session receives. */ -export function ownersForSandbox(row: Pick) { +/** + * The owners whose secrets a sandbox session receives. + * SEC-5: a workspace shared with teammates runs their shells too, so anything in its env is theirs to + * read (and a placeholder is theirs to spend). It gets the team's and the repository's secrets only, + * never its owner's personal ones, the same rule as personal accounts (D13). Fails closed: only a row + * known to be private counts as unshared. + */ +export function ownersForSandbox(row: Pick) { const repo = normalizeRepo(row.repo_url) return { org: ORG_ACCOUNT.test(row.account_id) ? row.account_id : null, - personal: personalOwner(row.user_id, row.account_id.startsWith('dev:')), + personal: row.visibility === 'private' ? personalOwner(row.user_id, row.account_id.startsWith('dev:')) : null, repo: repo ? repoOwner(row.account_id, repo) : null } } @@ -329,16 +335,22 @@ export type ResolvedSecrets = { env: Record; scopes: Record + row: Pick ): Promise { const owners = ownersForSandbox(row) - const pairs: [SecretScope, string][] = [['personal', owners.personal]] + const pairs: [SecretScope, string][] = [] + if (owners.personal) { + pairs.push(['personal', owners.personal]) + } if (owners.org) { pairs.push(['org', owners.org]) } if (owners.repo) { pairs.push(['repo', owners.repo]) } + if (pairs.length === 0) { + return { env: {}, scopes: {}, skipped: 0 } + } const where = pairs.map(() => '(scope = ? AND owner_id = ?)').join(' OR ') const { results } = await db .prepare(`SELECT * FROM secrets WHERE ${where}`) diff --git a/cloud/apps/sandbox-control/src/session-env.ts b/cloud/apps/sandbox-control/src/session-env.ts index 92d2a15c485..7f7bb7a8c36 100644 --- a/cloud/apps/sandbox-control/src/session-env.ts +++ b/cloud/apps/sandbox-control/src/session-env.ts @@ -27,7 +27,7 @@ export type ProviderEnv = { env: Record; scopes: Record + row: Pick ): Promise { const { env: stored, scopes } = await resolveSandboxSecrets(db, keyring, row) // The proxy only needs the keys; dropping those of agents not on 'keep' happens at request time @@ -43,7 +43,8 @@ const PROVIDER_ENV_CACHE_MS = 60_000 const providerEnvCache = new Map }>() export function cachedProviderEnv(db: D1Database, keyring: Keyring, row: SandboxRow, now: number): Promise { - const key = `${row.id}:${row.session_id ?? ''}` + // Visibility is part of the key: sharing a workspace stops its owner's personal keys at once (SEC-5). + const key = `${row.id}:${row.session_id ?? ''}:${row.visibility}` const hit = providerEnvCache.get(key) if (hit && now - hit.at < PROVIDER_ENV_CACHE_MS) { return hit.value diff --git a/cloud/apps/sandbox-control/test/shared-workspace-secrets.test.ts b/cloud/apps/sandbox-control/test/shared-workspace-secrets.test.ts new file mode 100644 index 00000000000..e4e92b532ab --- /dev/null +++ b/cloud/apps/sandbox-control/test/shared-workspace-secrets.test.ts @@ -0,0 +1,216 @@ +// SEC-5: a workspace shared with teammates runs their shells too, so nothing personal to its owner may +// be in its env: not a variable's value, and not a placeholder that would spend the owner's model key. +import { SignJWT, createLocalJWKSet, exportJWK, generateKeyPair } from 'jose' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ENV_COMMAND, START_COMMAND } from '../src/sandbox-vm-commands' +import { ownersForSandbox } from '../src/secrets' +import { createHarness } from './harness' + +const KEK = Buffer.alloc(32, 7).toString('base64') +const PROXY_URL = 'https://sandbox.test/v1/egress/proxy' +// Fake values only. +const TEAM_KEY = 'sk-ant-api03-TEAM-fake-0000-aaaa' +const PERSONAL_OPENAI = 'sk-proj-fake-personal-openai-2222' +const PERSONAL_VALUES = [PERSONAL_OPENAI, 'personal-db-password', 'personal-foo-value', 'personal-aws-secret-value'] + +type Harness = Awaited> + +const logs: string[] = [] +beforeEach(() => { + logs.length = 0 + for (const method of ['log', 'info', 'warn', 'error', 'debug'] as const) { + vi.spyOn(console, method).mockImplementation((...args: unknown[]) => { + logs.push(args.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' ')) + }) + } +}) +afterEach(() => { + for (const value of [...PERSONAL_VALUES, TEAM_KEY]) { + expect(logs.join('\n')).not.toContain(value) + } + vi.restoreAllMocks() +}) + +function decodeEnv(encoded: string | undefined): Record { + return Object.fromEntries( + (encoded ?? '') + .split('\n') + .filter(Boolean) + .map((line) => { + const at = line.indexOf('=') + return [line.slice(0, at), Buffer.from(line.slice(at + 1), 'base64').toString('utf8')] + }) + ) +} + +/** The env the VM got at its last boot, or from its last live refresh. */ +function vmEnv(h: Harness, command: string = START_COMMAND): Record { + return decodeEnv(h.vercel.commands.filter((c) => c.command === command).at(-1)!.env.ORCA_SECRET_ENV) +} + +/** Everything the control plane ever sent the VM, as one string: no personal value may be in it. */ +function everythingSent(h: Harness, from = 0): string { + return JSON.stringify( + h.vercel.commands.slice(from).map((c) => ({ ...c, env: { ...c.env, ORCA_SECRET_ENV: decodeEnv(c.env.ORCA_SECRET_ENV) } })) + ) +} + +async function seeded(overrides: Record = {}, deps: Parameters[1] = {}) { + const h = await createHarness({ SECRETS_KEK: KEK, ...overrides }, deps) + const admin = await h.token('ada', 'acme', 'sandbox', { orgRole: 'admin' }) + const mia = await h.token('mia', 'acme', 'sandbox', { orgRole: 'member' }) + const put = (scope: string, name: string, value: string, bearer: string, repo?: string) => + h.call('PUT', `/v1/secrets/${scope}/${name}${repo ? `?repo=${encodeURIComponent(repo)}` : ''}`, { body: { value }, bearer }) + await put('org', 'ANTHROPIC_API_KEY', TEAM_KEY, admin) + await put('org', 'FOO', 'team-foo-value', admin) + await put('repo', 'BAR', 'repo-bar-value', admin, 'acme/app') + await put('personal', 'OPENAI_API_KEY', PERSONAL_OPENAI, mia) + await put('personal', 'DB_PASSWORD', 'personal-db-password', mia) + await put('personal', 'FOO', 'personal-foo-value', mia) + await put('personal', 'AWS_SECRET_ACCESS_KEY', 'personal-aws-secret-value', mia) + const create = (visibility?: 'team' | 'private') => + h.call('POST', '/v1/sandboxes', { + body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, ...(visibility ? { visibility } : {}) }, + bearer: mia + }) + const share = (id: string, visibility: 'team' | 'private') => + h.call('PATCH', `/v1/team/workspaces/${id}`, { body: { visibility }, bearer: mia }) + return { h, mia, admin, put, create, share } +} + +const TEAM_AND_REPO = { ANTHROPIC_API_KEY: TEAM_KEY, BAR: 'repo-bar-value', FOO: 'team-foo-value' } + +describe('personal secrets in shared workspaces (SEC-5)', () => { + it('resolves no personal owner for a shared row, and fails closed on an unknown visibility', () => { + const row = { account_id: 'org:acme', user_id: 'mia', repo_url: 'https://github.com/acme/app' } + expect(ownersForSandbox({ ...row, visibility: 'private' }).personal).toBe('user:mia') + expect(ownersForSandbox({ ...row, visibility: 'team' })).toEqual({ org: 'org:acme', personal: null, repo: 'org:acme#github.com/acme/app' }) + expect(ownersForSandbox({ ...row, visibility: undefined as never }).personal).toBeNull() + }) + + it('keeps the owner’s personal secrets in their own private workspace', async () => { + const { h, create } = await seeded() + expect((await create()).status).toBe(200) + expect(vmEnv(h)).toEqual({ + ...TEAM_AND_REPO, + AWS_SECRET_ACCESS_KEY: 'personal-aws-secret-value', + DB_PASSWORD: 'personal-db-password', + FOO: 'personal-foo-value', + OPENAI_API_KEY: PERSONAL_OPENAI + }) + }) + + it('starts a shared workspace with team and repository secrets only; the team value replaces a personal override', async () => { + const { h, create } = await seeded() + expect((await create('team')).status).toBe(200) + expect(vmEnv(h)).toEqual(TEAM_AND_REPO) + for (const value of PERSONAL_VALUES) { + expect(everythingSent(h)).not.toContain(value) + } + }) + + it('drops them from a running workspace the moment it is shared, and brings them back when it is private again', async () => { + const { h, create, share, mia } = await seeded() + const id: string = (await create()).body.sandbox.id + expect(vmEnv(h).DB_PASSWORD).toBe('personal-db-password') + const before = h.vercel.commands.length + + expect((await share(id, 'team')).status).toBe(200) + expect(vmEnv(h, ENV_COMMAND)).toEqual(TEAM_AND_REPO) + for (const value of PERSONAL_VALUES) { + expect(everythingSent(h, before)).not.toContain(value) + } + // A wake while shared resolves the same way. + await h.call('POST', `/v1/sandboxes/${id}/suspend`, { bearer: mia }) + await h.call('POST', `/v1/sandboxes/${id}/resume`, { bearer: mia }) + expect(vmEnv(h)).toEqual(TEAM_AND_REPO) + + expect((await share(id, 'private')).status).toBe(200) + expect(vmEnv(h, ENV_COMMAND)).toMatchObject({ DB_PASSWORD: 'personal-db-password', FOO: 'personal-foo-value' }) + }) + + it('does not pick up a personal secret the owner saves while the workspace is shared', async () => { + const { h, create, put, mia } = await seeded() + await create('team') + await put('personal', 'LATER', 'personal-db-password', mia) + const refreshes = h.vercel.commands.filter((c) => c.command === ENV_COMMAND) + for (const refresh of refreshes) { + expect(decodeEnv(refresh.env.ORCA_SECRET_ENV)).toEqual(TEAM_AND_REPO) + } + }) +}) + +describe('personal model keys in shared workspaces with egress placeholders (SEC-5)', () => { + async function placeholderSetup() { + const { privateKey, publicKey } = await generateKeyPair('RS256') + const jwks = { keys: [{ ...(await exportJWK(publicKey)), kid: 'v1', alg: 'RS256' }] } + const upstream: { url: string; headers: Headers }[] = [] + const ctx = await seeded( + { SECRETS_EGRESS_PLACEHOLDERS: 'on', EGRESS_PROXY_URL: PROXY_URL }, + { + egressKeysForIssuer: () => createLocalJWKSet(jwks), + credentials: { authorizationFor: async () => 'Bearer ghs_fake' }, + egressFetch: async (input, init) => { + upstream.push({ url: String(input), headers: new Headers(init?.headers) }) + return new Response('ok', { status: 200 }) + } + } + ) + async function proxied(sandboxId: string, host: string, headers: Record) { + const token = await new SignJWT({ team_id: 'team_orca', project_id: 'prj_orca', sandbox_name: `orca-test-${sandboxId}` }) + .setProtectedHeader({ alg: 'RS256', kid: 'v1' }) + .setIssuer('https://oidc.vercel.com/team_orca') + .setAudience(PROXY_URL) + .setIssuedAt() + .setExpirationTime('5m') + .sign(privateKey) + const response = await ctx.h.send( + new Request(`${PROXY_URL}/v1/messages`, { + method: 'POST', + body: '{"model":"x"}', + headers: { + 'vercel-forwarded-host': host, + 'vercel-forwarded-scheme': 'https', + 'vercel-forwarded-port': '443', + 'vercel-forwarded-path': '/v1/messages', + 'vercel-sandbox-oidc-token': token, + ...headers + } + }) + ) + return response.status + } + return { ...ctx, proxied, upstream } + } + + it('gives a shared workspace no placeholder and no route for the owner’s personal key; the team key still works', async () => { + const { h, create, proxied, upstream } = await placeholderSetup() + const id: string = (await create('team')).body.sandbox.id + const env = vmEnv(h) + expect(env.ANTHROPIC_API_KEY).toBe(`orca-ph-anthropic-api-key-${id}`) + expect(env).not.toHaveProperty('OPENAI_API_KEY') + expect(env).not.toHaveProperty('DB_PASSWORD') + const [box] = [...h.vercel.boxes.values()] + // No forward rule for the personal key: the host is plain allowlisted, nothing is swapped there. + expect(box!.policy.allow['api.openai.com']).toEqual([]) + expect(await proxied(id, 'api.openai.com', { authorization: `Bearer orca-ph-openai-api-key-${id}` })).toBe(403) + expect(await proxied(id, 'api.anthropic.com', { 'x-api-key': `orca-ph-anthropic-api-key-${id}` })).toBe(200) + expect(upstream).toHaveLength(1) + expect(upstream[0]!.headers.get('x-api-key')).toBe(TEAM_KEY) + }) + + it('stops swapping the owner’s personal key at the proxy as soon as a running workspace is shared', async () => { + const { h, create, share, proxied, upstream } = await placeholderSetup() + const id: string = (await create()).body.sandbox.id + const placeholder = `orca-ph-openai-api-key-${id}` + expect(vmEnv(h).OPENAI_API_KEY).toBe(placeholder) + expect(await proxied(id, 'api.openai.com', { authorization: `Bearer ${placeholder}` })).toBe(200) + expect(upstream.at(-1)!.headers.get('authorization')).toBe(`Bearer ${PERSONAL_OPENAI}`) + + expect((await share(id, 'team')).status).toBe(200) + expect(vmEnv(h, ENV_COMMAND)).not.toHaveProperty('OPENAI_API_KEY') + // A process still holding the old placeholder gets nothing for it. + expect(await proxied(id, 'api.openai.com', { authorization: `Bearer ${placeholder}` })).toBe(403) + expect(upstream).toHaveLength(1) + }) +}) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index fb899cecf65..5533b809edb 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -221,8 +221,15 @@ export function CloudWorkspacesHome({ void refreshCloudMessageSenders().catch(() => undefined) } if (change.visibility === 'team') { + // SEC-5: the owner's personal secrets stop being injected once teammates can open it. toast.success( - t('auto.components.cloudWorkspaces.sharedWithYourTeam', 'Shared with your team') + t('auto.components.cloudWorkspaces.sharedWithYourTeam', 'Shared with your team'), + { + description: t( + 'auto.components.cloudWorkspaces.sharedPersonalSecretsNote', + 'Your personal cloud secrets aren’t used in shared workspaces. Shared and repository secrets still are.' + ) + } ) } else if (change.visibility === 'private') { toast.success( diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx index 22695bdef73..ab4fc3cb34c 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx @@ -178,14 +178,25 @@ async function setVisibility( ) return } - toast.success( - visibility === 'team' - ? t('auto.components.cloudWorkspaces.sharedWithYourTeam', 'Shared with your team') - : t( - 'auto.components.cloudWorkspaces.nowPrivate', - 'Now private. Teammates’ devices were disconnected.' + if (visibility === 'team') { + // SEC-5: the owner's personal secrets stop being injected once teammates can open it. + toast.success( + t('auto.components.cloudWorkspaces.sharedWithYourTeam', 'Shared with your team'), + { + description: t( + 'auto.components.cloudWorkspaces.sharedPersonalSecretsNote', + 'Your personal cloud secrets aren’t used in shared workspaces. Shared and repository secrets still are.' ) - ) + } + ) + } else { + toast.success( + t( + 'auto.components.cloudWorkspaces.nowPrivate', + 'Now private. Teammates’ devices were disconnected.' + ) + ) + } reload() } diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPane.fixture.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPane.fixture.tsx index ad5d0d8ea23..ab2291b3601 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPane.fixture.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPane.fixture.tsx @@ -199,7 +199,7 @@ function list( initialMode={mode} initialSaved={options.saved} onSetUpAgent={noop} - description="Only you get these, in every Orca Cloud workspace you start." + description="Only you get these, in cloud workspaces you haven’t shared. Shared workspaces don’t get them." /> ) diff --git a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPane.tsx b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPane.tsx index ca4475202fd..70d236a775e 100644 --- a/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPane.tsx +++ b/src/renderer/src/components/settings/cloud-secrets/CloudSecretsPane.tsx @@ -201,8 +201,8 @@ export function CloudSecretsPane({ ) : null } description={t( - 'cloudSecrets.personal.description', - 'Only you get these, in every Orca Cloud workspace you start.' + 'cloudSecrets.personal.descriptionUnshared', + 'Only you get these, in cloud workspaces you haven’t shared. Shared workspaces don’t get them.' )} emptyTitle={t('cloudSecrets.personal.emptyTitle', 'No personal secrets yet')} emptyDetail={t( diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b396585c676..aa8947d3d48 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -21606,7 +21606,8 @@ "errorTrialSandboxLimit_one": "Your trial can run {{count}} sandbox at once. Put it to sleep or delete it, then try again.", "errorTrialSandboxLimit_other": "Your trial can run {{count}} sandboxes at once. Put one to sleep or delete it, then try again.", "errorTeamSandboxLimitNoSeat_one": "Your team can run {{count}} sandbox at once. Put it to sleep or delete it, then try again.", - "errorTeamSandboxLimitNoSeat_other": "Your team can run {{count}} sandboxes at once. Put one to sleep or delete it, then try again." + "errorTeamSandboxLimitNoSeat_other": "Your team can run {{count}} sandboxes at once. Put one to sleep or delete it, then try again.", + "sharedPersonalSecretsNote": "Your personal cloud secrets aren’t used in shared workspaces. Shared and repository secrets still are." }, "orcaCloud": { "QueuedPrompt": { @@ -28032,7 +28033,8 @@ "personal": { "description": "Only you get these, in every Orca Cloud workspace you start.", "emptyTitle": "No personal secrets yet", - "emptyDetail": "Add one or paste a .env file. New terminals and agents in your cloud workspaces get them as environment variables." + "emptyDetail": "Add one or paste a .env file. New terminals and agents in your cloud workspaces get them as environment variables.", + "descriptionUnshared": "Only you get these, in cloud workspaces you haven’t shared. Shared workspaces don’t get them." }, "org": { "description": "Everyone on your team gets these in their Orca Cloud workspaces.", From 24ba947167b0eecb03224cca558aa8ce28796057 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 22:11:58 -0800 Subject: [PATCH 12/28] fix(cloud): design review: contraction, no MFA badge before first sign-in, link style on the setup screen --- .../billing/team/TeamMemberList.test.tsx | 17 +++++++++++ .../billing/team/TeamMemberList.tsx | 6 +++- .../src/components/team-mfa/TeamMfaBanner.tsx | 29 ++++++++++--------- .../team-mfa/TeamMfaBlockedScreen.tsx | 8 ++++- .../src/components/team-mfa/team-mfa.test.tsx | 13 +++++---- src/renderer/src/i18n/locales/en.json | 2 +- 6 files changed, 53 insertions(+), 22 deletions(-) diff --git a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx index b9d94b343ca..849ae209ecc 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx @@ -137,3 +137,20 @@ it('leaves the cell blank, not "off", for a member with no status', () => { expect(cell('member:u-neil').textContent).toBe('MFA off') expect(cell('member:u-grace').textContent).toBe('') }) + +it('shows no MFA badge for a member who has not signed in yet', () => { + const { container } = renderList( + { + ...roster, + members: [ + { ...roster.members[0]!, mfa: 'on' }, + { userId: null, email: 'linus@acme.dev', role: 'member', mfa: 'off' } + ] + }, + 'u-neil' + ) + const pending = container.querySelector( + '[data-team-row="member:linus@acme.dev"] [data-team-mfa]' + )! + expect(pending.textContent).toBe('') +}) diff --git a/src/renderer/src/components/billing/team/TeamMemberList.tsx b/src/renderer/src/components/billing/team/TeamMemberList.tsx index 0e23b4d765c..c23a07c9b61 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.tsx @@ -322,7 +322,11 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element { data-team-mfa={row.kind === 'member' ? (row.member.mfa ?? '') : ''} className="flex w-28 shrink-0" > - {row.kind === 'member' && memberMfaLabel(row.member, locale, t) ? ( + {/* Only for members who have signed in: someone still pending has no account + state yet, so "off" would mislead. */} + {row.kind === 'member' && + row.status === 'active' && + memberMfaLabel(row.member, locale, t) ? ( {memberMfaLabel(row.member, locale, t)} ) : null} diff --git a/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx b/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx index cd03511e892..6f57b82ef1a 100644 --- a/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfaBanner.tsx @@ -37,23 +37,24 @@ export function TeamMfaBanner({ const t = useTranslate() const locale = useIntlLocale() const urgency = mfaUrgency(enforceAt, now, blocked) - const title = urgency === 'soon' - ? mfaSoonTitle(teamName, enforceAt, now, t) - : blocked - ? t( - 'auto.components.teamMfa.bannerBlockedTitle', - '{{value0}} requires two-factor authentication', - { value0: teamName } - ) - : t( - 'auto.components.teamMfa.bannerTitle', - '{{value0}} requires two-factor authentication. {{value1}}.', - { value0: teamName, value1: mfaCountdownLabel(enforceAt, now, t) } - ) + const title = + urgency === 'soon' + ? mfaSoonTitle(teamName, enforceAt, now, t) + : blocked + ? t( + 'auto.components.teamMfa.bannerBlockedTitle', + '{{value0}} requires two-factor authentication', + { value0: teamName } + ) + : t( + 'auto.components.teamMfa.bannerTitle', + '{{value0}} requires two-factor authentication. {{value1}}.', + { value0: teamName, value1: mfaCountdownLabel(enforceAt, now, t) } + ) const detail = blocked ? t( 'auto.components.teamMfa.bannerBlockedBody', - 'You can’t use this team’s workspaces until you set it up. Your personal account is not affected.' + 'You can’t use this team’s workspaces until you set it up. Your personal account isn’t affected.' ) : t( 'auto.components.teamMfa.bannerBody', diff --git a/src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx b/src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx index b2ea07b51ce..bb18047e2ec 100644 --- a/src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx @@ -84,7 +84,13 @@ export function TeamMfaBlockedScreen({ : null}

    {onUsePersonal ? ( - ) : null} diff --git a/src/renderer/src/components/team-mfa/team-mfa.test.tsx b/src/renderer/src/components/team-mfa/team-mfa.test.tsx index 6a07012637c..18999d7b3b2 100644 --- a/src/renderer/src/components/team-mfa/team-mfa.test.tsx +++ b/src/renderer/src/components/team-mfa/team-mfa.test.tsx @@ -50,9 +50,9 @@ describe('what the member sees', () => { expect(teamMfaSurface(policy())).toBe('banner') expect(teamMfaSurface(policy({ self: 'blocked' }))).toBe('blocked') // Past the deadline by the local clock, but the server still says pending: not blocked. - expect( - teamMfaSurface(policy({ policy: { enforceAt: NOW - DAY, setAt: NOW - 8 * DAY } })) - ).toBe('banner') + expect(teamMfaSurface(policy({ policy: { enforceAt: NOW - DAY, setAt: NOW - 8 * DAY } }))).toBe( + 'banner' + ) }) it('is nothing with MFA on, an unknown state, or no policy', () => { @@ -241,7 +241,7 @@ describe('banner after the deadline', () => { ) expect(container.textContent).toContain('Acme requires two-factor authentication') expect(container.textContent).toContain('until you set it up') - expect(container.textContent).toContain('Your personal account is not affected') + expect(container.textContent).toContain('Your personal account isn’t affected') expect(container.textContent).not.toContain('days left') expect(getByRole('button', { name: 'Set up MFA' })).toBeTruthy() }) @@ -290,7 +290,10 @@ describe('escalation', () => { describe('one-time toast', () => { const memory = (): Pick => { const map = new Map() - return { getItem: (key) => map.get(key) ?? null, setItem: (key, value) => void map.set(key, value) } + return { + getItem: (key) => map.get(key) ?? null, + setItem: (key, value) => void map.set(key, value) + } } it('shows once per team and deadline, and again when the date changes', () => { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index af32b910741..312e56a8eae 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -21712,7 +21712,7 @@ "soonTitle_one": "{{value0}} requires MFA in {{count}} day", "soonTitle_other": "{{value0}} requires MFA in {{count}} days", "toast": "{{value0}} requires MFA from {{value1}}.", - "bannerBlockedBody": "You can’t use this team’s workspaces until you set it up. Your personal account is not affected.", + "bannerBlockedBody": "You can’t use this team’s workspaces until you set it up. Your personal account isn’t affected.", "setUp": "Set up MFA", "blockedTitle": "Set up two-factor authentication to use {{value0}}", "blockedBody": "{{value0}} has required it for all members since {{value1}}. Your workspaces and files are safe, and open again as soon as you add an authenticator app.", From 10a6999ef7a98f9eedd44255aef58e1401f78535 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 22:16:40 -0800 Subject: [PATCH 13/28] fix(cloud): SEC-5 share toast through one helper; drop the replaced private catalog key --- .../cloud-workspaces/CloudWorkspacesHome.tsx | 12 ++---------- .../cloud-workspaces/shared-with-team-toast.ts | 15 +++++++++++++++ .../orca-cloud/CloudWorkspaceMenuItems.tsx | 12 ++---------- src/renderer/src/i18n/locales/en.json | 1 - 4 files changed, 19 insertions(+), 21 deletions(-) create mode 100644 src/renderer/src/components/cloud-workspaces/shared-with-team-toast.ts diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index 5533b809edb..094144d9230 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -32,6 +32,7 @@ import { useCloudReadPanel } from './use-cloud-read-panel' import type { MemberDirectory } from './cloud-workspace-format' import { refreshCloudMessageSenders } from '@/lib/cloud-message-sender' import { describeError } from './cloud-workspace-errors' +import { toastSharedWithTeam } from './shared-with-team-toast' import { focusCloudChat } from './cloud-chat-focus' import * as homeArchive from './cloud-workspace-home-archive' import { focusedKind, frontCloudChat } from './cloud-workspace-links' @@ -221,16 +222,7 @@ export function CloudWorkspacesHome({ void refreshCloudMessageSenders().catch(() => undefined) } if (change.visibility === 'team') { - // SEC-5: the owner's personal secrets stop being injected once teammates can open it. - toast.success( - t('auto.components.cloudWorkspaces.sharedWithYourTeam', 'Shared with your team'), - { - description: t( - 'auto.components.cloudWorkspaces.sharedPersonalSecretsNote', - 'Your personal cloud secrets aren’t used in shared workspaces. Shared and repository secrets still are.' - ) - } - ) + toastSharedWithTeam(t) } else if (change.visibility === 'private') { toast.success( t( diff --git a/src/renderer/src/components/cloud-workspaces/shared-with-team-toast.ts b/src/renderer/src/components/cloud-workspaces/shared-with-team-toast.ts new file mode 100644 index 00000000000..b40318b1ab7 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/shared-with-team-toast.ts @@ -0,0 +1,15 @@ +import { toast } from 'sonner' +import type { Translate } from '@/i18n/use-translate' + +/** + * "Shared with your team", with the one thing that changes for the owner (SEC-5): their personal + * secrets stop being injected once teammates can open the workspace. + */ +export function toastSharedWithTeam(t: Translate): void { + toast.success(t('auto.components.cloudWorkspaces.sharedWithYourTeam', 'Shared with your team'), { + description: t( + 'auto.components.cloudWorkspaces.sharedPersonalSecretsNote', + 'Your personal cloud secrets aren’t used in shared workspaces. Shared and repository secrets still are.' + ) + }) +} diff --git a/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx b/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx index ab4fc3cb34c..11e46733bc3 100644 --- a/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx +++ b/src/renderer/src/components/orca-cloud/CloudWorkspaceMenuItems.tsx @@ -12,6 +12,7 @@ import { } from 'lucide-react' import { DropdownMenuItem, DropdownMenuSeparator } from '@/components/ui/dropdown-menu' import { useTranslate } from '@/i18n/use-translate' +import { toastSharedWithTeam } from '@/components/cloud-workspaces/shared-with-team-toast' import { isCloudSyncAvailable, requestCloudSyncFocus } from '@/lib/orca-cloud/cloud-sync-store' import { ConfirmationDialogContext, @@ -179,16 +180,7 @@ async function setVisibility( return } if (visibility === 'team') { - // SEC-5: the owner's personal secrets stop being injected once teammates can open it. - toast.success( - t('auto.components.cloudWorkspaces.sharedWithYourTeam', 'Shared with your team'), - { - description: t( - 'auto.components.cloudWorkspaces.sharedPersonalSecretsNote', - 'Your personal cloud secrets aren’t used in shared workspaces. Shared and repository secrets still are.' - ) - } - ) + toastSharedWithTeam(t) } else { toast.success( t( diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index c44781927fa..2c9dbbad384 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -28032,7 +28032,6 @@ }, "setUpAgent": "Set up an agent", "personal": { - "description": "Only you get these, in every Orca Cloud workspace you start.", "emptyTitle": "No personal secrets yet", "emptyDetail": "Add one or paste a .env file. New terminals and agents in your cloud workspaces get them as environment variables.", "descriptionUnshared": "Only you get these, in cloud workspaces you haven’t shared. Shared workspaces don’t get them." From 4ea9f1288058230af1c57ad799e25e2771ef3a78 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 22:32:45 -0800 Subject: [PATCH 14/28] fix(recipes): render passEnv as code in the narrowed recipe-env headline Design-squad sign-off on agentHostPanel.recipeEnvNarrowed: same text, with passEnv in a code span so it reads as the orca.yaml key. Co-Authored-By: Claude --- .../RecipeEnvForwardingWarning.test.tsx | 25 +++++++++++++++++++ .../RecipeEnvForwardingWarning.tsx | 23 +++++++++++------ src/renderer/src/i18n/locales/en.json | 2 +- 3 files changed, 42 insertions(+), 8 deletions(-) create mode 100644 src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.test.tsx diff --git a/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.test.tsx b/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.test.tsx new file mode 100644 index 00000000000..00718ef0fae --- /dev/null +++ b/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.test.tsx @@ -0,0 +1,25 @@ +// @vitest-environment happy-dom +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, it } from 'vitest' +import { RecipeEnvForwardingWarning } from './RecipeEnvForwardingWarning' + +afterEach(cleanup) + +const summary = { count: 2, keyLike: ['AWS_SECRET_ACCESS_KEY'], other: ['PATH'] } + +it('says the recipe gets only what its passEnv allows, with passEnv as code', () => { + render() + const code = screen.getByText('passEnv') + expect(code.tagName).toBe('CODE') + expect(code.parentElement?.textContent).toBe( + "This recipe's create script gets only the variables its passEnv allows." + ) + expect(screen.queryByText(/this computer's environment/)).toBeNull() +}) + +it("keeps the whole-environment headline when passEnv didn't apply", () => { + render() + expect( + screen.getByText("This recipe's create script gets this computer's environment.") + ).toBeTruthy() +}) diff --git a/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.tsx b/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.tsx index abb228f99de..6e4b48150c6 100644 --- a/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.tsx +++ b/src/renderer/src/components/agent-host-panel/RecipeEnvForwardingWarning.tsx @@ -1,6 +1,8 @@ import { TriangleAlert } from 'lucide-react' import type React from 'react' import { useEffect, useId, useState } from 'react' +import { Trans } from 'react-i18next' +import { i18n } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { Button } from '../ui/button' import { Skeleton } from '../ui/skeleton' @@ -71,15 +73,22 @@ export function RecipeEnvForwardingWarning({

    - {summary?.narrowed - ? t( + {summary?.narrowed ? ( + // passEnv is an orca.yaml key, so it reads as code rather than a word. + passEnv allows." )} + components={{ code: }} + /> + ) : ( + t( + 'agentHostPanel.recipeEnv', + "This recipe's create script gets this computer's environment." + ) + )}

    {summary === null ? ( diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index e74f6cabd73..52299f52065 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -28468,7 +28468,7 @@ "deviceStep": "Enter this code on auth.openai.com. The sign-in is saved on {{host}}.", "codePlaceholder": "Paste the code" }, - "recipeEnvNarrowed": "This recipe's create script gets only the variables its passEnv allows." + "recipeEnvNarrowed": "This recipe's create script gets only the variables its passEnv allows." }, "cloudSecretsAsk": { "scopeLabel": "Scope for {{name}}", From ebacf7c882b16ef62cc91f606f30a50f40c48ce2 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 22:47:05 -0800 Subject: [PATCH 15/28] fix(cloud): premerge lint: type guards instead of assertions, MFA member fields in their own file, runtime catalog, link-muted button --- .../hosted-sandbox-config.test.ts | 2 +- .../hosted-sandbox/hosted-sandbox-config.ts | 9 +++-- .../orca-profile-org-members-handlers.ts | 17 +++++----- .../cloud-mfa/profile-cloud-mfa-service.ts | 10 ++++-- .../profile-cloud-team-mfa-service.ts | 33 +++++++++++-------- .../profile-cloud-org-members-client.ts | 2 +- .../team-mfa/TeamMfaBlockedScreen.tsx | 8 +---- .../src/components/team-mfa/team-mfa.test.tsx | 4 +-- .../src/i18n/en-runtime-required.json | 12 +++++++ src/shared/orca-account-mfa.ts | 14 ++++++++ src/shared/orca-profiles.ts | 14 ++------ 11 files changed, 75 insertions(+), 50 deletions(-) diff --git a/src/main/hosted-sandbox/hosted-sandbox-config.test.ts b/src/main/hosted-sandbox/hosted-sandbox-config.test.ts index 143960b1ab1..c22aa14be3d 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-config.test.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-config.test.ts @@ -126,7 +126,7 @@ describe('isMfaRequiredRefusal', () => { { status: 403 } ) expect(await isMfaRequiredRefusal(response)).toBe(true) - expect(((await response.json()) as { orgId: string }).orgId).toBe('org_1') + expect(await response.json()).toMatchObject({ orgId: 'org_1' }) }) it('is false for other refusals and for bodies that are not JSON', async () => { diff --git a/src/main/hosted-sandbox/hosted-sandbox-config.ts b/src/main/hosted-sandbox/hosted-sandbox-config.ts index 973ab6596e5..6558709f8af 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-config.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-config.ts @@ -28,8 +28,13 @@ export const MFA_REQUIRED_REASON = 'mfa_required' /** Reads a copy of the body, so the caller can still read the response. */ export async function isMfaRequiredRefusal(response: Response): Promise { try { - const body = (await response.clone().json()) as { error?: unknown } | null - return body?.error === MFA_REQUIRED_REASON + const body: unknown = await response.clone().json() + return ( + typeof body === 'object' && + body !== null && + 'error' in body && + body.error === MFA_REQUIRED_REASON + ) } catch { return false } diff --git a/src/main/ipc/profiles/orca-profile-org-members-handlers.ts b/src/main/ipc/profiles/orca-profile-org-members-handlers.ts index 455bdc47600..889b38d0d94 100644 --- a/src/main/ipc/profiles/orca-profile-org-members-handlers.ts +++ b/src/main/ipc/profiles/orca-profile-org-members-handlers.ts @@ -160,9 +160,8 @@ export function registerOrcaProfileOrgMemberHandlers(): void { createOrcaProfileOrg(getProfileUserDataPath(), { name: orgCreateNameFromUnknown(rawArgs) }) ) - ipcMain.handle( - 'orcaProfiles:accountMfa', - async (): Promise => getOrcaProfileAccountMfa(getProfileUserDataPath()) + ipcMain.handle('orcaProfiles:accountMfa', async (): Promise => + getOrcaProfileAccountMfa(getProfileUserDataPath()) ) ipcMain.handle( @@ -175,15 +174,15 @@ export function registerOrcaProfileOrgMemberHandlers(): void { 'orcaProfiles:teamMfaPolicySet', async (_event, rawArgs: unknown): Promise => { const { orgId, record } = orgMembersScopedArgs(rawArgs) - const enforce = record.enforce // Only the fixed choices cross to the server; anything else is refused here. - if (enforce !== 'off' && !ORCA_TEAM_MFA_GRACE_CHOICES.some((choice) => choice === enforce)) { + const enforce: OrcaTeamMfaGrace | 'off' | undefined = + record.enforce === 'off' + ? 'off' + : ORCA_TEAM_MFA_GRACE_CHOICES.find((choice) => choice === record.enforce) + if (enforce === undefined) { return { status: 'failed', error: 'invalid_enforce' } } - return setOrcaTeamMfaPolicy(getProfileUserDataPath(), { - orgId, - enforce: enforce as OrcaTeamMfaGrace | 'off' - }) + return setOrcaTeamMfaPolicy(getProfileUserDataPath(), { orgId, enforce }) } ) diff --git a/src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.ts b/src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.ts index a901526a3cb..f4349260791 100644 --- a/src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.ts +++ b/src/main/orca-profiles/cloud-mfa/profile-cloud-mfa-service.ts @@ -15,7 +15,8 @@ import { ensureActiveOrcaProfile } from '../profile-index-store' * a compromised or misconfigured answer cannot send the person to another site to "set up MFA". */ export function normalizeAccountMfa(value: unknown, apiBaseUrl: string): OrcaAccountMfa { - const record = value && typeof value === 'object' ? (value as Record) : {} + const record: Record = + typeof value === 'object' && value !== null ? { ...value } : {} const mfa = record.mfa === 'on' || record.mfa === 'off' ? record.mfa : null let setupUrl: URL | null = null try { @@ -46,10 +47,13 @@ async function fetchAccountMfa( if (!response.ok) { throw new OrcaCloudRequestError(response.status, await extractErrorCode(response)) } - return normalizeAccountMfa((await response.json()) as unknown, config.apiBaseUrl) + const body: unknown = await response.json() + return normalizeAccountMfa(body, config.apiBaseUrl) } -export async function getOrcaProfileAccountMfa(userDataPath: string): Promise { +export async function getOrcaProfileAccountMfa( + userDataPath: string +): Promise { const active = ensureActiveOrcaProfile(userDataPath) // Local dev auth has no server and no factor to enrol. if (isOrcaCloudDevAuthEnabled()) { diff --git a/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts index ae7f8101976..88cb059de74 100644 --- a/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts +++ b/src/main/orca-profiles/cloud-mfa/profile-cloud-team-mfa-service.ts @@ -25,6 +25,10 @@ import { } from '../cloud-org/profile-cloud-org-members-service' import { ensureActiveOrcaProfile } from '../profile-index-store' +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + const SELF_STATES: readonly OrcaTeamMfaSelfState[] = ['on', 'off', 'pending', 'blocked', 'unknown'] function finiteNumber(value: unknown): number | null { @@ -47,27 +51,25 @@ export function sameOriginUrl(value: unknown, apiBaseUrl: string): string | null } function normalizeDeadline(value: unknown): { enforceAt: number; setAt: number } | null { - const record = value && typeof value === 'object' ? (value as Record) : null + const record = isRecord(value) ? value : null const enforceAt = finiteNumber(record?.enforceAt) const setAt = finiteNumber(record?.setAt) return enforceAt !== null && setAt !== null ? { enforceAt, setAt } : null } export function normalizeTeamMfaPolicy(value: unknown, apiBaseUrl: string): OrcaTeamMfaPolicy { - const record = value && typeof value === 'object' ? (value as Record) : null + const record = isRecord(value) ? value : null const setupUrl = sameOriginUrl(record?.setupUrl, apiBaseUrl) if (!record || !setupUrl) { throw new Error('invalid_orca_team_mfa_policy') } - const selfRecord = - record.self && typeof record.self === 'object' ? (record.self as Record) : {} + const selfRecord = isRecord(record.self) ? record.self : {} // An unrecognized state is "unknown", never "blocked": only the server's word blocks anyone. const self = SELF_STATES.find((state) => state === selfRecord.mfa) ?? 'unknown' const pendingMembers = finiteNumber(record.pendingMembers) - const inactive = - record.inactivePolicy && typeof record.inactivePolicy === 'object' - ? finiteNumber((record.inactivePolicy as Record).enforceAt) - : null + const inactive = isRecord(record.inactivePolicy) + ? finiteNumber(record.inactivePolicy.enforceAt) + : null return { policy: normalizeDeadline(record.policy), self, @@ -86,10 +88,10 @@ export function normalizeTeamMfaPolicy(value: unknown, apiBaseUrl: string): Orca } export function normalizePendingMembers(value: unknown): OrcaTeamMfaPendingMember[] { - const record = value && typeof value === 'object' ? (value as Record) : null + const record = isRecord(value) ? value : null const members = Array.isArray(record?.members) ? record.members : [] return members.flatMap((entry): OrcaTeamMfaPendingMember[] => { - const member = entry && typeof entry === 'object' ? (entry as Record) : null + const member = isRecord(entry) ? entry : null const email = typeof member?.email === 'string' ? member.email.trim() : '' if (!member || !email) { return [] @@ -111,7 +113,8 @@ async function request(url: string, init: RequestInit): Promise { if (!response.ok) { throw new OrcaCloudRequestError(response.status, await extractErrorCode(response)) } - return (await response.json()) as unknown + const body: unknown = await response.json() + return body } type Unavailable = Extract< @@ -203,7 +206,8 @@ export async function setOrcaTeamMfaPolicy( args.enforce === 'off' ? { ...requestInit('GET', token), method: 'DELETE' } : { ...requestInit('POST', token, { enforce: args.enforce }), method: 'PUT' } - const body = (await request(url('/mfa-policy'), init)) as Record | null + const answer = await request(url('/mfa-policy'), init) + const body = isRecord(answer) ? answer : null return { policy: normalizeDeadline(body?.policy), pendingMembers: finiteNumber(body?.pendingMembers) ?? 0 @@ -254,10 +258,11 @@ export async function remindOrcaTeamMfa( const result = await call( userDataPath, async (_apiBaseUrl, token, url) => { - const body = (await request( + const answer = await request( url('/mfa-policy/remind'), requestInit('POST', token, args.userId ? { userId: args.userId } : {}) - )) as Record | null + ) + const body = isRecord(answer) ? answer : null const delivery: 'log' | 'test-inbox' | 'unknown' = body?.delivery === 'log' || body?.delivery === 'test-inbox' ? body.delivery : 'unknown' return { recipients: finiteNumber(body?.recipients) ?? 0, delivery } diff --git a/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts index 26ad8e230d3..90e14c3e393 100644 --- a/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts +++ b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts @@ -1,6 +1,6 @@ +import type { OrcaOrgMemberMfa } from '../../../shared/orca-account-mfa' import type { OrcaOrgMember, - OrcaOrgMemberMfa, OrcaOrgMembersRoster, OrcaOrgPendingInvite, OrcaOrgRole diff --git a/src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx b/src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx index bb18047e2ec..f89665070ec 100644 --- a/src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfaBlockedScreen.tsx @@ -84,13 +84,7 @@ export function TeamMfaBlockedScreen({ : null}

    {onUsePersonal ? ( - ) : null} diff --git a/src/renderer/src/components/team-mfa/team-mfa.test.tsx b/src/renderer/src/components/team-mfa/team-mfa.test.tsx index 18999d7b3b2..34bc8f81f65 100644 --- a/src/renderer/src/components/team-mfa/team-mfa.test.tsx +++ b/src/renderer/src/components/team-mfa/team-mfa.test.tsx @@ -212,8 +212,8 @@ describe('Require MFA row', () => { describe('the server refusal in cloud workspace errors', () => { it('says to set up MFA, never to sign in again', () => { - for (const describe of [describeError, describeInlineError]) { - const message = describe('unauthorized', 'mfa_required', translate) + for (const explain of [describeError, describeInlineError]) { + const message = explain('unauthorized', 'mfa_required', translate) expect(message).toContain('requires two-factor authentication') expect(message).not.toMatch(/sign in/i) } diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index a987535364d..83d3ecc7cc7 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1374,6 +1374,18 @@ "unavailableCount_one": "{{count}} unavailable", "unavailableCount_other": "{{count}} unavailable" }, + "teamMfa": { + "daysLeft_one": "{{count}} day left", + "daysLeft_other": "{{count}} days left", + "nowWarning_one": "{{count}} member doesn’t have it yet and will lose access to this team right away.", + "nowWarning_other": "{{count}} members don’t have it yet and will lose access to this team right away.", + "pendingCount_one": "{{count}} member still needs it", + "pendingCount_other": "{{count}} members still need it", + "reminded_one": "Reminder sent to {{count}} member.", + "reminded_other": "Reminder sent to {{count}} members.", + "soonTitle_one": "{{value0}} requires MFA in {{count}} day", + "soonTitle_other": "{{value0}} requires MFA in {{count}} days" + }, "teammates": { "daySandboxHours_one": "{{hours}} sandbox hour", "daySandboxHours_other": "{{hours}} sandbox hours" diff --git a/src/shared/orca-account-mfa.ts b/src/shared/orca-account-mfa.ts index 12596bc0cda..2274d9784eb 100644 --- a/src/shared/orca-account-mfa.ts +++ b/src/shared/orca-account-mfa.ts @@ -11,3 +11,17 @@ export type OrcaAccountMfaResult = /** `unsupported`: this Orca Cloud deployment (or local dev auth) has no MFA status. */ | { status: 'unconfigured' | 'reconnect-required' | 'unsupported' } | { status: 'failed'; error: string } + +/** + * A team member's two-factor state as owners and admins see it. Absent for everyone else, and + * for a member the provider said nothing about. 'pending': a team policy requires it by the + * member's `mfaDeadline` and they have not set it up. + */ +export type OrcaOrgMemberMfa = 'on' | 'off' | 'pending' + +/** The two-factor fields of a team member (OrcaOrgMember in orca-profiles.ts). */ +export type OrcaOrgMemberMfaFields = { + mfa?: OrcaOrgMemberMfa + /** Epoch ms the member must have MFA by; only with `mfa: 'pending'`. */ + mfaDeadline?: number +} diff --git a/src/shared/orca-profiles.ts b/src/shared/orca-profiles.ts index 4ce8ec0bdc8..1f8d3daf904 100644 --- a/src/shared/orca-profiles.ts +++ b/src/shared/orca-profiles.ts @@ -1,3 +1,4 @@ +import type { OrcaOrgMemberMfaFields } from './orca-account-mfa' import './constants' import { ORCA_BROWSER_PARTITION } from './browser/browser-session-partition' import type { ExecutionHostId } from './execution-host' @@ -250,7 +251,8 @@ export type RefreshCurrentOrcaProfileAuthResult = // Mirror the server’s fixed role enum so UI options cannot drift from accepted API values. export type OrcaOrgRole = 'owner' | 'admin' | 'member' -export type OrcaOrgMember = { +// Two-factor state (owners and admins only) lives in OrcaOrgMemberMfaFields. +export type OrcaOrgMember = OrcaOrgMemberMfaFields & { // Provisioned teammates without sign-in have no userId; disable mutations requiring that key. userId: string | null email: string @@ -258,18 +260,8 @@ export type OrcaOrgMember = { /** Profile picture from the identity provider (https only); avatars fall back to initials. */ pictureUrl?: string role: OrcaOrgRole - /** - * Whether the member has two-factor authentication. The server sends it to owners and admins - * only, so it is absent for everyone else, and for a member the provider said nothing about. - * 'pending': a team policy requires it by `mfaDeadline` and the member has not set it up. - */ - mfa?: OrcaOrgMemberMfa - /** Epoch ms the member must have MFA by; only with `mfa: 'pending'`. */ - mfaDeadline?: number } -export type OrcaOrgMemberMfa = 'on' | 'off' | 'pending' - export type OrcaOrgPendingInvite = { email: string role: OrcaOrgRole From b6fdb18033e34f3be6a10d0b02a18fdd48ebd433 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 22:49:42 -0800 Subject: [PATCH 16/28] test(recipes): type the forwarded-env handler fake instead of casting its result Co-Authored-By: Claude --- src/main/ipc/ephemeral-vm-forwarded-env.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/ipc/ephemeral-vm-forwarded-env.test.ts b/src/main/ipc/ephemeral-vm-forwarded-env.test.ts index 6a59860b2c3..e0fd791fd14 100644 --- a/src/main/ipc/ephemeral-vm-forwarded-env.test.ts +++ b/src/main/ipc/ephemeral-vm-forwarded-env.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' -const handlers = new Map unknown>() +// The only channel registered here returns a summary. +const handlers = new Map RecipeForwardedEnvSummary>() const { listRuntimesMock, recipeContextMock } = vi.hoisted(() => ({ listRuntimesMock: vi.fn(), recipeContextMock: vi.fn() @@ -31,7 +32,7 @@ function summarize(args?: unknown): RecipeForwardedEnvSummary { if (!handler) { throw new Error('handler not registered') } - return handler({}, args) as RecipeForwardedEnvSummary + return handler({}, args) } beforeEach(() => { From 979c7d15ed220b09db014c785ff9ac16dec863ce Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 23:02:13 -0800 Subject: [PATCH 17/28] test(cloud-glossary): allowlist matches file + string snippet, not line number Allowlist entries keyed on path:line:term went stale whenever an unrelated edit shifted lines, breaking PRs. Entries now carry a 'match' snippet and allow a hit when file, term and snippet (hit.text.includes(match)) all match. Adds isAllowed/staleAllowEntries helpers and synthetic tests. --- .../cloud-glossary-allowlist-match.ts | 21 +++++++ .../orca-cloud/cloud-glossary-allowlist.json | 42 ++++++------- .../orca-cloud/cloud-glossary-lint.test.ts | 60 ++++++++++++++++--- 3 files changed, 93 insertions(+), 30 deletions(-) create mode 100644 src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist-match.ts diff --git a/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist-match.ts b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist-match.ts new file mode 100644 index 00000000000..0dd790595d0 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist-match.ts @@ -0,0 +1,21 @@ +// Allowlist matching for the cloud glossary lint. Entries match by file + term + a snippet of the +// string, never by line number, so unrelated edits that shift lines don't make entries stale. + +export type GlossaryHit = { file: string; line: number; term: string; text: string } +export type AllowEntry = { path: string; term: string; match: string; reason: string } + +export function isAllowed(hit: GlossaryHit, entry: AllowEntry): boolean { + return ( + hit.file === entry.path && + hit.term === entry.term && + entry.match.length > 0 && + hit.text.includes(entry.match) + ) +} + +/** Entries that no longer match any hit, or that have no reason. */ +export function staleAllowEntries(hits: GlossaryHit[], allow: AllowEntry[]): AllowEntry[] { + return allow.filter( + (entry) => !entry.reason?.trim() || !hits.some((hit) => isAllowed(hit, entry)) + ) +} diff --git a/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json index e9a169b5dae..0a777170fa2 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json +++ b/src/renderer/src/lib/orca-cloud/cloud-glossary-allowlist.json @@ -1,128 +1,128 @@ [ { "path": "src/renderer/src/components/cloud-environment/EnvironmentForm.tsx", - "line": 127, "term": "container", + "match": "Reads Conductor and Dev Container setup from a local project.", "reason": "Dev Containers spec name" }, { "path": "src/renderer/src/components/settings/virtual-machines/runtimes/CloudVmSetupGuide.tsx", - "line": 20, "term": "VM", + "match": "Cloud VMs", "reason": "BYOC recipe VMs (experimental), not Orca Cloud" }, { "path": "src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx", - "line": 412, "term": "VM", + "match": "Delete VM", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/VmBuildFailureCard.tsx", - "line": 138, "term": "VM", + "match": "The VM is running until you choose.", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", - "line": 38, "term": "VM", + "match": "Delete this VM?", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", - "line": 49, "term": "VM", + "match": "The VM and anything on it are destroyed, and the workspace isn’t created.", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/VmDeleteConfirmDialog.tsx", - "line": 63, "term": "VM", + "match": "Delete VM", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts", - "line": 55, "term": "VM", + "match": "The VM is up, but some environment checks need attention", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts", - "line": 59, "term": "VM", + "match": "The VM is up, but {{count}} environment checks failed", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-failure-copy.ts", - "line": 62, "term": "VM", + "match": "The VM is up, but {{count}} environment check failed", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-recipe-failure-copy.ts", - "line": 15, "term": "VM", + "match": "The VM recipe failed", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-recipe-failure-copy.ts", - "line": 19, "term": "VM", + "match": "Your VM recipe stopped with an error before the VM was ready.", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-recipe-failure-copy.ts", - "line": 25, "term": "VM", + "match": "Couldn’t create the workspace on the VM", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-recipe-failure-copy.ts", - "line": 29, "term": "VM", + "match": "The VM started, but creating the workspace on it stopped with an error.", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts", - "line": 10, "term": "VM", + "match": "Provision VM", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts", - "line": 69, "term": "VM", + "match": "Building your VM workspace", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts", - "line": 74, "term": "VM", + "match": "Your VM workspace is ready", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts", - "line": 79, "term": "VM", + "match": "Your VM workspace needs attention", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts", - "line": 84, "term": "VM", + "match": "Couldn’t build your VM workspace", "reason": "recipe-VM branch; cloud branch says sandbox" }, { "path": "src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.ts", - "line": 13, "term": "VM", + "match": "This workspace's VM is asleep", "reason": "match pattern for older builds' saved terminal errors; never rendered" }, { "path": "src/renderer/src/components/orca-cloud/use-cloud-terminal-error-override.ts", - "line": 14, "term": "VM", + "match": "This workspace's VM could not wake up", "reason": "match pattern for older builds' saved terminal errors; never rendered" } ] diff --git a/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts b/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts index 8078f45efef..acf3f226132 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-glossary-lint.test.ts @@ -7,6 +7,12 @@ import ts from 'typescript-api' import { globSync } from 'glob' import { describe, expect, it } from 'vitest' import allowlist from './cloud-glossary-allowlist.json' +import { + isAllowed, + staleAllowEntries, + type AllowEntry, + type GlossaryHit +} from './cloud-glossary-allowlist-match' const ROOT = path.resolve(__dirname, '../../../../..') @@ -88,8 +94,7 @@ const TEXT_ATTRIBUTES = new Set([ ]) const TRANSLATE_CALLEES = new Set(['t', 'translate']) -type Hit = { file: string; line: number; term: string; text: string; rule: Rule } -type AllowEntry = { path: string; line: number; term: string; reason: string } +type Hit = GlossaryHit & { rule: Rule } function stringValue(node: ts.Node): string | null { if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) { @@ -240,8 +245,6 @@ function findHits(): Hit[] { } const ALLOW: AllowEntry[] = allowlist -const allowKey = (e: { path: string; line: number; term: string }): string => - `${e.path}:${e.line}:${e.term}` describe('cloud glossary lint', () => { const hits = findHits() @@ -251,17 +254,16 @@ describe('cloud glossary lint', () => { }) it('every allowlist entry has a reason and still matches a string', () => { - const live = new Set(hits.map((h) => allowKey({ path: h.file, line: h.line, term: h.term }))) - const problems = ALLOW.filter((e) => !e.reason?.trim() || !live.has(allowKey(e))).map( - (e) => `stale or unexplained allowlist entry: ${allowKey(e)}` + const problems = staleAllowEntries(hits, ALLOW).map( + (e) => + `stale or unexplained allowlist entry: ${e.path} "${e.term}" match ${JSON.stringify(e.match)}` ) expect(problems).toEqual([]) }) it('cloud strings use glossary words', () => { - const allowed = new Set(ALLOW.map(allowKey)) const failures = hits - .filter((h) => !allowed.has(allowKey({ path: h.file, line: h.line, term: h.term }))) + .filter((h) => !ALLOW.some((e) => isAllowed(h, e))) .map( (h) => `cloud glossary: "${h.term}" at ${h.file}:${h.line}; use "${h.rule.use}" (glossary row: ${h.rule.row}). ` + @@ -270,3 +272,43 @@ describe('cloud glossary lint', () => { expect(failures).toEqual([]) }) }) + +describe('allowlist matching', () => { + const file = 'src/renderer/src/components/worktree-creation/vm-build-sheet-copy.ts' + const entry: AllowEntry = { + path: file, + term: 'VM', + match: 'Your VM workspace is ready', + reason: 'recipe-VM branch' + } + const hit = (over: Partial = {}): GlossaryHit => ({ + file, + line: 74, + term: 'VM', + text: 'Your VM workspace is ready', + ...over + }) + + it('still allows the same string after it moves to another line', () => { + expect(isAllowed(hit({ line: 74 }), entry)).toBe(true) + expect(isAllowed(hit({ line: 112 }), entry)).toBe(true) + }) + + it('does not allow a different string with the same term in the same file', () => { + expect(isAllowed(hit({ text: 'Delete this VM?' }), entry)).toBe(false) + }) + + it('does not allow the same snippet in a different file', () => { + expect(isAllowed(hit({ file: 'src/renderer/src/lib/other-cloud.ts' }), entry)).toBe(false) + }) + + it('reports an entry with no matching hit as stale', () => { + expect(staleAllowEntries([hit({ text: 'Delete this VM?' })], [entry])).toEqual([entry]) + expect(staleAllowEntries([hit()], [entry])).toEqual([]) + }) + + it('reports an entry with an empty reason', () => { + const unexplained = { ...entry, reason: ' ' } + expect(staleAllowEntries([hit()], [unexplained])).toEqual([unexplained]) + }) +}) From 7eccb72a9acd5d014ddd18d7acccfef0afce4a18 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 11:21:37 -0800 Subject: [PATCH 18/28] wip chat-renew-inplace: idle strip + send block --- .../CloudStructuredChatBanners.tsx | 7 +- .../cloud-chat-running-strip.test.tsx | 54 +++++++++++++++- .../use-cloud-chat-running-strip.ts | 64 ++++++++++++++----- .../host-access/NativeChatInstallSlot.tsx | 20 +++++- .../pane/actions/NativeChatPaneHeader.tsx | 1 + src/renderer/src/i18n/locales/en.json | 3 + 6 files changed, 126 insertions(+), 23 deletions(-) diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudStructuredChatBanners.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudStructuredChatBanners.tsx index ba0b56c6ba1..4e8bf438777 100644 --- a/src/renderer/src/components/agent-sign-in-strip/CloudStructuredChatBanners.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/CloudStructuredChatBanners.tsx @@ -22,16 +22,19 @@ function tabStillOpen(tabId: string): boolean { export function CloudStructuredChatBanners({ tabId, paneKey, - statusKey + statusKey, + agent }: { tabId: string /** The launch-hold key (from the session id). */ paneKey: string /** The agent-status key (tab and session): the running strip (B2) reads the agent through it. */ statusKey: string + /** The chat's agent, for an idle chat with no status yet. */ + agent?: string }): React.JSX.Element { const { key, active, strip } = useCloudHeldStrip(paneKey, null, { chat: true }) - const running = useCloudChatRunningStrip({ tabId, statusKey, holdKey: paneKey }) + const running = useCloudChatRunningStrip({ tabId, statusKey, holdKey: paneKey, agent }) const shown = strip ?? running useEffect(() => { if (!active) { diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-chat-running-strip.test.tsx b/src/renderer/src/components/agent-sign-in-strip/cloud-chat-running-strip.test.tsx index a53c70fc85f..45147d775d6 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-chat-running-strip.test.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-chat-running-strip.test.tsx @@ -2,7 +2,7 @@ // CHAT-BANNERS B2: RA-11's running strip on a structured chat. Expired shows Renew; renewed confirms // with no Restart (the chat's next message uses the renewed sign-in) and its × dismisses; a held // launch's strip wins over it. -import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { TooltipProvider } from '@/components/ui/tooltip' @@ -94,6 +94,7 @@ vi.stubGlobal( ) const { CloudStructuredChatBanners } = await import('./CloudStructuredChatBanners') +const { useCloudChatSendBlock } = await import('./use-cloud-chat-running-strip') const mount = () => render( @@ -139,3 +140,54 @@ describe('the running strip on a structured chat (B2)', () => { expect(screen.queryByRole('button', { name: /Renew/ })).toBeNull() }) }) + +describe('an idle chat (no message yet, no status entry)', () => { + const IDLE_TAB = 'structured-agent-session-claude_idle' + const idle = () => + render( + + + + ) + + it("expired account: the strip shows, decided from the chat's own agent", () => { + stub.strip = { phase: 'expired', agent: 'claude' } + idle() + expect(screen.getAllByText(/Claude sign-in expired/).length).toBeGreaterThan(0) + expect(stub.calls.at(-1)?.paneKey).toBe(`${IDLE_TAB}:no-status`) + }) + + it('covered account: no strip', () => { + idle() + expect(screen.queryByRole('region')).toBeNull() + }) + + it('a held launch shows the held strip instead', () => { + stub.strip = { phase: 'expired', agent: 'claude' } + stub.held = true + idle() + expect(screen.getByRole('button', { name: 'Set up once' })).toBeTruthy() + }) +}) + +describe('Send while the account is expired', () => { + const args = { tabId: TAB_ID, statusKey: STATUS_KEY, holdKey: HOLD_KEY, agent: 'claude' } + + it('expired: Send is held with the Renew hint (typing is not touched)', () => { + stub.strip = { phase: 'expired', agent: 'claude' } + const { result } = renderHook(() => useCloudChatSendBlock(args)) + expect(result.current).toBe('Renew Claude sign-in above to send') + }) + + it('renewed or covered: Send is free again', () => { + stub.strip = { phase: 'renewed', agent: 'claude', resumable: true } + expect(renderHook(() => useCloudChatSendBlock(args)).result.current).toBeUndefined() + stub.strip = null + expect(renderHook(() => useCloudChatSendBlock(args)).result.current).toBeUndefined() + }) +}) diff --git a/src/renderer/src/components/agent-sign-in-strip/use-cloud-chat-running-strip.ts b/src/renderer/src/components/agent-sign-in-strip/use-cloud-chat-running-strip.ts index ef46a8abf49..9a5ab27a572 100644 --- a/src/renderer/src/components/agent-sign-in-strip/use-cloud-chat-running-strip.ts +++ b/src/renderer/src/components/agent-sign-in-strip/use-cloud-chat-running-strip.ts @@ -4,7 +4,10 @@ // with the renewed sign-in. import { useAppStore } from '@/store' import { useTranslate } from '@/i18n/use-translate' -import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status' +import { + HOST_AGENT_SIGN_IN_AGENT_NAME, + type HostAgentSignInAgent +} from '../../../../shared/host-agent-sign-in-status' import { parseExecutionHostId } from '../../../../shared/execution-host' import { useCloudAgentHold } from '@/lib/orca-cloud/cloud-agent-launch-hold' import { @@ -15,6 +18,7 @@ import { isOrcaCloudEnvironmentId } from '@/lib/orca-cloud/orca-cloud-environmen import { clearCloudRunningSignout, cloudRunningStrip, + type CloudRunningStrip, useCloudRunningAccountReads, useCloudRunningSignoutVersion, useWorkspaceUsesAccount @@ -43,27 +47,33 @@ function useChatEnvironmentId(tabId: string): string | null { }) } -/** - * statusKey: the chat's agent-status key (its tab and session); holdKey: its launch-hold key. A held - * launch shows the held strip instead. - */ -export function useCloudChatRunningStrip(args: { +type ChatAccountArgs = { tabId: string statusKey: string holdKey: string -}): CloudHeldStrip | null { - const t = useTranslate() + /** The chat's own agent: an idle chat (no message yet) has no status entry to name it. */ + agent?: string +} + +/** + * The RA-11 decision for a structured chat: expired / renewed / none. An idle chat with no status + * entry is decided from its own agent, so the strip shows as soon as the account expires, before a + * first message could fail. A held launch wins (null here). + */ +export function useCloudChatAccountStrip(args: ChatAccountArgs): CloudRunningStrip | null { const revision = useCloudRunningSignoutVersion() const environmentId = useChatEnvironmentId(args.tabId) const cloud = environmentId !== null && isOrcaCloudEnvironmentId(environmentId) - const entry = useAppStore((state) => + const status = useAppStore((state) => cloud ? (state.agentStatusByPaneKey[args.statusKey] ?? null) : null ) + const agentType = status?.agentType ?? args.agent const agent: HostAgentSignInAgent | null = - entry?.agentType === 'claude' ? 'claude' : entry?.agentType === 'codex' ? 'codex' : null - const running = cloud && agent !== null - useCloudRunningAccountReads(running) - const accounts = useOrcaCloudAgentAccounts(running) + agentType === 'claude' ? 'claude' : agentType === 'codex' ? 'codex' : null + const watched = cloud && agent !== null + // Focus and the 30 s poll keep the account read fresh for any open cloud chat of an account agent. + useCloudRunningAccountReads(watched) + const accounts = useOrcaCloudAgentAccounts(watched) // D13: only a workspace that runs the agent on the person's own account (never shared or keyed). const credential = agent && accounts.load.kind === 'ready' ? accounts.load.status.credentials[agent] : null @@ -73,18 +83,18 @@ export function useCloudChatRunningStrip(args: { credential.state !== 'expiring' && credential.state !== 'none' const usesAccount = useWorkspaceUsesAccount( - running ? environmentId : null, + watched ? environmentId : null, agent, expired, orcaCloudAgentAccountsLoadedAt() ) const held = useCloudAgentHold(args.holdKey) !== null - if (!running) { + if (!watched || !agent) { return null } - const strip = cloudRunningStrip({ + return cloudRunningStrip({ paneKey: args.statusKey, - entry, + entry: status ?? { agentType: agent, state: 'idle' }, accounts, held, now: orcaCloudAgentAccountsLoadedAt(), @@ -92,6 +102,12 @@ export function useCloudChatRunningStrip(args: { revision, turnEndedFallback: true }) +} + +/** The strip a structured chat shows for its account while its agent runs or waits idle. */ +export function useCloudChatRunningStrip(args: ChatAccountArgs): CloudHeldStrip | null { + const t = useTranslate() + const strip = useCloudChatAccountStrip(args) if (!strip) { return null } @@ -106,3 +122,17 @@ export function useCloudChatRunningStrip(args: { } return { model: cloudChatRunningStripModel(strip, t), prompt: null, actions } } + +/** + * While the chat's account is expired, typing stays open and only Send is held, with this hint + * (the person's draft is never lost); Renew lifts it at once. + */ +export function useCloudChatSendBlock(args: ChatAccountArgs): string | undefined { + const t = useTranslate() + const strip = useCloudChatAccountStrip(args) + return strip?.phase === 'expired' + ? t('orcaCloud.chatSend.renewAbove', 'Renew {{agent}} sign-in above to send', { + agent: HOST_AGENT_SIGN_IN_AGENT_NAME[strip.agent] + }) + : undefined +} diff --git a/src/renderer/src/components/native-chat/host-access/NativeChatInstallSlot.tsx b/src/renderer/src/components/native-chat/host-access/NativeChatInstallSlot.tsx index fb311bf91e8..604f7eff689 100644 --- a/src/renderer/src/components/native-chat/host-access/NativeChatInstallSlot.tsx +++ b/src/renderer/src/components/native-chat/host-access/NativeChatInstallSlot.tsx @@ -1,6 +1,8 @@ import { translate } from '@/i18n/i18n' import { useCloudChatHoldHint } from '../../agent-sign-in-strip/use-cloud-chat-hold-hint' import { structuredCloudHoldKey } from '@/lib/orca-cloud/cloud-structured-launch-hold' +import { useCloudChatSendBlock } from '../../agent-sign-in-strip/use-cloud-chat-running-strip' +import { structuredAgentSessionPaneKey } from '../../../../../shared/agent-session/view/structured-agent-session-projection' import { useTranslate, type Translate } from '@/i18n/use-translate' import { managedRuntimeInstallCard, @@ -33,7 +35,10 @@ const RESERVED: NativeChatInstallSlotState = { kind: 'reserved' } /** Reserve unknown readiness with an editable composer and held sends; missing runtimes show installation, while read failures leave it alone. */ export function useNativeChatInstallSlot( - props: Pick, + props: Pick< + NativeChatStructuredViewProps, + 'target' | 'agent' | 'isVisible' | 'sessionId' | 'tabId' + >, agentLabel: string, layout: ManagedRuntimeInstallLayout ): { @@ -49,7 +54,15 @@ export function useNativeChatInstallSlot( hostProgram ) // CHAT-BANNERS: an Orca Cloud launch held on the chat's strip has no agent to send to yet. - const cloudHoldHint = useCloudChatHoldHint(structuredCloudHoldKey(props.sessionId), '') + const cloudHoldKey = structuredCloudHoldKey(props.sessionId) + const cloudHoldHint = useCloudChatHoldHint(cloudHoldKey, '') + // While its Orca Cloud account is expired, the chat takes typing but holds Send (draft kept). + const cloudSendBlock = useCloudChatSendBlock({ + tabId: props.tabId, + statusKey: structuredAgentSessionPaneKey(props.tabId, props.sessionId), + holdKey: cloudHoldKey, + agent: props.agent + }) const unavailableHint = cloudHoldHint ?? (slot.kind === 'install' @@ -57,7 +70,8 @@ export function useNativeChatInstallSlot( : undefined) return { slot, - sendBlockedReason: unavailableHint ?? installSlotSendBlockedReason(slot, agentLabel, t), + sendBlockedReason: + unavailableHint ?? cloudSendBlock ?? installSlotSendBlockedReason(slot, agentLabel, t), unavailableHint } } diff --git a/src/renderer/src/components/native-chat/pane/actions/NativeChatPaneHeader.tsx b/src/renderer/src/components/native-chat/pane/actions/NativeChatPaneHeader.tsx index 5ca92b45986..153cafb5635 100644 --- a/src/renderer/src/components/native-chat/pane/actions/NativeChatPaneHeader.tsx +++ b/src/renderer/src/components/native-chat/pane/actions/NativeChatPaneHeader.tsx @@ -152,6 +152,7 @@ export function nativeChatPaneHeader( tabId={view.tabId} paneKey={structuredCloudHoldKey(view.sessionId)} statusKey={structuredAgentSessionPaneKey(view.tabId, view.sessionId)} + agent={view.agent} /> ) const header = diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 1bb5e0ec9a2..dc213e5b036 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -28413,6 +28413,9 @@ "setUpNotStarted": "{{agent}} is set up. Open the workspace to start it.", "notStartedRow": "{{agent}} hasn’t started" }, + "chatSend": { + "renewAbove": "Renew {{agent}} sign-in above to send" + }, "chatSignIn": { "renewAbove": "Your {{agent}} sign-in for Orca Cloud didn’t work. Renew it above, then send your message again." }, From f5e9547beed4132624f89b077ff9cb34e9489843 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 22:14:50 -0800 Subject: [PATCH 19/28] fix(cloud): CHAT-RENEW-INPLACE (B) a renewal never launches a held agent; every held launch waits for its own Start --- .../cloud-agent-launch-hold.test.ts | 31 +++++++++++++---- .../lib/orca-cloud/cloud-agent-launch-hold.ts | 33 ++++--------------- .../cloud-held-launch-restore.test.ts | 15 +++++++-- .../cloud-web-host-launch-hold.test.ts | 11 +++++-- 4 files changed, 53 insertions(+), 37 deletions(-) diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.test.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.test.ts index 3fc90b01ee6..53edf0cd0b2 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.test.ts @@ -79,16 +79,35 @@ describe('cloud agent launch hold', () => { expect(cloudAgentLaunchNeedsHold('claude')).toBe(true) }) - it('holds an expired launch until Renew fixes the account, then every held pane goes', async () => { + it('CHAT-RENEW-INPLACE (B): a renewal never launches; every held pane waits for its own Start', async () => { setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'expired' })) - const first = holdCloudAgentLaunch({ paneKey: 'tab:a', agent: 'claude', prompt: 'fix it' }) - const second = holdCloudAgentLaunch({ paneKey: 'tab:b', agent: 'claude', prompt: null }) + let firstOutcome = 'pending' + let secondOutcome = 'pending' + void holdCloudAgentLaunch({ paneKey: 'tab:a', agent: 'claude', prompt: 'fix it' }).then( + (o) => (firstOutcome = o) + ) + void holdCloudAgentLaunch({ paneKey: 'tab:b', agent: 'claude', prompt: null }).then( + (o) => (secondOutcome = o) + ) await vi.waitFor(() => expect(readCloudAgentHold('tab:b')).not.toBeNull()) expect(readCloudAgentHold('tab:a')).toMatchObject({ prompt: 'fix it' }) setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) - await expect(first).resolves.toBe('proceed') - await expect(second).resolves.toBe('proceed') - expect(readCloudAgentHold('tab:a')).toBeNull() + for (let i = 0; i < 3; i += 1) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } + for (const key of ['tab:a', 'tab:b']) { + expect(readCloudAgentHold(key)).toMatchObject({ + reason: 'awaitingStart', + awaiting: 'renewed' + }) + } + expect([firstOutcome, secondOutcome]).toEqual(['pending', 'pending']) + // Start in one tab launches that one; the other keeps waiting. + releaseCloudAgentHold('tab:a', 'proceed') + await vi.waitFor(() => expect(firstOutcome).toBe('proceed')) + expect(secondOutcome).toBe('pending') + expect(readCloudAgentHold('tab:b')).toMatchObject({ awaiting: 'renewed' }) + releaseCloudAgentHold('tab:b', 'cancel') }) it('cancel releases only that pane', async () => { diff --git a/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts b/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts index a3aa2cfb59f..fbe3faed7c0 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-agent-launch-hold.ts @@ -112,11 +112,7 @@ type HoldRequest = Omit & { restored?: boolean } -type Entry = CloudAgentHold & { - release: (outcome: 'proceed' | 'cancel') => void - /** Renewed or covered, it waits for the person's Start instead of starting (restored, or setup). */ - askFirst: boolean -} +type Entry = CloudAgentHold & { release: (outcome: 'proceed' | 'cancel') => void } const holds = new Map() /** Each live hold's outcome, so a second launch for the same key joins it instead of holding twice. */ @@ -298,8 +294,7 @@ async function placeCloudAgentHold({ ...hold, reason, ...(awaiting ? { awaiting } : {}), - release: finish, - askFirst: Boolean(restored) || reason !== 'accountExpired' + release: finish }) notify() }) @@ -315,14 +310,7 @@ function redecide(entry: Entry, accounts: OrcaCloudAgentAccountsState): void { const now = cloudAgentHoldReason(entry.agent, accounts) if (now !== null) { if (now !== entry.reason) { - // A removed sign-in becomes the one-time setup, which never starts unasked (PC-3b), even - // for a hold placed on an expired sign-in in this session. - holds.set(entry.paneKey, { - ...entry, - reason: now, - awaiting: undefined, - askFirst: entry.askFirst || now === 'notSetUp' - }) + holds.set(entry.paneKey, { ...entry, reason: now, awaiting: undefined }) notify() } return @@ -339,11 +327,9 @@ function redecide(entry: Entry, accounts: OrcaCloudAgentAccountsState): void { } return } - if (!entry.askFirst) { - // Renewed in this session: every pane held on recovery starts. - entry.release('proceed') - return - } + // CHAT-RENEW-INPLACE (team-lead, B): covered again, every held launch waits for its Start, in + // this session or restored, in every tab: "{{agent}} sign-in renewed · Start {{agent}}" after a + // renewal, "is set up · Start" after the one-time setup. Nothing launches unasked. const awaiting = entry.reason === 'notSetUp' ? 'setUp' : 'renewed' holds.set(entry.paneKey, { ...entry, reason: 'awaitingStart', awaiting }) notify() @@ -373,12 +359,7 @@ export async function startCloudAgentHold(paneKey: string): Promise<'started' | const coverage = orcaCloudAgentCoverageFromAccounts(entry.agent, accounts)?.kind if (now !== null || (coverage !== 'account' && coverage !== 'key')) { if (now !== null && now !== entry.reason) { - holds.set(paneKey, { - ...entry, - reason: now, - awaiting: undefined, - askFirst: entry.askFirst || now === 'notSetUp' - }) + holds.set(paneKey, { ...entry, reason: now, awaiting: undefined }) notify() } return 'held' diff --git a/src/renderer/src/lib/orca-cloud/cloud-held-launch-restore.test.ts b/src/renderer/src/lib/orca-cloud/cloud-held-launch-restore.test.ts index 3fb5e2eee4a..a90d42b945e 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-held-launch-restore.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-held-launch-restore.test.ts @@ -291,7 +291,7 @@ describe('after a restart', () => { }) describe('in session (not restored)', () => { - it('in-session (not restored), an expired hold still starts on Renew as before', async () => { + it('CHAT-RENEW-INPLACE (B): in session, a renewed hold waits for Start: no create until Start', async () => { mocks.coverage = 'expired' setTabs([TAB]) const create = vi.fn(async (args: CreateWebRuntimeSessionTerminalOnHostArgs) => @@ -307,6 +307,13 @@ describe('in session (not restored)', () => { for (const listener of mocks.listeners) { listener() } + await flush() + expect(readCloudAgentHold(cloudTabHoldKey(TAB))).toMatchObject({ + reason: 'awaitingStart', + awaiting: 'renewed' + }) + expect(create).not.toHaveBeenCalledWith(expect.objectContaining({ agent: 'claude' })) + releaseCloudAgentHold(cloudTabHoldKey(TAB), 'proceed') await launch expect(create).toHaveBeenLastCalledWith(expect.objectContaining({ agent: 'claude' })) }) @@ -332,7 +339,7 @@ describe('in session (not restored)', () => { expect(create).toHaveBeenCalledTimes(1) }) - it('a paused (kill switch) agent never starts the expired hold; a real renewal does', async () => { + it('a paused (kill switch) agent never starts the expired hold; a real renewal waits for Start (B)', async () => { mocks.coverage = 'expired' setTabs([TAB]) const create = vi.fn(async (args: CreateWebRuntimeSessionTerminalOnHostArgs) => @@ -354,6 +361,10 @@ describe('in session (not restored)', () => { for (const listener of mocks.listeners) { listener() } + await flush() + expect(readCloudAgentHold(cloudTabHoldKey(TAB))).toMatchObject({ awaiting: 'renewed' }) + expect(create).toHaveBeenCalledTimes(1) + releaseCloudAgentHold(cloudTabHoldKey(TAB), 'proceed') await launch expect(create).toHaveBeenLastCalledWith(expect.objectContaining({ agent: 'claude' })) }) diff --git a/src/renderer/src/lib/orca-cloud/cloud-web-host-launch-hold.test.ts b/src/renderer/src/lib/orca-cloud/cloud-web-host-launch-hold.test.ts index e3912c0893a..81f6767e34e 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-web-host-launch-hold.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-web-host-launch-hold.test.ts @@ -219,7 +219,7 @@ describe('createWithCloudAgentHold (the one hold for every Orca Cloud agent laun expect(readCloudAgentHold(key)).toBeNull() }) - it('expired: holds, then starts on Renew', async () => { + it('expired: holds; Renew turns it to "renewed · Start", and Start launches it (B)', async () => { setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'revoked' })) const create = hostCreate() const args = { ...CREATE_AGENT, prompt: 'fix the bug' } @@ -231,9 +231,14 @@ describe('createWithCloudAgentHold (the one hold for every Orca Cloud agent laun prompt: 'fix the bug' }) setOrcaCloudAgentAccountsStateForTest(accounts({ state: 'active' })) + await flush() + // A renewal never launches by itself (team-lead, B): it waits for Start. + expect(readCloudAgentHold(key)).toMatchObject({ reason: 'awaitingStart', awaiting: 'renewed' }) + expect(create).toHaveBeenCalledOnce() + releaseCloudAgentHold(key, 'proceed') await expect(result).resolves.toBe(AGENT) - // Renew's auto-start: the original args, no focus taken (the tab may be in the background). - expect(create).toHaveBeenLastCalledWith(args) + // The person's Start: the original args, with its tab brought forward. + expect(create).toHaveBeenLastCalledWith({ ...args, activate: true }) }) it('cancel leaves the plain shell and never starts the agent', async () => { From e95d45c0e68fa147e56c8bfb4ede5a0951e5b53d Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 22:46:37 -0800 Subject: [PATCH 20/28] feat(cloud): CHAT-RENEW-INPLACE every expired strip renews in place (held, running terminal, chat); idle-chat strip and send block; fixtures --- .../CloudAgentSignInStrip.tsx | 13 ++ .../CloudRenewInPlace.fixture.tsx | 136 +++++++++++++++ .../CloudRunningStripPortal.test.tsx | 9 +- .../CloudRunningStripPortal.tsx | 26 ++- .../CloudStripSettingsLink.tsx | 34 ++++ .../cloud-agent-strip-model.test.ts | 4 +- .../cloud-agent-strip-model.ts | 11 +- .../cloud-chat-running-strip.test.tsx | 10 +- .../cloud-renew-in-place.test.ts | 153 +++++++++++++++++ .../cloud-renew-in-place.ts | 159 ++++++++++++++++++ .../cloud-setup-strip-actions.ts | 2 +- .../use-cloud-chat-running-strip.ts | 28 ++- .../use-cloud-held-strip.ts | 28 ++- src/renderer/src/i18n/locales/en.json | 4 + 14 files changed, 587 insertions(+), 30 deletions(-) create mode 100644 src/renderer/src/components/agent-sign-in-strip/CloudRenewInPlace.fixture.tsx create mode 100644 src/renderer/src/components/agent-sign-in-strip/CloudStripSettingsLink.tsx create mode 100644 src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.test.ts create mode 100644 src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx index 3132c871845..5583bcb9e7c 100644 --- a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx @@ -18,6 +18,7 @@ import { Button } from '@/components/ui/button' import type { ExternalLinkSource } from '@/components/open-external/copy-external-link' import { CloudStripPasteForm } from './CloudStripPasteForm' import { StripPrimaryButton, stripPrimaryLink } from './CloudStripPrimaryButton' +import { CloudStripSettingsLink } from './CloudStripSettingsLink' import { DropdownMenu, DropdownMenuContent, @@ -103,6 +104,8 @@ export type CloudStripActions = { * setup's sign-in page, known only to main). Actions carrying a `url` copy it without this. */ linkFor?: (action: CloudStripPrimary) => ExternalLinkSource | null + /** CHAT-RENEW-INPLACE: the model's `settingsLink` ("Renew in Settings"). */ + openSettings?: () => void } /** GA-P3t: the strip's severity look; anything that isn't a warning or an error reads as info. */ @@ -336,6 +339,9 @@ export function CloudAgentSignInStrip({ ) : null} + {model.settingsLink && !stacked ? ( + + ) : null} {/* Renew and Restart are the whole action and the strip leaves on its own; Escape still cancels. */} {model.noClose || (!model.dismiss && @@ -378,6 +384,13 @@ export function CloudAgentSignInStrip({ {model.primary.label} ) : null} + {model.settingsLink ? ( + + ) : null}
    ) : null} diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudRenewInPlace.fixture.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudRenewInPlace.fixture.tsx new file mode 100644 index 00000000000..387efbaaf71 --- /dev/null +++ b/src/renderer/src/components/agent-sign-in-strip/CloudRenewInPlace.fixture.tsx @@ -0,0 +1,136 @@ +// CHAT-RENEW-INPLACE: the in-place renewal, step by step, on all three surfaces (a launch held on the +// expired sign-in, a running terminal, a structured chat). design-squad's per-step copy. +import React from 'react' +import { defineFixture } from '../../component-fixtures/component-fixture' +import { translate } from '@/i18n/i18n' +import type { OrcaCloudAgentSetup } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import { + CloudAgentSignInStrip, + CloudStripLayer, + cloudStripWidth, + type CloudStripActions +} from './CloudAgentSignInStrip' +import type { CloudStripModel } from './cloud-agent-strip-model' +import { cloudAgentStripModel } from './cloud-agent-strip-model' +import { cloudAgentAwaitingStartStripModel } from './cloud-agent-setup-strip-model' +import { cloudChatRunningStripModel, cloudRunningStripModel } from './cloud-running-strip-model' +import { cloudRenewInPlaceModel } from './cloud-renew-in-place' + +const noop = (): void => {} +const ACTIONS: CloudStripActions = { + primary: noop, + submitCode: noop, + pasteCode: noop, + useCode: noop, + useApiKey: noop, + cancel: noop, + openSettings: noop +} + +type Surface = 'held' | 'terminal' | 'chat' +type Step = 'expired' | 'browser' | 'checking' | 'rejected' | 'renewed' + +const SETUP: Record, OrcaCloudAgentSetup> = { + expired: { phase: 'idle' }, + browser: { phase: 'browser', startedAt: 0, canReopen: true, acceptsCode: true }, + checking: { + phase: 'browser', + startedAt: 0, + canReopen: true, + acceptsCode: true, + code: 'checking' + }, + rejected: { phase: 'browser', startedAt: 0, canReopen: true, acceptsCode: true, code: 'rejected' } +} + +function expiredModel(surface: Surface): CloudStripModel { + const strip = { phase: 'expired' as const, agent: 'claude' as const } + return surface === 'held' + ? cloudAgentStripModel({ + agent: 'claude', + reason: 'accountExpired', + view: null, + hostLabel: '', + t: translate + }) + : surface === 'chat' + ? cloudChatRunningStripModel(strip, translate) + : cloudRunningStripModel(strip, translate) +} + +function stepModel(surface: Surface, step: Step): CloudStripModel { + if (step !== 'renewed') { + return cloudRenewInPlaceModel({ + agent: 'claude', + expired: expiredModel(surface), + setup: SETUP[step], + t: translate + }) + } + const renewed = { phase: 'renewed' as const, agent: 'claude' as const, resumable: true } + // Step 5 is each surface's own: held waits for Start (team-lead B), the terminal offers Restart + // (RA-11), the chat's next message uses the renewed sign-in. + return surface === 'held' + ? cloudAgentAwaitingStartStripModel({ + agent: 'claude', + awaiting: 'renewed', + queuedPrompt: true, + t: translate + }) + : surface === 'chat' + ? cloudChatRunningStripModel(renewed, translate) + : cloudRunningStripModel(renewed, translate) +} + +function Frame({ + surface, + step, + width +}: { + surface: Surface + step: Step + width: number +}): React.JSX.Element { + return ( +
    +
    + + + +
    +
    + ) +} + +const fixture = (surface: Surface, step: Step, width = 900) => + defineFixture({ + width: width + 40, + render: () => + }) + +export const heldExpired = fixture('held', 'expired') +export const heldBrowser = fixture('held', 'browser') +export const heldChecking = fixture('held', 'checking') +export const heldRejected = fixture('held', 'rejected') +export const heldRenewed = fixture('held', 'renewed') +export const terminalExpired = fixture('terminal', 'expired') +export const terminalBrowser = fixture('terminal', 'browser') +export const terminalChecking = fixture('terminal', 'checking') +export const terminalRejected = fixture('terminal', 'rejected') +export const terminalRenewed = fixture('terminal', 'renewed') +export const chatExpired = fixture('chat', 'expired') +export const chatBrowser = fixture('chat', 'browser') +export const chatChecking = fixture('chat', 'checking') +export const chatRejected = fixture('chat', 'rejected') +export const chatRenewed = fixture('chat', 'renewed') +/** Narrow: the code field stacks under the text, and "Renew in Settings" gets its own line. */ +export const chatBrowserNarrow = fixture('chat', 'browser', 440) +export const terminalRejectedNarrow = fixture('terminal', 'rejected', 440) diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudRunningStripPortal.test.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudRunningStripPortal.test.tsx index 33e5548aa71..33af6feba9f 100644 --- a/src/renderer/src/components/agent-sign-in-strip/CloudRunningStripPortal.test.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/CloudRunningStripPortal.test.tsx @@ -49,7 +49,14 @@ vi.mock('@/lib/orca-cloud/orca-cloud-environment-id', () => ({ })) vi.mock('@/lib/orca-cloud/orca-cloud-agent-accounts-store', () => ({ orcaCloudAgentAccountsLoadedAt: () => 0, - useOrcaCloudAgentAccounts: () => ({ load: { kind: 'loading' }, keyKinds: {} }) + useOrcaCloudAgentAccounts: () => ({ + load: { kind: 'loading' }, + keyKinds: {}, + setups: { claude: { phase: 'idle' }, codex: { phase: 'idle' } } + }), + runOrcaCloudAgentSetups: () => undefined, + stopOrcaCloudAgentSetups: () => undefined, + reloadOrcaCloudAgentAccounts: async () => undefined })) vi.mock('@/lib/orca-cloud/cloud-running-agent-signout', () => ({ clearCloudRunningSignout: () => undefined, diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudRunningStripPortal.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudRunningStripPortal.tsx index bdfde2a50c4..690d5b6aa60 100644 --- a/src/renderer/src/components/agent-sign-in-strip/CloudRunningStripPortal.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/CloudRunningStripPortal.tsx @@ -42,6 +42,7 @@ import { cloudRestartFreshModel, cloudRunningStripModel } from './cloud-running-strip-model' +import { openOrcaCloudAccountsSettings, withRenewInPlace } from './cloud-renew-in-place' const NO_ACTIONS: CloudStripActions = { primary: () => undefined, @@ -52,12 +53,6 @@ const NO_ACTIONS: CloudStripActions = { cancel: () => undefined } -function openAccounts(): void { - const store = useAppStore.getState() - store.openSettingsTarget({ pane: 'accounts', repoId: null, sectionId: 'orca-cloud' }) - store.openSettingsPage() -} - export function CloudRunningStripPortal({ pane, tabId, @@ -192,7 +187,7 @@ export function CloudRunningStripPortal({ const actions: CloudStripActions = { primary: (action) => { if (action.kind === 'renew') { - openAccounts() + openOrcaCloudAccountsSettings() } else if (action.kind === 'restart' && strip.phase === 'renewed') { restart({ agent: strip.agent, resumable: strip.resumable }) } @@ -204,6 +199,19 @@ export function CloudRunningStripPortal({ // State 2's ×; state 1 has none (Renew is the action) and Escape leaves it showing. cancel: () => (strip.phase === 'renewed' ? clearCloudRunningSignout(paneKey) : undefined) } + // CHAT-RENEW-INPLACE: "sign-in expired · Renew" renews right here; renewed keeps RA-11's Restart. + const model = cloudRunningStripModel(strip, t) + const shown = + strip.phase === 'expired' + ? withRenewInPlace({ + agent: strip.agent, + setup: accounts.setups[strip.agent], + model, + actions, + key: paneKey, + t + }) + : { model, actions } return ( ) diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudStripSettingsLink.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudStripSettingsLink.tsx new file mode 100644 index 00000000000..e8bc3692d04 --- /dev/null +++ b/src/renderer/src/components/agent-sign-in-strip/CloudStripSettingsLink.tsx @@ -0,0 +1,34 @@ +import React from 'react' +import { cn } from '@/lib/class-names' + +/** + * CHAT-RENEW-INPLACE: the strip's quiet "Renew in Settings" link, at the end of the actions row, or on + * its own line under the buttons in the narrow stack (design-squad). + */ +export function CloudStripSettingsLink({ + label, + onOpen, + ownLine = false +}: { + label: string + onOpen?: () => void + ownLine?: boolean +}): React.JSX.Element | null { + if (!onOpen) { + return null + } + return ( + + ) +} diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.test.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.test.ts index 547f12c3306..388752f0dd0 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.test.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.test.ts @@ -5,11 +5,11 @@ import { cloudAgentStripModel } from './cloud-agent-strip-model' const base = { agent: 'claude' as const, hostLabel: 'the sandbox', t: translate } describe('cloudAgentStripModel', () => { - it('account recovery (S4-c): Renew, account-level wording, no per-workspace words', () => { + it('account recovery (S4-c), held: Renew, "Renew to start Claude." (CHAT-RENEW-INPLACE copy)', () => { const model = cloudAgentStripModel({ ...base, reason: 'accountExpired', view: null }) expect(model).toMatchObject({ title: 'Your Claude sign-in expired', - detail: 'Sign in once to fix every workspace.', + detail: 'Renew to start Claude.', primary: { label: 'Renew', action: { kind: 'renew' } } }) }) diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts index 3f7b7a6baa6..e0f7827e35e 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts @@ -57,6 +57,11 @@ export type CloudStripModel = { otherWays: boolean /** Already on a code: ⋯ offers the paste fallback and Cancel instead of "Use a code". */ codeStep?: boolean + /** + * CHAT-RENEW-INPLACE: a quiet text link at the end of the actions row ("Renew in Settings"); in + * the narrow stack it gets its own line under the buttons. + */ + settingsLink?: string /** RA-11 state 2: a dismiss × with this label (the strip otherwise drops its × on Renew). */ dismiss?: string /** RA-11 "Restarting…": nothing to close; the strip leaves with the result. */ @@ -121,15 +126,15 @@ export function cloudAgentStripModel(args: { return { status: 'warning', title: t('agentSignInStrip.expired', 'Your {{agent}} sign-in expired', { agent }), - detail: t('agentSignInStrip.expiredDetail', 'Sign in once to fix every workspace.'), + detail: t('agentSignInStrip.expiredHeldDetail', 'Renew to start {{agent}}.', { agent }), description: null, primary: { label: t('agentSignInStrip.renew', 'Renew'), action: { kind: 'renew' } }, code: null, paste: null, otherWays: false, announcement: t( - 'agentSignInStrip.expiredAnnounce', - 'Your {{agent}} sign-in expired. Renew it once to fix every workspace.', + 'agentSignInStrip.expiredHeldAnnounce', + 'Your {{agent}} sign-in expired. Renew to start {{agent}}.', { agent } ) } diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-chat-running-strip.test.tsx b/src/renderer/src/components/agent-sign-in-strip/cloud-chat-running-strip.test.tsx index 45147d775d6..aac72b6f24e 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-chat-running-strip.test.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-chat-running-strip.test.tsx @@ -21,7 +21,8 @@ const stub = vi.hoisted(() => { cleared: string[] calls: { paneKey: string; turnEndedFallback?: boolean }[] openedSettings: number - } = { strip: null, held: false, cleared: [], calls: [], openedSettings: 0 } + renewsRun: string[][] + } = { strip: null, held: false, cleared: [], calls: [], openedSettings: 0, renewsRun: [] } return state }) @@ -47,6 +48,9 @@ vi.mock('@/lib/orca-cloud/orca-cloud-environment-id', () => ({ })) vi.mock('@/lib/orca-cloud/orca-cloud-agent-accounts-store', () => ({ orcaCloudAgentAccountsLoadedAt: () => 1, + runOrcaCloudAgentSetups: (agents: string[]) => stub.renewsRun.push(agents), + stopOrcaCloudAgentSetups: () => undefined, + reloadOrcaCloudAgentAccounts: async () => undefined, useOrcaCloudAgentAccounts: () => ({ load: { kind: 'loading' }, keyKinds: {}, @@ -118,7 +122,9 @@ describe('the running strip on a structured chat (B2)', () => { mount() expect(screen.getAllByText(/Claude sign-in expired/).length).toBeGreaterThan(0) fireEvent.click(screen.getByRole('button', { name: /Renew/ })) - expect(stub.openedSettings).toBe(1) + // CHAT-RENEW-INPLACE: Renew runs the renewal right here, never Settings. + expect(stub.renewsRun).toEqual([['claude']]) + expect(stub.openedSettings).toBe(0) expect(stub.calls.at(-1)).toEqual({ paneKey: STATUS_KEY, turnEndedFallback: true }) }) diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.test.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.test.ts new file mode 100644 index 00000000000..8620ee7337e --- /dev/null +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.test.ts @@ -0,0 +1,153 @@ +// CHAT-RENEW-INPLACE: every expired strip renews in place, with design-squad's per-step copy. +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaCloudAgentSetup } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import type { CloudStripActions } from './CloudAgentSignInStrip' +import type { CloudStripModel } from './cloud-agent-strip-model' +import { translate as t } from '@/i18n/i18n' + +const store = vi.hoisted(() => ({ run: vi.fn(), stop: vi.fn() })) +vi.mock('@/lib/orca-cloud/orca-cloud-agent-accounts-store', () => ({ + runOrcaCloudAgentSetups: store.run, + stopOrcaCloudAgentSetups: store.stop, + reloadOrcaCloudAgentAccounts: async () => undefined +})) +vi.mock('@/lib/orca-cloud/cloud-agent-launch-hold', () => ({ + releaseCloudAgentHold: vi.fn(), + startCloudAgentHold: vi.fn() +})) +vi.mock('@/store', () => ({ useAppStore: { getState: () => ({}) } })) +vi.mock('../agent-sign-in/AgentSignInPanePortals', () => ({ + agentSignInCardActions: () => ({ copyText: vi.fn(), openLink: vi.fn() }) +})) +const api = vi.hoisted(() => ({ reopen: vi.fn(async () => undefined), submitClaudeCode: vi.fn() })) +vi.stubGlobal('window', { api: { orcaCloudAgents: api } }) + +const { cloudRenewInPlaceActions, cloudRenewInPlaceModel } = await import('./cloud-renew-in-place') + +const EXPIRED: CloudStripModel = { + status: 'warning', + title: 'Your Claude sign-in expired', + detail: 'Renew to keep working. Your conversation is kept.', + description: null, + primary: { label: 'Renew', action: { kind: 'renew' } }, + code: null, + paste: null, + otherWays: false, + announcement: 'Your Claude sign-in expired.' +} + +const model = (setup: OrcaCloudAgentSetup) => + cloudRenewInPlaceModel({ agent: 'claude', expired: EXPIRED, setup, t }) + +describe('cloudRenewInPlaceModel (design-squad per-step copy)', () => { + it("1 expired: the surface's own strip, [Renew], no Settings link", () => { + expect(model({ phase: 'idle' })).toBe(EXPIRED) + expect(model({ phase: 'saved' })).toBe(EXPIRED) + }) + + it('2 browser: same title, paste code, [Finish renewing] [Open again], "Renew in Settings"', () => { + const shown = model({ phase: 'browser', startedAt: 0, canReopen: true, acceptsCode: true }) + expect(shown.title).toBe('Your Claude sign-in expired') + expect(shown.detail).toBe('Finish in your browser, then paste the code here.') + expect(shown.paste?.setupCode).toEqual({ + placeholder: 'Paste code', + submitLabel: 'Finish renewing' + }) + expect(shown.primary).toMatchObject({ label: 'Open again', action: { kind: 'reopenSetup' } }) + expect(shown.settingsLink).toBe('Renew in Settings') + expect(JSON.stringify(shown)).not.toContain('Finish setup') + }) + + it('3 checking: the field and its button disabled', () => { + const shown = model({ + phase: 'browser', + startedAt: 0, + canReopen: true, + acceptsCode: true, + code: 'checking' + }) + expect(shown.paste).toMatchObject({ submitting: true }) + expect(shown.paste?.setupCode?.submitLabel).toBe('Checking the code…') + }) + + it('4 rejected: "Code didn\'t work", the newest-code detail, [Open again] and the Settings link', () => { + const shown = model({ + phase: 'browser', + startedAt: 0, + canReopen: true, + acceptsCode: true, + code: 'rejected' + }) + expect(shown.title).toBe('Code didn’t work') + expect(shown.detail).toBe('Paste the newest code from the sign-in page, or open it again.') + expect(shown.paste?.refusal).toBeTruthy() + expect(shown.primary?.action.kind).toBe('reopenSetup') + expect(shown.settingsLink).toBe('Renew in Settings') + }) + + it('a setup that failed outright starts again from Renew', () => { + const shown = model({ phase: 'failed', error: 'denied' }) + expect(shown.status).toBe('error') + expect(shown.primary?.action.kind).toBe('renew') + }) +}) + +describe('cloudRenewInPlaceActions', () => { + const surface = (): CloudStripActions => ({ + primary: vi.fn(), + submitCode: vi.fn(), + pasteCode: vi.fn(), + useCode: vi.fn(), + useApiKey: vi.fn(), + cancel: vi.fn() + }) + const actions = (setup: OrcaCloudAgentSetup, own = surface(), openSettings = vi.fn()) => ({ + own, + openSettings, + built: cloudRenewInPlaceActions({ + agent: 'claude', + setup, + surface: own, + openSettings, + copyText: vi.fn(), + openLink: vi.fn() + }) + }) + beforeEach(() => { + store.run.mockClear() + store.stop.mockClear() + api.reopen.mockClear() + }) + + it('Renew runs the setup here (never the Settings page or the sign-in sheet)', () => { + const { built, own, openSettings } = actions({ phase: 'idle' }) + built.primary({ kind: 'renew' }) + expect(store.run).toHaveBeenCalledExactlyOnceWith(['claude']) + expect(own.primary).not.toHaveBeenCalled() + expect(openSettings).not.toHaveBeenCalled() + }) + + it('Open again reopens the setup page; "Renew in Settings" opens Settings', () => { + const { built, openSettings } = actions({ phase: 'browser', startedAt: 0, canReopen: true }) + built.primary({ kind: 'reopenSetup' }) + expect(api.reopen).toHaveBeenCalledExactlyOnceWith({ agent: 'claude' }) + built.openSettings?.() + expect(openSettings).toHaveBeenCalledOnce() + }) + + it('6: × mid-flow stops the setup (back to step 1) and never dismisses the strip', () => { + const { built, own } = actions({ phase: 'browser', startedAt: 0, canReopen: true }) + built.cancel() + expect(store.stop).toHaveBeenCalledExactlyOnceWith('claude') + expect(own.cancel).not.toHaveBeenCalled() + }) + + it('outside a renewal, the surface keeps its own × and Restart', () => { + const { built, own } = actions({ phase: 'idle' }) + built.cancel() + built.primary({ kind: 'restart' }) + expect(store.stop).not.toHaveBeenCalled() + expect(own.cancel).toHaveBeenCalledOnce() + expect(own.primary).toHaveBeenCalledExactlyOnceWith({ kind: 'restart' }) + }) +}) diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts new file mode 100644 index 00000000000..f6514d36286 --- /dev/null +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts @@ -0,0 +1,159 @@ +// CHAT-RENEW-INPLACE (Option A, design-squad per-step copy): every "sign-in expired" strip — a held +// launch, a running terminal, a structured chat — renews in place. Renew runs the same Orca Cloud +// setup as "Set up once" right in the strip (re-running it replaces the account's expired sign-in), +// instead of sending the person to Settings. One model and one set of actions for every surface, so +// the terminal and the chat can't drift apart. +// 1 expired: [Renew] 2 browser: paste code, [Finish renewing] [Open again] × +// 3 checking: field and buttons disabled 4 rejected: "Code didn't work", [Open again] +// 5 renewed: the surface's own renewed state (held: Start; terminal: Restart; chat: next message) +// × mid-flow stops the setup and goes back to step 1; it never dismisses the strip. +import type { Translate } from '@/i18n/use-translate' +import { useAppStore } from '@/store' +import { + runOrcaCloudAgentSetups, + stopOrcaCloudAgentSetups +} from '@/lib/orca-cloud/orca-cloud-agent-accounts-store' +import type { OrcaCloudAgentSetup } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire' +import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status' +import type { CloudStripActions } from './CloudAgentSignInStrip' +import type { CloudStripModel } from './cloud-agent-strip-model' +import { cloudAgentSetupStripModel } from './cloud-agent-setup-strip-model' +import { cloudSetupStripActions } from './cloud-setup-strip-actions' +import { agentSignInCardActions } from '../agent-sign-in/AgentSignInPanePortals' + +/** The renewal's own setup is under way (steps 2-4): the strip shows it instead of step 1. */ +export function renewInPlaceRunning(setup: OrcaCloudAgentSetup): boolean { + return setup.phase !== 'idle' && setup.phase !== 'saved' +} + +/** + * Steps 1-4 over a surface's "expired" model (step 1 keeps the surface's own detail: running "Renew + * to keep working…", held "Renew to start {{agent}}."). Step 5 is each surface's renewed state. + */ +export function cloudRenewInPlaceModel(args: { + agent: HostAgentSignInAgent + expired: CloudStripModel + setup: OrcaCloudAgentSetup + t: Translate +}): CloudStripModel { + const { expired, setup, t } = args + if (!renewInPlaceRunning(setup)) { + return expired + } + const flow = cloudAgentSetupStripModel({ agent: args.agent, setup, ready: false, t }) + const settingsLink = t('agentSignInStrip.renewInSettings', 'Renew in Settings') + // A failed setup keeps its own words; a refused code says "Code didn't work" (as #484). + const keepsTitle = + setup.phase === 'failed' || (setup.phase === 'browser' && setup.code === 'rejected') + const finishRenewing = t('agentSignInStrip.finishRenewing', 'Finish renewing') + const paste = flow.paste + ? { + ...flow.paste, + // Never the setup's "Finish setup" (design-squad). + ...(flow.paste.setupCode + ? { + setupCode: { + ...flow.paste.setupCode, + submitLabel: + setup.phase === 'browser' && setup.code === 'checking' + ? flow.paste.setupCode.submitLabel + : finishRenewing + } + } + : {}), + ...(flow.paste.submitLabel ? { submitLabel: finishRenewing } : {}) + } + : null + return { + ...flow, + title: keepsTitle ? flow.title : expired.title, + paste, + // A setup that failed outright starts again from Renew. + primary: + setup.phase === 'failed' && flow.primary?.action.kind === 'setUpOnce' + ? { ...flow.primary, action: { kind: 'renew' } } + : flow.primary, + ...(setup.phase === 'browser' || setup.phase === 'paste' ? { settingsLink } : {}), + announcement: keepsTitle ? flow.announcement : `${expired.title}. ${flow.announcement}` + } +} + +/** + * Renew starts the setup here; Open again, the code and the paste go to it; × stops it (back to + * step 1). With no renewal running, everything else is the surface's own (its × or Restart). + */ +export function cloudRenewInPlaceActions(args: { + agent: HostAgentSignInAgent + setup: OrcaCloudAgentSetup + /** The surface's own actions, used outside the renewal (Restart, a renewed strip's ×). */ + surface: CloudStripActions + /** "Renew in Settings": the same renewal in Settings › Accounts › Orca Cloud. */ + openSettings: () => void + copyText: (text: string) => void + openLink: (url: string) => void +}): CloudStripActions { + const running = renewInPlaceRunning(args.setup) + const flow = cloudSetupStripActions({ + agent: args.agent, + // Renewing holds nothing itself: Start (step 5) belongs to the surface. + holdKey: '', + setupRunning: running, + copyText: args.copyText, + openLink: args.openLink, + useApiKey: args.surface.useApiKey, + keepHoldOnCancel: true + }) + return { + ...args.surface, + primary: (action) => { + if (action.kind === 'renew') { + runOrcaCloudAgentSetups([args.agent]) + } else if (action.kind === 'reopenSetup' || action.kind === 'copyAndOpen') { + flow.primary(action) + } else { + args.surface.primary(action) + } + }, + submitCode: running ? flow.submitCode : args.surface.submitCode, + submitSetupCode: flow.submitSetupCode, + pasteCode: running ? flow.pasteCode : args.surface.pasteCode, + openSettings: args.openSettings, + cancel: () => (running ? stopOrcaCloudAgentSetups(args.agent) : args.surface.cancel()) + } +} + +/** "Renew in Settings": Settings › Accounts › Orca Cloud, where the same renewal runs. */ +export function openOrcaCloudAccountsSettings(): void { + const store = useAppStore.getState() + store.openSettingsTarget({ pane: 'accounts', repoId: null, sectionId: 'orca-cloud' }) + store.openSettingsPage() +} + +/** A surface's expired strip, renewing in place: its model (steps 1-4) and actions together. */ +export function withRenewInPlace(args: { + agent: HostAgentSignInAgent + setup: OrcaCloudAgentSetup + model: CloudStripModel + actions: CloudStripActions + /** The pane or chat key, for the sign-in page's copy and open. */ + key: string + t: Translate +}): { model: CloudStripModel; actions: CloudStripActions } { + const page = agentSignInCardActions(args.key) + return { + model: cloudRenewInPlaceModel({ + agent: args.agent, + expired: args.model, + setup: args.setup, + t: args.t + }), + actions: cloudRenewInPlaceActions({ + agent: args.agent, + setup: args.setup, + surface: args.actions, + openSettings: openOrcaCloudAccountsSettings, + copyText: page.copyText, + openLink: page.openLink + }) + } +} diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts index ab90eac24da..7325eea6371 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts @@ -31,7 +31,7 @@ export function cloudSetupStripActions(args: { keepHoldOnCancel?: boolean }): CloudStripActions { const { agent, holdKey } = args - const api = window.api.orcaCloudAgents + const api = window.api?.orcaCloudAgents return { primary: (action) => { if (action.kind === 'setUpOnce') { diff --git a/src/renderer/src/components/agent-sign-in-strip/use-cloud-chat-running-strip.ts b/src/renderer/src/components/agent-sign-in-strip/use-cloud-chat-running-strip.ts index 9a5ab27a572..92330c53794 100644 --- a/src/renderer/src/components/agent-sign-in-strip/use-cloud-chat-running-strip.ts +++ b/src/renderer/src/components/agent-sign-in-strip/use-cloud-chat-running-strip.ts @@ -26,12 +26,7 @@ import { import type { CloudStripActions } from './CloudAgentSignInStrip' import type { CloudHeldStrip } from './use-cloud-held-strip' import { cloudChatRunningStripModel } from './cloud-running-strip-model' - -function openAccounts(): void { - const store = useAppStore.getState() - store.openSettingsTarget({ pane: 'accounts', repoId: null, sectionId: 'orca-cloud' }) - store.openSettingsPage() -} +import { openOrcaCloudAccountsSettings, withRenewInPlace } from './cloud-renew-in-place' /** The Orca Cloud environment a structured chat's tab runs on, or null. */ function useChatEnvironmentId(tabId: string): string | null { @@ -94,7 +89,8 @@ export function useCloudChatAccountStrip(args: ChatAccountArgs): CloudRunningStr } return cloudRunningStrip({ paneKey: args.statusKey, - entry: status ?? { agentType: agent, state: 'idle' }, + // An idle chat (no message yet) has no status entry: decided from its own agent. + entry: status ?? { agentType: agent, state: 'waiting' }, accounts, held, now: orcaCloudAgentAccountsLoadedAt(), @@ -108,11 +104,12 @@ export function useCloudChatAccountStrip(args: ChatAccountArgs): CloudRunningStr export function useCloudChatRunningStrip(args: ChatAccountArgs): CloudHeldStrip | null { const t = useTranslate() const strip = useCloudChatAccountStrip(args) + const accounts = useOrcaCloudAgentAccounts(strip !== null) if (!strip) { return null } const actions: CloudStripActions = { - primary: (action) => (action.kind === 'renew' ? openAccounts() : undefined), + primary: (action) => (action.kind === 'renew' ? openOrcaCloudAccountsSettings() : undefined), submitCode: () => undefined, pasteCode: () => undefined, useCode: () => undefined, @@ -120,7 +117,20 @@ export function useCloudChatRunningStrip(args: ChatAccountArgs): CloudHeldStrip // Expired has no ×; renewed's × dismisses. cancel: () => (strip.phase === 'renewed' ? clearCloudRunningSignout(args.statusKey) : undefined) } - return { model: cloudChatRunningStripModel(strip, t), prompt: null, actions } + const model = cloudChatRunningStripModel(strip, t) + // CHAT-RENEW-INPLACE: the chat's "sign-in expired · Renew" renews right here. + const shown = + strip.phase === 'expired' + ? withRenewInPlace({ + agent: strip.agent, + setup: accounts.setups[strip.agent], + model, + actions, + key: args.statusKey, + t + }) + : { model, actions } + return { ...shown, prompt: null } } /** diff --git a/src/renderer/src/components/agent-sign-in-strip/use-cloud-held-strip.ts b/src/renderer/src/components/agent-sign-in-strip/use-cloud-held-strip.ts index fa9989f86ae..5711413b7db 100644 --- a/src/renderer/src/components/agent-sign-in-strip/use-cloud-held-strip.ts +++ b/src/renderer/src/components/agent-sign-in-strip/use-cloud-held-strip.ts @@ -21,6 +21,11 @@ import { cloudAgentSetupStripModel } from './cloud-agent-setup-strip-model' import { cloudSetupStripActions } from './cloud-setup-strip-actions' +import { + cloudRenewInPlaceActions, + cloudRenewInPlaceModel, + openOrcaCloudAccountsSettings +} from './cloud-renew-in-place' export type CloudHeldStrip = { model: CloudStripModel @@ -70,7 +75,7 @@ export function useCloudHeldStrip( const setupHold = hold?.reason === 'notSetUp' || awaiting !== null const setup = accounts.setups[agent] // HELD-STALE-COVERED: the setup just finished here: "is set up · Start" (the account, read fresh). - const model = + const shownBeforeRenew = awaiting === 'setUp' ? cloudAgentSetupStripModel({ agent, setup: accounts.setups[agent], ready: true, t }) : awaiting @@ -95,6 +100,11 @@ export function useCloudHeldStrip( hostLabel: cloudGate?.hostLabel ?? t('agentSignInStrip.sandbox', 'the sandbox'), t }) + // CHAT-RENEW-INPLACE: a launch held on an expired sign-in renews right here (steps 1-4). + const renewing = hold?.reason === 'accountExpired' + const model = renewing + ? cloudRenewInPlaceModel({ agent, expired: shownBeforeRenew, setup, t }) + : shownBeforeRenew const setupRunning = setup.phase !== 'idle' && setup.phase !== 'saved' && setup.phase !== 'failed' const holdActions: CloudStripActions | null = setupHold ? cloudSetupStripActions({ @@ -107,7 +117,7 @@ export function useCloudHeldStrip( keepHoldOnCancel: chat }) : null - const actions: CloudStripActions = holdActions ?? { + const gateOrRecovery: CloudStripActions = { primary: (action) => { // RA-11's restart belongs to the running-pane strip; a held launch never offers it. if ( @@ -152,9 +162,21 @@ export function useCloudHeldStrip( } } } + const actions: CloudStripActions = + holdActions ?? + (renewing + ? cloudRenewInPlaceActions({ + agent, + setup, + surface: gateOrRecovery, + openSettings: openOrcaCloudAccountsSettings, + copyText: gateActions.copyText, + openLink: gateActions.openLink + }) + : gateOrRecovery) // A held chat's strip has nothing to cancel unless a setup is running: no × (Escape is a no-op). const shownModel = - chat && hold && !(setupHold && setupRunning) ? { ...model, noClose: true } : model + chat && hold && !((setupHold || renewing) && setupRunning) ? { ...model, noClose: true } : model return { key, active, diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index dc213e5b036..7caf5e1b393 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -29017,6 +29017,10 @@ "nothingNeedsAttention": "Nothing needs attention." }, "agentSignInStrip": { + "renewInSettings": "Renew in Settings", + "finishRenewing": "Finish renewing", + "expiredHeldDetail": "Renew to start {{agent}}.", + "expiredHeldAnnounce": "Your {{agent}} sign-in expired. Renew to start {{agent}}.", "rowNeedsSignIn": "Needs sign-in", "rowNeedsSignInTooltip": "Set up once for Orca Cloud", "rowExpired": "Sign-in expired", From 22090289d709655c22de739e8cff0ec4a3f439e7 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 23:30:49 -0800 Subject: [PATCH 21/28] chore(i18n): CHAT-RENEW-INPLACE drop the held strip's old expired copy keys --- src/renderer/src/i18n/locales/en.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 7caf5e1b393..0a55f8e38ba 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -29040,9 +29040,7 @@ "useMySignIn": "Use my {{agent}} sign-in", "signIn": "Sign in", "expired": "Your {{agent}} sign-in expired", - "expiredDetail": "Sign in once to fix every workspace.", "renew": "Renew", - "expiredAnnounce": "Your {{agent}} sign-in expired. Renew it once to fix every workspace.", "waiting": "Approve on {{site}}", "openAgain": "Open again", "waitingAnnounce": "Waiting for you to approve in your browser.", From 353ad5b8df346bd146a742295ec523147aeaa2a9 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 23:36:33 -0800 Subject: [PATCH 22/28] fix(cloud): CHAT-RENEW-INPLACE "Renew in Settings" is underlined at rest (quiet-link rule) --- .../components/agent-sign-in-strip/CloudStripSettingsLink.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudStripSettingsLink.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudStripSettingsLink.tsx index e8bc3692d04..39bce76b0dc 100644 --- a/src/renderer/src/components/agent-sign-in-strip/CloudStripSettingsLink.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/CloudStripSettingsLink.tsx @@ -23,7 +23,8 @@ export function CloudStripSettingsLink({ data-strip-settings-link onClick={onOpen} className={cn( - 'shrink-0 cursor-pointer text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline', + // The quiet-link rule: underlined at rest (muted), stronger on hover, a visible focus ring. + 'shrink-0 cursor-pointer text-xs text-muted-foreground underline decoration-muted-foreground/50 underline-offset-2 hover:text-foreground hover:decoration-foreground', 'rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring', ownLine && 'basis-full text-left' )} From 084b3d1e9dd2d0efc37ff8a659453baa580ff4fc Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 23:37:42 -0800 Subject: [PATCH 23/28] fix(cloud): CHAT-RENEW-INPLACE Open again keeps its Copy link during a renewal --- .../src/components/agent-sign-in-strip/cloud-renew-in-place.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts index f6514d36286..6934dc64204 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-renew-in-place.ts @@ -116,6 +116,8 @@ export function cloudRenewInPlaceActions(args: { }, submitCode: running ? flow.submitCode : args.surface.submitCode, submitSetupCode: flow.submitSetupCode, + // "Copy link" beside Open again: the renewal's sign-in page, as for "Set up once". + linkFor: running ? flow.linkFor : args.surface.linkFor, pasteCode: running ? flow.pasteCode : args.surface.pasteCode, openSettings: args.openSettings, cancel: () => (running ? stopOrcaCloudAgentSetups(args.agent) : args.surface.cancel()) From 7533e82242bc1fb4760275cfbdb173dd0b5dda10 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 21:45:55 -0800 Subject: [PATCH 24/28] fix(team): TEAM-DIALOG-2; drop the header Plan & billing button, invite line is only the seat rule --- .../billing/team/TeamInviteComposer.test.tsx | 32 +++++++ .../billing/team/TeamInviteComposer.tsx | 30 +----- .../billing/team/TeamPageView.fixture.tsx | 23 +---- .../billing/team/TeamPageView.test.tsx | 63 ++++++++++++ .../components/billing/team/TeamPageView.tsx | 20 +--- .../team/team-invite-impact-copy.test.ts | 96 ------------------- .../billing/team/team-invite-impact-copy.ts | 86 ----------------- .../billing/team/team-seat-math.test.ts | 77 +-------------- .../components/billing/team/team-seat-math.ts | 81 +--------------- .../src/i18n/en-runtime-required.json | 8 -- src/renderer/src/i18n/locales/en.json | 16 +--- 11 files changed, 106 insertions(+), 426 deletions(-) create mode 100644 src/renderer/src/components/billing/team/TeamInviteComposer.test.tsx create mode 100644 src/renderer/src/components/billing/team/TeamPageView.test.tsx delete mode 100644 src/renderer/src/components/billing/team/team-invite-impact-copy.test.ts delete mode 100644 src/renderer/src/components/billing/team/team-invite-impact-copy.ts diff --git a/src/renderer/src/components/billing/team/TeamInviteComposer.test.tsx b/src/renderer/src/components/billing/team/TeamInviteComposer.test.tsx new file mode 100644 index 00000000000..3eb9fe09a3b --- /dev/null +++ b/src/renderer/src/components/billing/team/TeamInviteComposer.test.tsx @@ -0,0 +1,32 @@ +// @vitest-environment happy-dom +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { TeamInviteComposer } from './TeamInviteComposer' + +afterEach(cleanup) + +const RULE = 'Each invite uses a seat once accepted.' + +it('says only the seat rule, with no seat counts or prices, however many are entered', () => { + render( ({ failed: [] })} />, { + wrapper: TooltipProvider + }) + const input = screen.getByRole('textbox') + const hint = document.getElementById(input.getAttribute('aria-describedby')!)! + expect(hint.textContent).toBe(RULE) + + fireEvent.change(input, { target: { value: 'jordan@acme.dev, kim@acme.dev ' } }) + expect(hint.textContent).toBe(RULE) + expect(hint.textContent).not.toMatch(/open seat|\$|prorated/) +}) + +it('still flags invalid entries after the rule', () => { + render( ({ failed: [] })} />, { + wrapper: TooltipProvider + }) + const input = screen.getByRole('textbox') + fireEvent.change(input, { target: { value: 'jordan@acme.dev, not-an-email ' } }) + const hint = document.getElementById(input.getAttribute('aria-describedby')!)! + expect(hint.textContent).toBe(`${RULE} Skipping 1 invalid entry.`) +}) diff --git a/src/renderer/src/components/billing/team/TeamInviteComposer.tsx b/src/renderer/src/components/billing/team/TeamInviteComposer.tsx index 566ea08c500..4c1429b5d25 100644 --- a/src/renderer/src/components/billing/team/TeamInviteComposer.tsx +++ b/src/renderer/src/components/billing/team/TeamInviteComposer.tsx @@ -10,9 +10,8 @@ import { } from '@/components/ui/select' import { LoadingSpinner } from '@/components/LoadingSpinner' import { SettingsDisabledControlTooltip } from '@/components/settings/form-controls/SettingsDisabledControlTooltip' -import { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/class-names' -import type { OrcaBillingEntitlement } from '../../../../../shared/orca-billing' import type { OrcaOrgRole } from '../../../../../shared/orca-profiles' import { MAX_INVITES_PER_BATCH, @@ -22,17 +21,11 @@ import { } from './parse-invite-emails' import { roleDescription } from './team-copy' import { assignableRoles, roleLabel } from './team-roles' -import { inviteSeatImpactLine } from './team-invite-impact-copy' -import { inviteSeatImpact } from './team-seat-math' export type InviteBatchOutcome = { failed: { email: string; message: string }[] } export type TeamInviteComposerProps = { viewerRole: OrcaOrgRole - entitlement: OrcaBillingEntitlement | null - members: number - pendingInvites: number - now: number /** Sends every invite; resolves with the ones that failed so they stay in the field. */ onInvite: (emails: string[], role: OrcaOrgRole) => Promise inputRef?: React.Ref @@ -41,7 +34,6 @@ export type TeamInviteComposerProps = { /** Multi-email invite field: paste a list, review the chips, pick a role, send. */ export function TeamInviteComposer(props: TeamInviteComposerProps): React.JSX.Element { const t = useTranslate() - const locale = useIntlLocale() const id = useId() const [draft, setDraft] = useState('') const [candidates, setCandidates] = useState([]) @@ -65,19 +57,10 @@ export function TeamInviteComposer(props: TeamInviteComposerProps): React.JSX.El const pendingDraft = draft.trim() ? mergeInviteCandidates(candidates, splitInviteText(draft)) : candidates - // The button and the seat line both count what Send would send, including a typed, - // unseparated address, so the seat impact always matches the invites about to go out. + // The button counts what Send would send, including a typed, unseparated address. const valid = pendingDraft.filter((candidate) => candidate.valid) const committedValid = candidates.filter((candidate) => candidate.valid) const invalidCount = candidates.length - committedValid.length - const paymentFailed = props.entitlement?.payment.pastDueSince != null - const impact = inviteSeatImpact({ - entitlement: props.entitlement, - members: props.members, - pendingInvites: props.pendingInvites, - newInvites: valid.length, - now: props.now - }) const send = async (): Promise => { const all = commit(draft) @@ -271,13 +254,8 @@ export function TeamInviteComposer(props: TeamInviteComposerProps): React.JSX.El

- {inviteSeatImpactLine(impact, valid.length, locale, t)} - {paymentFailed && valid.length > 0 - ? ` ${t( - 'auto.components.billing.team.invitePaymentFailed2', - 'New seats are charged once the failed payment is fixed.' - )}` - : null} + {/* Only the rule: seat counts and prices live in Plan & billing (Neil, TEAM-DIALOG-2). */} + {t('auto.components.billing.team.inviteSeatRule', 'Each invite uses a seat once accepted.')} {invalidCount > 0 ? ` ${t( 'auto.components.billing.team.skipInvalid', diff --git a/src/renderer/src/components/billing/team/TeamPageView.fixture.tsx b/src/renderer/src/components/billing/team/TeamPageView.fixture.tsx index 67784fa9137..1eb77834e17 100644 --- a/src/renderer/src/components/billing/team/TeamPageView.fixture.tsx +++ b/src/renderer/src/components/billing/team/TeamPageView.fixture.tsx @@ -244,34 +244,13 @@ async function typeInvites(text: string): Promise { await new Promise((resolve) => setTimeout(resolve, 100)) } -/** Will add seats: 4 paid, 4 members and 2 pending, so both new invites add a seat. */ +/** Pasted list: the chips, one invalid entry, and the seat rule (no counts or prices). */ export const invitePasted = defineFixture({ width, render: () => , interact: () => typeInvites('jordan@acme.dev, kim@acme.dev, not-an-email ') }) -/** Seats free: 8 paid, 6 taken (members plus pending), so one invite adds nothing. */ -export const inviteSeatsFree = defineFixture({ - width, - render: () => , - interact: () => typeInvites('jordan@acme.dev ') -}) - -/** Billing unknown (disabled in this build, or it failed): the rule without counts or prices. */ -export const inviteBillingUnknown = defineFixture({ - width, - render: () => , - interact: () => typeInvites('jordan@acme.dev, kim@acme.dev ') -}) - -/** Billing sent no price: seats are still counted, no price is shown. */ -export const inviteNoPrice = defineFixture({ - width, - render: () => , - interact: () => typeInvites('jordan@acme.dev, kim@acme.dev ') -}) - /** Short roster so the Enterprise row sits inside the frame. */ export const ssoRow = defineFixture({ width, diff --git a/src/renderer/src/components/billing/team/TeamPageView.test.tsx b/src/renderer/src/components/billing/team/TeamPageView.test.tsx new file mode 100644 index 00000000000..5ae89ebf7cf --- /dev/null +++ b/src/renderer/src/components/billing/team/TeamPageView.test.tsx @@ -0,0 +1,63 @@ +// @vitest-environment happy-dom +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, it } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import type { OrcaOrgMembersRoster } from '../../../../../shared/orca-profiles' +import { sampleTeam } from '../plan-billing-fixtures' +import { TeamPageView, type TeamPageViewProps } from './TeamPageView' + +afterEach(cleanup) + +const roster: OrcaOrgMembersRoster = { + viewerRole: 'owner', + canManageMembers: true, + members: [ + { userId: 'u-neil', email: 'neil@acme.dev', displayName: 'Neil Parker', role: 'owner' }, + { userId: 'u-ada', email: 'ada@acme.dev', displayName: 'Ada Lovelace', role: 'admin' } + ], + pendingInvites: [{ email: 'sam@acme.dev', role: 'member', createdAt: 0 }] +} + +const noop = (): void => {} +const props: TeamPageViewProps = { + org: { orgId: 'org-acme', name: 'Acme Engineering' }, + viewerUserId: 'u-neil', + roster: { status: 'ok', roster }, + billing: { status: 'ok', entitlement: { ...sampleTeam, canManageBilling: true } }, + arrival: null, + rowStates: {}, + refreshing: false, + billingBusy: false, + now: 0, + create: { + organizations: [], + creating: false, + error: null, + unavailable: false, + switchingOrgId: null + }, + onCreateTeam: noop, + onSwitchOrg: noop, + onRefresh: noop, + onInvite: async () => ({ failed: [] }), + onChangeRole: noop, + onMakeOwner: noop, + onRemove: noop, + onResend: noop, + onRevoke: noop, + onLeave: noop, + onSeePlans: noop, + onManageBilling: noop, + onCreateWorkspace: noop, + onDismissArrival: noop +} + +it('keeps the header to the name and counts: no role sentence, no Plan & billing button', () => { + render(, { wrapper: TooltipProvider }) + const header = document.querySelector('header')! + expect(header.textContent).toContain('2 members · 1 invited') + expect(header.textContent).not.toMatch(/You’re an|Plan & billing/) + expect(header.querySelector('button')).toBeNull() + // Seat counts and prices live only in Plan & billing. + expect(screen.queryByText(/open seat/)).toBeNull() +}) diff --git a/src/renderer/src/components/billing/team/TeamPageView.tsx b/src/renderer/src/components/billing/team/TeamPageView.tsx index 427c63bb752..ccf26d7b5a2 100644 --- a/src/renderer/src/components/billing/team/TeamPageView.tsx +++ b/src/renderer/src/components/billing/team/TeamPageView.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef } from 'react' -import { CreditCard, RefreshCw } from 'lucide-react' +import { RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { InlineError } from '@/components/ui/inline-error' import { Skeleton } from '@/components/ui/skeleton' @@ -141,20 +141,6 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element { : t('auto.components.billing.team.loadFailedTitle', 'Couldn’t load team')}

- {!inline && entitlement?.canManageBilling ? ( - // Seats, prices and invoices live in Plan & billing; one quiet way there from here. - // mr-6 clears the dialog's close button, which sits in this corner. - - ) : null} {props.arrival?.kind === 'checkout-success' && entitlement ? ( @@ -213,10 +199,6 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element { {roster?.canManageMembers ? ( diff --git a/src/renderer/src/components/billing/team/team-invite-impact-copy.test.ts b/src/renderer/src/components/billing/team/team-invite-impact-copy.test.ts deleted file mode 100644 index e642e810f4c..00000000000 --- a/src/renderer/src/components/billing/team/team-invite-impact-copy.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { OrcaBillingEntitlement } from '../../../../../shared/orca-billing' -import type { Translate } from '@/i18n/use-translate' -import { sampleTeam } from '../plan-billing-fixtures' -import { formatCents } from '../plans/plans-pricing' -import { inviteSeatImpactLine } from './team-invite-impact-copy' -import { inviteSeatImpact } from './team-seat-math' - -const DAY = 86_400_000 - -// Mirrors i18next's `_one` plural pick so both forms are checked. -const t: Translate = (_key, fallback, options) => { - const one = options?.count === 1 ? options.defaultValue_one : undefined - const text = typeof one === 'string' ? one : fallback - return text.replace(/\{\{(\w+)\}\}/g, (_, name: string) => String(options?.[name] ?? '')) -} - -function team(overrides: Partial = {}): OrcaBillingEntitlement { - return { - ...sampleTeam, - status: 'active', - interval: 'month', - seats: 3, - seatChange: null, - cancelAtPeriodEnd: false, - period: { start: 0, end: 30 * DAY }, - ...overrides - } -} - -function line( - entitlement: OrcaBillingEntitlement | null, - counts: { members: number; pendingInvites: number; newInvites: number } -): string { - const impact = inviteSeatImpact({ entitlement, ...counts, now: 0 }) - return inviteSeatImpactLine(impact, counts.newInvites, 'en-US', t) -} - -const monthly = sampleTeam.offers?.team.monthlyPriceCentsPerSeat ?? 0 - -describe('invite seat impact line', () => { - it('says how many seats are open before anything is typed', () => { - expect(line(team({ seats: 5 }), { members: 2, pendingInvites: 1, newInvites: 0 })).toBe( - 'Each invite uses a seat once accepted. You have 2 open seats.' - ) - expect(line(team({ seats: 3 }), { members: 3, pendingInvites: 0, newInvites: 0 })).toBe( - 'Each invite uses a seat once accepted. You have no open seats.' - ) - }) - - it('adds nothing while the invites fit in open seats', () => { - expect(line(team({ seats: 4 }), { members: 3, pendingInvites: 0, newInvites: 1 })).toBe( - 'Each invite uses a seat once accepted. You have 1 open seat, so no seats will be added.' - ) - }) - - it('prices the added seats from billing, per period, prorated', () => { - const total = formatCents(2 * monthly, 'en-US') - expect(line(team({ seats: 3 }), { members: 3, pendingInvites: 0, newInvites: 2 })).toBe( - `Each invite uses a seat once accepted. You have no open seats, so 2 more seats (${total}/mo, prorated) will be added.` - ) - }) - - it('counts open seats first, then pluralizes the added ones apart', () => { - const one = formatCents(monthly, 'en-US') - expect(line(team({ seats: 4 }), { members: 3, pendingInvites: 0, newInvites: 2 })).toBe( - `Each invite uses a seat once accepted. You have 1 open seat, so 1 more seat (${one}/mo, prorated) will be added.` - ) - }) - - it('names the yearly price on annual plans', () => { - expect( - line(team({ seats: 1, interval: 'year' }), { members: 1, pendingInvites: 0, newInvites: 1 }) - ).toMatch(/\/yr, prorated\) will be added\.$/) - }) - - it('never shows a price billing did not send', () => { - expect( - line(team({ seats: 3, offers: null }), { members: 3, pendingInvites: 0, newInvites: 2 }) - ).toBe( - 'Each invite uses a seat once accepted. You have no open seats, so 2 more seats will be added, prorated.' - ) - }) - - it('keeps to the rule when billing is off or unreachable', () => { - expect(line(null, { members: 3, pendingInvites: 0, newInvites: 2 })).toBe( - 'Each invite uses a seat once accepted.' - ) - }) - - it('says invites are free before the team has a plan', () => { - expect( - line(team({ plan: null, status: 'none' }), { members: 1, pendingInvites: 0, newInvites: 1 }) - ).toBe('Invites are free. Seats are billed once your team picks a plan.') - }) -}) diff --git a/src/renderer/src/components/billing/team/team-invite-impact-copy.ts b/src/renderer/src/components/billing/team/team-invite-impact-copy.ts deleted file mode 100644 index c51d6e50e79..00000000000 --- a/src/renderer/src/components/billing/team/team-invite-impact-copy.ts +++ /dev/null @@ -1,86 +0,0 @@ -// The one line under "Invite teammates" that says what the invites do to seats. Billing's own -// numbers only (ENTITLEMENTS-C): no price is shown when billing didn't send one. -import type { Translate } from '@/i18n/use-translate' -import { formatCents } from '../plans/plans-pricing' -import type { InviteSeatImpact } from './team-seat-math' - -/** "You have N open seats", its own key so the seat count and the added count pluralize apart. */ -function openSeatsClause(open: number, t: Translate): string { - return open === 0 - ? t('auto.components.billing.team.openSeatsNone', 'You have no open seats') - : t('auto.components.billing.team.openSeatsClause', 'You have {{count}} open seats', { - count: open, - defaultValue_one: 'You have {{count}} open seat' - }) -} - -export function inviteSeatImpactLine( - impact: InviteSeatImpact, - invites: number, - locale: string, - t: Translate -): string { - switch (impact.kind) { - case 'unknown': - return t( - 'auto.components.billing.team.inviteSeatUnknown', - 'Each invite uses a seat once accepted.' - ) - case 'no-plan': - return t( - 'auto.components.billing.team.inviteNoPlan', - 'Invites are free. Seats are billed once your team picks a plan.' - ) - case 'covered': - return invites === 0 - ? t( - 'auto.components.billing.team.inviteSeatOpen', - 'Each invite uses a seat once accepted. {{openSeats}}.', - { - openSeats: openSeatsClause(impact.freeSeats, t) - } - ) - : t( - 'auto.components.billing.team.inviteSeatCovered', - 'Each invite uses a seat once accepted. {{openSeats}}, so no seats will be added.', - { openSeats: openSeatsClause(impact.freeSeats, t) } - ) - case 'adds-seats-unpriced': - return t( - 'auto.components.billing.team.inviteSeatAddsUnpriced', - 'Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seats will be added, prorated.', - { - openSeats: openSeatsClause(impact.freeSeats, t), - count: impact.addedSeats, - defaultValue_one: - 'Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seat will be added, prorated.' - } - ) - case 'adds-seats': { - const price = formatCents(impact.addedSeats * impact.perSeatPeriodCents, locale) - return impact.interval === 'year' - ? t( - 'auto.components.billing.team.inviteSeatAddsYear', - 'Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seats ({{price}}/yr, prorated) will be added.', - { - openSeats: openSeatsClause(impact.freeSeats, t), - count: impact.addedSeats, - price, - defaultValue_one: - 'Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seat ({{price}}/yr, prorated) will be added.' - } - ) - : t( - 'auto.components.billing.team.inviteSeatAddsMonth', - 'Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seats ({{price}}/mo, prorated) will be added.', - { - openSeats: openSeatsClause(impact.freeSeats, t), - count: impact.addedSeats, - price, - defaultValue_one: - 'Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seat ({{price}}/mo, prorated) will be added.' - } - ) - } - } -} diff --git a/src/renderer/src/components/billing/team/team-seat-math.test.ts b/src/renderer/src/components/billing/team/team-seat-math.test.ts index 94e18f86817..6c6919b83d0 100644 --- a/src/renderer/src/components/billing/team/team-seat-math.test.ts +++ b/src/renderer/src/components/billing/team/team-seat-math.test.ts @@ -1,17 +1,9 @@ import { describe, expect, it } from 'vitest' import type { OrcaBillingEntitlement } from '../../../../../shared/orca-billing' import { sampleTeam as activeTeamEntitlement } from '../plan-billing-fixtures' -import { inviteSeatImpact, nextInvoiceEstimate, proratedSeatCents } from './team-seat-math' +import { nextInvoiceEstimate } from './team-seat-math' const DAY = 86_400_000 -const noPlanEntitlement: OrcaBillingEntitlement = { - ...activeTeamEntitlement, - plan: null, - planLabel: null, - status: 'none', - interval: null, - period: null -} function team(overrides: Partial = {}): OrcaBillingEntitlement { return { @@ -25,73 +17,6 @@ function team(overrides: Partial = {}): OrcaBillingEntit } } -describe('proratedSeatCents', () => { - it('charges the remaining share of the period', () => { - const pricing = { interval: 'month' as const, perSeatPeriodCents: 5000 } - expect(proratedSeatCents(pricing, { start: 0, end: 30 * DAY }, 15 * DAY)).toBe(2500) - expect(proratedSeatCents(pricing, { start: 0, end: 30 * DAY }, 31 * DAY)).toBe(0) - expect(proratedSeatCents(pricing, { start: 0, end: 30 * DAY }, -DAY)).toBe(5000) - }) -}) - -describe('inviteSeatImpact', () => { - it('reports no plan when unsubscribed', () => { - expect( - inviteSeatImpact({ - entitlement: noPlanEntitlement, - members: 1, - pendingInvites: 0, - newInvites: 2, - now: 0 - }) - ).toEqual({ kind: 'no-plan' }) - }) - - it('uses seats already paid this period first (peak seats)', () => { - // 3 paid, 1 member: two free seats, so two invites cost nothing. - expect( - inviteSeatImpact({ - entitlement: team(), - members: 1, - pendingInvites: 0, - newInvites: 2, - now: 0 - }) - ).toEqual({ kind: 'covered', freeSeats: 2 }) - }) - - it('counts pending invites against free seats before new ones', () => { - const impact = inviteSeatImpact({ - entitlement: team(), - members: 2, - pendingInvites: 1, - newInvites: 2, - now: 15 * DAY - }) - expect(impact).toMatchObject({ - kind: 'adds-seats', - addedSeats: 2, - coveredSeats: 0, - proratedCentsEach: 2500 - }) - }) -}) - -describe('inviteSeatImpact without prices', () => { - it('still says seats are added (never "covered") when pricing is unknown', () => { - const unpriced = team({ offers: null }) - expect( - inviteSeatImpact({ - entitlement: unpriced, - members: 3, - pendingInvites: 0, - newInvites: 2, - now: 0 - }) - ).toEqual({ kind: 'adds-seats-unpriced', addedSeats: 2, freeSeats: 0 }) - }) -}) - describe('nextInvoiceEstimate', () => { it('bills the renewal seat count, not the period peak', () => { const estimate = nextInvoiceEstimate( diff --git a/src/renderer/src/components/billing/team/team-seat-math.ts b/src/renderer/src/components/billing/team/team-seat-math.ts index 928ac36cc41..c4465884cd7 100644 --- a/src/renderer/src/components/billing/team/team-seat-math.ts +++ b/src/renderer/src/components/billing/team/team-seat-math.ts @@ -1,7 +1,6 @@ -// Seat money shown on the Team page. Display estimates only: Stripe computes the real invoice. -// Mirrors the billing design: seats billed = the period's peak membership; a member who joins -// above the paid peak is charged now, prorated; removals only lower seats at renewal; pending -// invites cost nothing until accepted. +// Seat money shown in Plan & billing. Display estimates only: Stripe computes the real invoice. +// Mirrors the billing design: seats billed = the period's peak membership; removals only lower +// seats at renewal. import type { OrcaBillingEntitlement, OrcaBillingInterval @@ -33,80 +32,6 @@ export function isActivePlan(entitlement: OrcaBillingEntitlement | null): boolea ) } -/** One seat for the rest of the current period, rounded to the cent like Stripe's proration. */ -export function proratedSeatCents( - pricing: SeatPricing, - period: { start: number; end: number }, - now: number -): number { - const length = period.end - period.start - if (length <= 0) { - return pricing.perSeatPeriodCents - } - const remaining = Math.min(Math.max(period.end - now, 0), length) - return Math.round((pricing.perSeatPeriodCents * remaining) / length) -} - -export type InviteSeatImpact = - /** Billing didn't answer (disabled in this build, signed out or failed): no seat facts to show. */ - | { kind: 'unknown' } - | { kind: 'no-plan' } - /** Every new invite fits in seats already paid this period. */ - | { kind: 'covered'; freeSeats: number } - /** Seats will be added but the price or period isn't known (older billing service). */ - | { kind: 'adds-seats-unpriced'; addedSeats: number; freeSeats: number } - | { - kind: 'adds-seats' - /** Paid seats not taken by a member or a pending invite. */ - freeSeats: number - /** How many of the new invites would add a seat when accepted. */ - addedSeats: number - /** Seats already paid but unused that the first acceptances take for free. */ - coveredSeats: number - proratedCentsEach: number - perSeatPeriodCents: number - interval: OrcaBillingInterval - } - -/** - * What inviting `newInvites` people costs if they all accept now. Pending invites are assumed to - * accept first (conservative: never promises a free seat that an earlier invite will take). - */ -export function inviteSeatImpact(args: { - entitlement: OrcaBillingEntitlement | null - members: number - pendingInvites: number - newInvites: number - now: number -}): InviteSeatImpact { - const { entitlement } = args - if (!entitlement) { - return { kind: 'unknown' } - } - if (!isActivePlan(entitlement)) { - return { kind: 'no-plan' } - } - const pricing = seatPricing(entitlement) - const paidSeats = Math.max(entitlement.seats, 1) - const freeSeats = Math.max(0, paidSeats - args.members - args.pendingInvites) - const addedSeats = Math.max(0, args.newInvites - freeSeats) - if (addedSeats === 0) { - return { kind: 'covered', freeSeats } - } - if (!pricing || !entitlement.period) { - return { kind: 'adds-seats-unpriced', addedSeats, freeSeats } - } - return { - kind: 'adds-seats', - freeSeats, - addedSeats, - coveredSeats: Math.min(freeSeats, args.newInvites), - proratedCentsEach: proratedSeatCents(pricing, entitlement.period, args.now), - perSeatPeriodCents: pricing.perSeatPeriodCents, - interval: pricing.interval - } -} - export type NextInvoiceEstimate = { seats: number amountCents: number diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index c8cdcaf698d..689c39c5ed9 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -242,18 +242,10 @@ "blockedWorkspaces_one": "{{count}} cloud workspace still exists. Delete it first.", "blockedWorkspaces_other": "{{count}} cloud workspaces still exist. Delete them first." }, - "inviteSeatAddsMonth_one": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seat ({{price}}/mo, prorated) will be added.", - "inviteSeatAddsMonth_other": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seats ({{price}}/mo, prorated) will be added.", - "inviteSeatAddsUnpriced_one": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seat will be added, prorated.", - "inviteSeatAddsUnpriced_other": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seats will be added, prorated.", - "inviteSeatAddsYear_one": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seat ({{price}}/yr, prorated) will be added.", - "inviteSeatAddsYear_other": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seats ({{price}}/yr, prorated) will be added.", "invitedCount_one": "{{count}} invited", "invitedCount_other": "{{count}} invited", "memberCount_one": "{{count}} member", "memberCount_other": "{{count}} members", - "openSeatsClause_one": "You have {{count}} open seat", - "openSeatsClause_other": "You have {{count}} open seats", "seatCount_one": "{{count}} seat", "seatCount_other": "{{count}} seats", "sendInvites_one": "Send {{count}} invite", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 8ef21b2d308..4133e13111b 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -21254,7 +21254,6 @@ "dismiss": "Dismiss", "enterEmail": "Enter a teammate’s email", "inviteLabel": "Invite teammates", - "inviteNoPlan": "Invites are free. Seats are billed once your team picks a plan.", "invitePlaceholder2": "alex@company.com, sam@company.com", "inviteSentBody": "They join, and take a seat, when they accept.", "inviteSentMany": "{{value0}} invites sent", @@ -21310,7 +21309,6 @@ "createdNotSwitched": "{{value0}} was created, but Orca couldn’t switch to it.", "invitedCount_one": "{{count}} invited", "invitedCount_other": "{{count}} invited", - "invitePaymentFailed2": "New seats are charged once the failed payment is fixed.", "memberCount_one": "{{count}} member", "memberCount_other": "{{count}} members", "seatCount_one": "{{count}} seat", @@ -21351,22 +21349,10 @@ "deletedToast2": "{{value0}} was deleted" }, "leaveLastOwnerOrDelete": "You’re the only owner. Make someone else an owner first, or delete the team.", - "planBillingLink": "Plan & billing", "perSeat": "Per seat", "perSeatMonthValue": "{{value0}}/mo", "seatRulesShort": "New members above your paid seats are charged now, prorated. Removed seats stay paid until renewal.", - "openSeatsNone": "You have no open seats", - "openSeatsClause_one": "You have {{count}} open seat", - "openSeatsClause_other": "You have {{count}} open seats", - "inviteSeatUnknown": "Each invite uses a seat once accepted.", - "inviteSeatOpen": "Each invite uses a seat once accepted. {{openSeats}}.", - "inviteSeatCovered": "Each invite uses a seat once accepted. {{openSeats}}, so no seats will be added.", - "inviteSeatAddsUnpriced_one": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seat will be added, prorated.", - "inviteSeatAddsUnpriced_other": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seats will be added, prorated.", - "inviteSeatAddsYear_one": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seat ({{price}}/yr, prorated) will be added.", - "inviteSeatAddsYear_other": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seats ({{price}}/yr, prorated) will be added.", - "inviteSeatAddsMonth_one": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seat ({{price}}/mo, prorated) will be added.", - "inviteSeatAddsMonth_other": "Each invite uses a seat once accepted. {{openSeats}}, so {{count}} more seats ({{price}}/mo, prorated) will be added." + "inviteSeatRule": "Each invite uses a seat once accepted." }, "manageBilling": "Manage billing", "comparePlans": "Compare plans", From bd8e7002cbf706ccb16e92c59bc9b645352bee25 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 21:31:26 -0800 Subject: [PATCH 25/28] fix(cloud-create): GitHub-only creates get a sidebar row and a real Cancel (GH-CREATE-NO-ROW, GH-CREATE-CANCEL) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NO-ROW: a create with no project here yet (GitHub-only Orca Cloud) now has its pending row atop the list when grouped by project too (it got a blank 'repo:' section before). While it opens, openCloudWorkspace reports the server it pairs to (onHost); the sidebar hides that server's rows until the hand-off removes the pending row, both in one store update, so the workspace never shows twice. CANCEL: createSandboxWithProgress (owned and GitHub-only creates) deletes what a cancel leaves: cancelled in flight, it replays the create by its Idempotency-Key and deletes the sandbox the control plane hands back (reclaimCancelledCreate, retrying while the first is still in progress); cancelled just as it answered, it deletes it. A cancelled clone already deleted itself. The GitHub runner deletes the sandbox when Cancel lands before or during Open workspace (which also drops this computer's pairing), and cancel's 'Deleting the sandbox…' waits for it. Copy link moves to cloud-workspace-share-link.ts (re-exported) to keep open-cloud-workspace.ts within max-lines. --- .../cloud-create-from-github.ts | 5 - .../hosted-sandbox-create-reclaim.test.ts | 105 ++++++++++++++++ .../hosted-sandbox-create-reclaim.ts | 64 ++++++++++ .../hosted-sandbox/hosted-sandbox-driver.ts | 38 ++++-- .../cloud-workspace-share-link.ts | 68 ++++++++++ .../cloud-workspaces/open-cloud-workspace.ts | 105 +++++----------- .../grouping/projectless-pending-row.test.ts | 51 ++++++++ .../rows/PendingWorktreeRowGitHub.fixture.tsx | 62 ++++++++++ ...cloud-workspace-from-github.cancel.test.ts | 117 ++++++++++++++++++ .../start-cloud-workspace-from-github.ts | 41 +++++- .../use-sidebar-hidden-checkouts.test.ts | 23 ++++ .../use-sidebar-hidden-checkouts.ts | 16 ++- .../creation/pending-worktree-creation.ts | 2 + .../create/pending-worktree-creation.ts | 8 +- .../worktrees/worktree-slice-contract.ts | 1 + src/shared/sidebar-list/sidebar-row-plan.ts | 6 +- src/shared/sidebar-list/worktree-grouping.ts | 3 +- 17 files changed, 608 insertions(+), 107 deletions(-) create mode 100644 src/main/hosted-sandbox/hosted-sandbox-create-reclaim.test.ts create mode 100644 src/main/hosted-sandbox/hosted-sandbox-create-reclaim.ts create mode 100644 src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.ts create mode 100644 src/renderer/src/components/sidebar/worktree-list/grouping/projectless-pending-row.test.ts create mode 100644 src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRowGitHub.fixture.tsx create mode 100644 src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.cancel.test.ts diff --git a/src/main/hosted-sandbox/cloud-create-from-github.ts b/src/main/hosted-sandbox/cloud-create-from-github.ts index 1809caa686c..23dca09b989 100644 --- a/src/main/hosted-sandbox/cloud-create-from-github.ts +++ b/src/main/hosted-sandbox/cloud-create-from-github.ts @@ -73,11 +73,6 @@ export async function createCloudWorkspaceFromGitHub( onProgress: (progress) => io.onLog?.(hostedProgressLine(progress)) } ) - if (io.signal?.aborted) { - // Cancelled just as it answered: nothing will open it, so it must not keep running (and billing). - await client.destroy(ready.sandbox.id).catch(() => undefined) - return { ok: false, code: 'failed', message: 'Cancelled.' } - } return { ok: true, value: { sandboxId: ready.sandbox.id } } } catch (error) { const result = hostedCreateFailure(error) diff --git a/src/main/hosted-sandbox/hosted-sandbox-create-reclaim.test.ts b/src/main/hosted-sandbox/hosted-sandbox-create-reclaim.test.ts new file mode 100644 index 00000000000..b5686f8a2ee --- /dev/null +++ b/src/main/hosted-sandbox/hosted-sandbox-create-reclaim.test.ts @@ -0,0 +1,105 @@ +// GH-CREATE-CANCEL: a create cancelled in flight never leaves a sandbox running, for the owned +// create and the GitHub-only create alike (both use createSandboxWithProgress). +import { describe, expect, it, vi } from 'vitest' +import { EnvironmentProviderError } from '../environment-providers/environment-provider-driver' +import { HostedEntitlementDeniedError } from './hosted-environment-provider' +import { reclaimCancelledCreate } from './hosted-sandbox-create-reclaim' +import { createSandboxWithProgress } from './hosted-sandbox-driver' + +const READY = { + sandbox: { + id: 'sbx_1', + workspaceId: 'web-1', + status: 'running' as const, + machineSize: 'standard' as const, + region: 'iad1', + session: null, + createdAt: 1 + }, + connection: { type: 'orca-server' as const, pairingCode: 'code', projectRoot: '/work' } +} +const BODY = { workspaceId: 'web-1', machineSize: 'standard' as const } +const quiet = { waitMs: 0, log: () => {} } + +function client() { + return { + create: vi.fn(async () => READY), + bootPlan: vi.fn(async () => 'clone' as const), + cloneStatus: vi.fn(async () => ({ state: 'done' as const })), + destroy: vi.fn(async (id: string) => ({ id, status: 'destroyed' as const })) + } +} + +describe('reclaimCancelledCreate', () => { + it('replays the create by its key and deletes the sandbox it gets back', async () => { + const api = client() + expect(await reclaimCancelledCreate(api, BODY, 'create:k1', quiet)).toBe(true) + expect(api.create).toHaveBeenCalledWith(BODY, undefined, 'create:k1') + expect(api.destroy).toHaveBeenCalledWith('sbx_1') + }) + + it('waits while the first create is still in progress (409), then deletes', async () => { + const api = client() + api.create + .mockRejectedValueOnce(new EnvironmentProviderError('conflict', 'idempotency_in_progress')) + .mockRejectedValueOnce(new EnvironmentProviderError('unavailable', 'try later')) + expect(await reclaimCancelledCreate(api, BODY, 'create:k1', quiet)).toBe(true) + expect(api.create).toHaveBeenCalledTimes(3) + expect(api.destroy).toHaveBeenCalledWith('sbx_1') + }) + + it('a refused replay means the cancelled create made nothing either', async () => { + const api = client() + api.create.mockRejectedValueOnce(new HostedEntitlementDeniedError('denied', 'no_subscription')) + expect(await reclaimCancelledCreate(api, BODY, 'create:k1', quiet)).toBe(true) + expect(api.destroy).not.toHaveBeenCalled() + }) + + it('gives up (false) when it can never tell', async () => { + const api = client() + api.create.mockRejectedValue(new EnvironmentProviderError('unavailable', 'down')) + expect(await reclaimCancelledCreate(api, BODY, 'create:k1', { ...quiet, attempts: 3 })).toBe( + false + ) + }) +}) + +describe('createSandboxWithProgress cancel', () => { + const spec = { workspaceId: 'web-1', machineSize: 'standard', idempotencyKey: 'create:k1' } + + it('cancelled while the create was in flight: reclaims by key, then reports the cancel', async () => { + const api = client() + const controller = new AbortController() + api.create.mockImplementationOnce(async () => { + controller.abort() + throw new EnvironmentProviderError('aborted', 'Cancelled.') + }) + await expect( + createSandboxWithProgress(api, spec, { signal: controller.signal }) + ).rejects.toMatchObject({ code: 'aborted' }) + // The replay (no signal, same key) found the sandbox and deleted it. + expect(api.create).toHaveBeenLastCalledWith(expect.anything(), undefined, 'create:k1') + expect(api.destroy).toHaveBeenCalledWith('sbx_1') + }) + + it('cancelled just as the create answered: deletes the sandbox and reports the cancel', async () => { + const api = client() + const controller = new AbortController() + api.create.mockImplementationOnce(async () => { + controller.abort() + return READY + }) + await expect( + createSandboxWithProgress(api, spec, { signal: controller.signal }) + ).rejects.toMatchObject({ code: 'aborted' }) + expect(api.destroy).toHaveBeenCalledWith('sbx_1') + expect(api.create).toHaveBeenCalledTimes(1) + }) + + it('not cancelled: no replay, no delete', async () => { + const api = client() + await expect(createSandboxWithProgress(api, spec, {})).resolves.toBe(READY) + expect(api.create).toHaveBeenCalledTimes(1) + expect(api.destroy).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/hosted-sandbox/hosted-sandbox-create-reclaim.ts b/src/main/hosted-sandbox/hosted-sandbox-create-reclaim.ts new file mode 100644 index 00000000000..343360ff400 --- /dev/null +++ b/src/main/hosted-sandbox/hosted-sandbox-create-reclaim.ts @@ -0,0 +1,64 @@ +// A create cancelled while its request was in flight may still have made a sandbox on the control +// plane, and a sandbox bills (GH-CREATE-CANCEL). The control plane keys creates by Idempotency-Key +// and body: sending the same create again hands back the sandbox the first one made (or makes one, if +// the first never arrived), and that sandbox is deleted. Shared by the owned create (the recipe) and +// the GitHub-only create, which both go through createSandboxWithProgress. +import { isEnvironmentProviderError } from '../environment-providers/environment-provider-driver' +import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client' + +type CreateBody = Parameters[0] + +const RECLAIM_ATTEMPTS = 8 +const RECLAIM_WAIT_MS = 5_000 + +/** The first create may still be running (409 in progress) or the service briefly unreachable. */ +function worthRetrying(error: unknown): boolean { + return ( + isEnvironmentProviderError(error, 'conflict') || + isEnvironmentProviderError(error, 'unavailable') || + isEnvironmentProviderError(error, 'timeout') || + !isEnvironmentProviderError(error) + ) +} + +/** + * Deletes whatever the cancelled create made. True once it is gone (or the control plane refused + * the create, so nothing was made); false when it still couldn't tell after every attempt. + */ +export async function reclaimCancelledCreate( + client: Pick, + body: CreateBody, + idempotencyKey: string, + { + attempts = RECLAIM_ATTEMPTS, + waitMs = RECLAIM_WAIT_MS, + log = (message: string) => console.warn(message) + }: { attempts?: number; waitMs?: number; log?: (message: string) => void } = {} +): Promise { + for (let attempt = 1; attempt <= attempts; attempt += 1) { + let sandboxId: string + try { + // No signal: this request is the cleanup and must not be cancelled with the create. + sandboxId = (await client.create(body, undefined, idempotencyKey)).sandbox.id + } catch (error) { + if (!worthRetrying(error)) { + // Refused (billing, sign-in, bad request): the cancelled create made nothing either. + return true + } + log( + `[orca-cloud] cancelled create: replay ${attempt}/${attempts} failed (${isEnvironmentProviderError(error) ? error.code : 'error'})` + ) + await new Promise((resolve) => setTimeout(resolve, waitMs)) + continue + } + try { + await client.destroy(sandboxId) + log(`[orca-cloud] cancelled create: deleted sandbox ${sandboxId}`) + return true + } catch { + await new Promise((resolve) => setTimeout(resolve, waitMs)) + } + } + log('[orca-cloud] cancelled create: could not confirm the sandbox was deleted') + return false +} diff --git a/src/main/hosted-sandbox/hosted-sandbox-driver.ts b/src/main/hosted-sandbox/hosted-sandbox-driver.ts index cb0ccc76f5c..088f92f5b89 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-driver.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-driver.ts @@ -25,6 +25,7 @@ import type { } from './hosted-environment-provider' import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client' import { takeSuspendReason } from './idle-sleep-requests' +import { reclaimCancelledCreate } from './hosted-sandbox-create-reclaim' export const HOSTED_SANDBOX_DRIVER_ID = 'orca-cloud' @@ -144,21 +145,34 @@ export async function createSandboxWithProgress( ) .catch(() => undefined) } - const ready = await client.create( - { - workspaceId: spec.workspaceId, - machineSize, - // Named rows: Home shows the workspace's name, never an untitled sandbox (PC-8). - ...(spec.workspaceName?.trim() ? { title: spec.workspaceName.trim().slice(0, 120) } : {}), - ...(spec.region ? { region: spec.region } : {}), - ...(spec.repo ? { repo: spec.repo } : {}) - }, - ctx?.signal, - spec.idempotencyKey - ) + const body = { + workspaceId: spec.workspaceId, + machineSize, + // Named rows: Home shows the workspace's name, never an untitled sandbox (PC-8). + ...(spec.workspaceName?.trim() ? { title: spec.workspaceName.trim().slice(0, 120) } : {}), + ...(spec.region ? { region: spec.region } : {}), + ...(spec.repo ? { repo: spec.repo } : {}) + } + let ready: HostedSandboxReadyResponse + try { + ready = await client.create(body, ctx?.signal, spec.idempotencyKey) + } catch (error) { + // GH-CREATE-CANCEL: cancelled in flight, the control plane may still have made it: find it by + // its key and delete it before reporting the cancel. + if (ctx?.signal?.aborted && spec.idempotencyKey) { + await reclaimCancelledCreate(client, body, spec.idempotencyKey) + } + throw error + } if (ready.clone) { + // A cancelled, failed or stalled clone deletes the sandbox itself. await waitForClone(client, ready.sandbox.id, ctx, { mode: ready.clone.mode ?? 'clone' }) } + if (ctx?.signal?.aborted) { + // Cancelled just as it answered: nothing will use it, so it must not keep running (and billing). + await client.destroy(ready.sandbox.id).catch(() => undefined) + throw new EnvironmentProviderError('aborted', 'Cancelled.') + } ctx?.onProgress?.({ phase: 'connecting' }) return ready } diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.ts new file mode 100644 index 00000000000..d64be4157e1 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspace-share-link.ts @@ -0,0 +1,68 @@ +// A cloud workspace's share link: the org slug + W-number link when known, else the sandbox-id form. +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { cloudWorkspaceShareLink } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' +import { cloudWorkspaceIdentity, rememberCloudWorkspaces } from './cloud-workspace-identity' + +// How long Copy link waits on the control plane before settling for the sandbox-id link. +const LINK_LOOKUP_MS = 3_000 + +async function lookUpLink(id: string): Promise { + let timer: ReturnType | undefined + try { + const fetched = await Promise.race([ + window.api.cloudWorkspaces.get(id), + new Promise((resolve) => { + timer = setTimeout(() => resolve(null), LINK_LOOKUP_MS) + }) + ]) + if (!fetched?.ok) { + return null + } + rememberCloudWorkspaces([fetched.value]) + return fetched.value.link ?? null + } catch { + return null + } finally { + clearTimeout(timer) + } +} + +/** + * The org slug + W-number link when the control plane gave one, else the sandbox id form, which + * opens for anyone with access. Never rejects: a device that didn't create the workspace (paired, + * offline, signed out) still gets a working link. + */ +export async function shareLinkFor(id: string, chatId?: string | null): Promise { + const link = cloudWorkspaceIdentity(id)?.link ?? (await lookUpLink(id)) + return cloudWorkspaceShareLink({ id, ...(link ? { link } : {}) }, chatId) +} + +export async function copyCloudWorkspaceLink( + id: string, + chatId?: string | null, + options: { quiet?: boolean } = {} +): Promise { + const link = await shareLinkFor(id, chatId) + try { + // Why: main-process clipboard, like every other renderer copy. navigator.clipboard needs a + // focused document with live user activation; after the link lookup (or from the menu or a + // shortcut) Electron rejects it with "Document is not focused". + await window.api.ui.writeClipboardText(link) + } catch (error) { + console.warn('[cloud-workspaces] copy link failed', error) + toast.error( + translate('auto.components.cloudWorkspaces.copyFailed', "Couldn't copy the link. Try again.") + ) + return false + } + if (options.quiet) { + return true + } + toast.success( + chatId + ? translate('auto.components.cloudWorkspaces.chatLinkCopied', 'Chat link copied') + : translate('auto.components.cloudWorkspaces.workspaceLinkCopied', 'Workspace link copied') + ) + return true +} diff --git a/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts b/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts index e2b376a817e..0ae44d82588 100644 --- a/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts +++ b/src/renderer/src/components/cloud-workspaces/open-cloud-workspace.ts @@ -11,8 +11,6 @@ import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-a import { refreshRuntimeProjectWorktreesAndLineage } from '@/hooks/runtime-project-refresh-scheduler' import { RuntimeRpcCallError, unwrapRuntimeRpcResult } from '@/runtime/rpc/calls/runtime-rpc-result' import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' -import { cloudWorkspaceShareLink } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire' -import { cloudWorkspaceIdentity, rememberCloudWorkspaces } from './cloud-workspace-identity' import { getWorktreeExecutionHostId, toRuntimeExecutionHostId @@ -66,7 +64,20 @@ function isPairingRejected(error: unknown): boolean { return error instanceof Error && /\b(unauthori[sz]ed|device_revoked)\b/i.test(error.message) } -async function connectAndReveal(environmentId: string, name: string): Promise { +export type OpenCloudWorkspaceOptions = { + /** + * The server this open connects to, before any of its rows load. A GitHub-only create's sheet + * hides that server's rows until it hands off to them, so its pending row never doubles up. + */ + onHost?: (hostId: string) => void +} + +async function connectAndReveal( + environmentId: string, + name: string, + options: OpenCloudWorkspaceOptions = {} +): Promise { + options.onHost?.(toRuntimeExecutionHostId(environmentId)) const environments = await window.api.runtimeEnvironments.list() useAppStore.getState().setRuntimeEnvironments(environments) const environment = environments.find((e) => e.id === environmentId) @@ -147,7 +158,11 @@ async function wakeIfAsleep(workspace: CloudWorkspace): Promise { +async function pairAndReveal( + workspace: CloudWorkspace, + name: string, + options: OpenCloudWorkspaceOptions +): Promise { const api = window.api.cloudWorkspaces const binding = (await api.environmentBindings())[workspace.id] if (binding) { @@ -161,7 +176,7 @@ async function pairAndReveal(workspace: CloudWorkspace, name: string): Promise undefined) - return await connectAndReveal(added.environment.id, name) + return await connectAndReveal(added.environment.id, name, options) } -async function openOnce(workspace: CloudWorkspace): Promise { +async function openOnce( + workspace: CloudWorkspace, + options: OpenCloudWorkspaceOptions +): Promise { const name = cloudWorkspaceTitle(workspace) try { if (workspace.access === 'owner') { @@ -244,7 +262,7 @@ async function openOnce(workspace: CloudWorkspace): Promise { ) } } - return await pairAndReveal(workspace, name) + return await pairAndReveal(workspace, name, options) } catch (error) { // Raw transport/RPC messages are not user copy; keep them for diagnostics only. console.warn('[cloud-workspaces] open failed', error) @@ -262,75 +280,18 @@ async function openOnce(workspace: CloudWorkspace): Promise { // instead of minting parallel grants. const opening = new Map>() -export function openCloudWorkspace(workspace: CloudWorkspace): Promise { +export function openCloudWorkspace( + workspace: CloudWorkspace, + options: OpenCloudWorkspaceOptions = {} +): Promise { const existing = opening.get(workspace.id) if (existing) { return existing } - const attempt = openOnce(workspace).finally(() => opening.delete(workspace.id)) + const attempt = openOnce(workspace, options).finally(() => opening.delete(workspace.id)) opening.set(workspace.id, attempt) return attempt } -// How long Copy link waits on the control plane before settling for the sandbox-id link. -const LINK_LOOKUP_MS = 3_000 - -async function lookUpLink(id: string): Promise { - let timer: ReturnType | undefined - try { - const fetched = await Promise.race([ - window.api.cloudWorkspaces.get(id), - new Promise((resolve) => { - timer = setTimeout(() => resolve(null), LINK_LOOKUP_MS) - }) - ]) - if (!fetched?.ok) { - return null - } - rememberCloudWorkspaces([fetched.value]) - return fetched.value.link ?? null - } catch { - return null - } finally { - clearTimeout(timer) - } -} - -/** - * The org slug + W-number link when the control plane gave one, else the sandbox id form, which - * opens for anyone with access. Never rejects: a device that didn't create the workspace (paired, - * offline, signed out) still gets a working link. - */ -export async function shareLinkFor(id: string, chatId?: string | null): Promise { - const link = cloudWorkspaceIdentity(id)?.link ?? (await lookUpLink(id)) - return cloudWorkspaceShareLink({ id, ...(link ? { link } : {}) }, chatId) -} - -export async function copyCloudWorkspaceLink( - id: string, - chatId?: string | null, - options: { quiet?: boolean } = {} -): Promise { - const link = await shareLinkFor(id, chatId) - try { - // Why: main-process clipboard, like every other renderer copy. navigator.clipboard needs a - // focused document with live user activation; after the link lookup (or from the menu or a - // shortcut) Electron rejects it with "Document is not focused". - await window.api.ui.writeClipboardText(link) - } catch (error) { - console.warn('[cloud-workspaces] copy link failed', error) - toast.error( - translate('auto.components.cloudWorkspaces.copyFailed', "Couldn't copy the link. Try again.") - ) - return false - } - if (options.quiet) { - return true - } - toast.success( - chatId - ? translate('auto.components.cloudWorkspaces.chatLinkCopied', 'Chat link copied') - : translate('auto.components.cloudWorkspaces.workspaceLinkCopied', 'Workspace link copied') - ) - return true -} +// Copy link lives beside it; re-exported so callers keep one import. +export { copyCloudWorkspaceLink, shareLinkFor } from './cloud-workspace-share-link' diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/projectless-pending-row.test.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/projectless-pending-row.test.ts new file mode 100644 index 00000000000..b2bab1da297 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/grouping/projectless-pending-row.test.ts @@ -0,0 +1,51 @@ +// GH-CREATE-NO-ROW: a create with no project here yet (a GitHub-only Orca Cloud create) has a +// pending row atop the list when grouped by project, as in every other grouping; a create with a +// project still sits atop its own project. +import { describe, expect, it } from 'vitest' +import { repo, worktree } from './worktree-list-groups-test-fixtures' +import { buildRows } from './build-rows.test-fixture' + +function rows(groupBy: 'repo' | 'none', pending: { creationId: string; repoId: string }[]) { + return buildRows( + groupBy, + [{ ...worktree, lastActivityAt: 1 }], + new Map([[repo.id, repo]]), + null, + new Set(), + undefined, + undefined, + 'manual', + {}, + undefined, + false, + undefined, + [], + new Set(), + new Map(), + new Map(), + pending + ) +} + +describe('pending row for a create with no project yet', () => { + it('by project: sits atop the list, before the first project header', () => { + const list = rows('repo', [{ creationId: 'gh-1', repoId: '' }]) + expect(list[0]).toMatchObject({ type: 'pending-creation', creationId: 'gh-1' }) + expect(list.filter((row) => row.type === 'pending-creation')).toHaveLength(1) + // No blank project header for it (it used to get one, keyed "repo:"). + expect(list.filter((row) => row.type === 'header')).toHaveLength(1) + }) + + it('by project: a create with a project still sits atop that project only', () => { + const list = rows('repo', [{ creationId: 'local-1', repoId: repo.id }]) + const header = list.findIndex((row) => row.type === 'header') + expect(header).toBeGreaterThanOrEqual(0) + expect(list.findIndex((row) => row.type === 'pending-creation')).toBeGreaterThan(header) + expect(list.filter((row) => row.type === 'pending-creation')).toHaveLength(1) + }) + + it('ungrouped: unchanged, every pending row on top', () => { + const list = rows('none', [{ creationId: 'gh-1', repoId: '' }]) + expect(list[0]).toMatchObject({ type: 'pending-creation', creationId: 'gh-1' }) + }) +}) diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRowGitHub.fixture.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRowGitHub.fixture.tsx new file mode 100644 index 00000000000..38ef8a2cc50 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRowGitHub.fixture.tsx @@ -0,0 +1,62 @@ +// GH-CREATE-NO-ROW: a GitHub-only Orca Cloud create has a sidebar row while it builds, atop the list +// (it has no project here yet), with the cloud glyph from the start; the paired workspace's rows +// replace it on hand-off. +import { getDefaultSettings } from '../../../../../../shared/constants' +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import { githubCreateRequest } from '@/lib/orca-cloud/start-cloud-workspace-from-github' +import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' +import { PendingWorktreeRow } from './PendingWorktreeRow' + +const T0 = 1_700_000_000_000 + +function creation( + creationId: string, + patch: Partial = {} +): PendingWorktreeCreation { + return { + creationId, + phase: 'provisioning-vm', + status: 'creating', + startedAt: T0, + indeterminate: false, + loaderVisible: true, + provisioningLog: '[orca-cloud] provisioning\n[orca-cloud] plan-clone', + provisioningLogStamps: [T0, T0 + 400], + request: githubCreateRequest({ + repoUrl: 'https://github.com/nwparker/orca-sandbox-push-test', + fullName: 'nwparker/orca-sandbox-push-test', + prompt: 'Add a push test', + agent: 'claude', + composerRepoId: 'repo' + }), + ...patch + } +} + +const rows = { + building: creation('building'), + opening: creation('opening', { phase: 'creating' }), + failed: creation('failed', { + status: 'error', + error: 'Orca Cloud workspaces need a plan with cloud hours.', + errorCode: 'cloudPlanRequired', + provisioningLog: '[orca-cloud] provisioning\nOrca Cloud: included_hours_exhausted' + }) +} + +/** The sidebar's top while three GitHub-only creates are in flight: building, opening, refused. */ +export const githubOnlyPendingRows = defineFixture({ + width: 320, + store: { + settings: getDefaultSettings('/home/fixture'), + pendingWorktreeCreations: rows, + activePendingCreationId: 'building' + }, + render: () => ( +
+ {Object.keys(rows).map((creationId) => ( + + ))} +
+ ) +}) diff --git a/src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.cancel.test.ts b/src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.cancel.test.ts new file mode 100644 index 00000000000..216791fa2c3 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.cancel.test.ts @@ -0,0 +1,117 @@ +// @vitest-environment happy-dom +// GH-CREATE-CANCEL and GH-CREATE-NO-ROW for a GitHub-only Orca Cloud create: Cancel at any step +// leaves no workspace (the sandbox is deleted, which drops the pairing too), and a create that +// opens hands its pending row off to the paired server's rows, which stay hidden until then. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' + +type OpenOptions = { onHost?: (hostId: string) => void } +type OpenOutcome = { ok: true; worktreeId: string | null; hostId?: string } + +const mocks = vi.hoisted(() => ({ + open: vi.fn<(workspace: unknown, options?: OpenOptions) => Promise>(), + launch: vi.fn() +})) + +vi.mock('@/components/cloud-workspaces/open-cloud-workspace', () => ({ + openCloudWorkspace: mocks.open +})) +vi.mock('@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab', () => ({ + launchAgentInNewTabWithOutcome: mocks.launch +})) + +import { startCloudWorkspaceFromGitHub } from './start-cloud-workspace-from-github' +import { resetGitHubCreateKeysForTest } from './github-cloud-create-key' + +const createFromGitHub = vi.fn<(args: unknown) => Promise>() +const destroy = vi.fn(async () => ({ ok: true, value: undefined })) + +beforeEach(() => { + resetGitHubCreateKeysForTest() + useAppStore.setState({ pendingWorktreeCreations: {}, activePendingCreationId: null }) + createFromGitHub.mockResolvedValue({ ok: true, value: { sandboxId: 'sbx_1' } }) + mocks.open.mockResolvedValue({ ok: true, worktreeId: null }) + Object.assign(window, { + api: { + ...window.api, + orcaCloudWorkspace: { createFromGitHub }, + cloudWorkspaces: { + get: vi.fn(async (id: string) => ({ ok: true, value: { id } })), + destroy, + localWorkspaces: vi.fn(async () => []), + environmentBindings: vi.fn(async () => ({})) + }, + ephemeralVm: { + onProvisionEvent: () => () => {}, + cancelProvision: vi.fn(async () => ({ cancelled: true })), + // Cancel's cleanup looks for this create's runtime records; a GitHub-only create has none. + listRuntimes: vi.fn(async () => []) + } + } + }) +}) + +afterEach(() => { + vi.clearAllMocks() +}) + +const REQUEST = { + repoUrl: 'https://github.com/acme/web', + fullName: 'acme/web', + prompt: '', + agent: null, + composerRepoId: 'repo-1' +} + +const creationId = (): string => + Object.keys(useAppStore.getState().pendingWorktreeCreations)[0] ?? '' +const cancel = (): void => useAppStore.getState().removePendingWorktreeCreation(creationId()) + +describe('Cancel leaves no workspace (GH-CREATE-CANCEL)', () => { + it('cancelled after the sandbox started, before it opened: deleted, never opened', async () => { + createFromGitHub.mockImplementationOnce(async () => { + cancel() + return { ok: true, value: { sandboxId: 'sbx_1' } } + }) + expect(await startCloudWorkspaceFromGitHub(REQUEST)).toBe(false) + expect(mocks.open).not.toHaveBeenCalled() + expect(destroy).toHaveBeenCalledWith('sbx_1') + }) + + it('cancelled while it opened: the sandbox is deleted (its pairing and row go with it)', async () => { + mocks.open.mockImplementationOnce(async (_workspace, options) => { + options?.onHost?.('runtime:p') + cancel() + return { ok: true, worktreeId: 'w1', hostId: 'runtime:p' } + }) + expect(await startCloudWorkspaceFromGitHub(REQUEST)).toBe(false) + expect(destroy).toHaveBeenCalledWith('sbx_1') + expect(useAppStore.getState().pendingWorktreeCreations).toEqual({}) + }) + + it('cancelled while the create was in flight: main reclaims it; nothing opens here', async () => { + createFromGitHub.mockImplementationOnce(async () => { + cancel() + return { ok: false, code: 'failed', message: 'Cancelled.' } + }) + expect(await startCloudWorkspaceFromGitHub(REQUEST)).toBe(false) + expect(window.api.ephemeralVm.cancelProvision).toHaveBeenCalled() + expect(mocks.open).not.toHaveBeenCalled() + }) +}) + +describe('pending row hand-off (GH-CREATE-NO-ROW)', () => { + it('records the paired server while opening, and the hand-off drops the pending row', async () => { + let pairingHostIdDuringOpen: string | undefined + mocks.open.mockImplementationOnce(async (_workspace, options) => { + options?.onHost?.('runtime:p') + pairingHostIdDuringOpen = + useAppStore.getState().pendingWorktreeCreations[creationId()]?.pairingHostId + return { ok: true, worktreeId: null } + }) + expect(await startCloudWorkspaceFromGitHub(REQUEST)).toBe(true) + expect(pairingHostIdDuringOpen).toBe('runtime:p') + expect(useAppStore.getState().pendingWorktreeCreations).toEqual({}) + expect(destroy).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.ts b/src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.ts index 982b05ebc14..dd3fdd7000e 100644 --- a/src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.ts +++ b/src/renderer/src/lib/orca-cloud/start-cloud-workspace-from-github.ts @@ -9,6 +9,7 @@ import { useAppStore } from '@/store' import { translate } from '@/i18n/i18n' import { openCloudWorkspace } from '@/components/cloud-workspaces/open-cloud-workspace' +import { refreshCloudWorktreeBindings } from '@/components/cloud-workspaces/cloud-workspace-identity' import { createNonSecureContextUuid } from '../../../../shared/non-secure-context-uuid' import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id' @@ -87,7 +88,12 @@ export function startCloudWorkspaceFromGitHub(request: StartFromGitHubRequest): }) store.setActiveView('terminal') store.setSidebarOpen(true) - return runGitHubCloudCreate(creationId) + return runTracked(creationId) +} + +/** Cancel's "Deleting the sandbox…" waits for every step that may still own a sandbox. */ +function runTracked(creationId: string): Promise { + return trackOrcaCloudCreateStep(creationId, runGitHubCloudCreate(creationId)) } /** The sheet's Retry (and the plans page's retry after checkout) for a GitHub-only create. */ @@ -114,7 +120,7 @@ export function retryGitHubCloudCreate(creationId: string): void { }) store.setActivePendingWorktreeCreation(creationId) store.setActiveView('terminal') - void runGitHubCloudCreate(creationId) + void runTracked(creationId) } function current(creationId: string) { @@ -186,13 +192,27 @@ async function runGitHubCloudCreate(creationId: string): Promise { return false } if (!current(creationId)) { - // Cancelled while it started: main stopped the create and deleted what it had made. - startedSandboxes.delete(creationId) + // GH-CREATE-CANCEL: cancelled after the sandbox started but before it opened. + await discardSandbox(creationId, sandboxId) return false } useAppStore.getState().updatePendingWorktreeCreation(creationId, { phase: 'creating' }) const workspace = await window.api.cloudWorkspaces.get(sandboxId).catch(() => null) - const opened = workspace?.ok ? await openCloudWorkspace(workspace.value) : null + const opened = workspace?.ok + ? await openCloudWorkspace(workspace.value, { + // GH-CREATE-NO-ROW: that server's rows wait behind the pending row until the hand-off. + onHost: (hostId) => + useAppStore + .getState() + .updatePendingWorktreeCreation(creationId, { pairingHostId: hostId }) + }) + : null + if (!current(creationId)) { + // GH-CREATE-CANCEL: cancelled while it opened. Opening can't be stopped half way, so the + // sandbox is deleted, which also drops this computer's pairing and its row. + await discardSandbox(creationId, sandboxId) + return false + } if (!opened?.ok) { // The sandbox exists from here on: Retry opens it and never creates it again. return fail( @@ -219,3 +239,14 @@ async function runGitHubCloudCreate(creationId: string): Promise { }) return true } + +/** A cancelled create's sandbox: deleted, so nothing keeps running (or billing) behind the cancel. */ +async function discardSandbox(creationId: string, sandboxId: string): Promise { + startedSandboxes.delete(creationId) + forgetGitHubCreateKey(creationId) + const result = await window.api.cloudWorkspaces.destroy(sandboxId).catch(() => null) + if (!result?.ok) { + console.warn('[orca-cloud] cancelled GitHub create: could not delete sandbox', sandboxId) + } + void refreshCloudWorktreeBindings().catch(() => undefined) +} diff --git a/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.test.ts b/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.test.ts index 3e296c962c2..39cc60b4eff 100644 --- a/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.test.ts +++ b/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.test.ts @@ -125,3 +125,26 @@ describe('paired workspaces scoped by account (PAIRED-ACCOUNT-FILTER)', () => { expect(hostsFor('team-two', paired()).hiddenHostIds.has('runtime:gh')).toBe(false) }) }) + +describe('GH-CREATE-NO-ROW hand-off', () => { + it('hides the server a GitHub-only create is pairing to until its pending row hands off', () => { + const pairing = (pairingHostId?: string) => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the selector reads only these fields. + ({ + runtimeEnvironments: [{ id: 'p', name: 'web (cloud)', orcaCloudPaired: true }], + orcaProfileAuthStatus: { cloud: { userId: 'u1' } }, + pendingWorktreeCreations: { + gh: { + creationId: 'gh', + request: { githubSource: { fullName: 'acme/web' } }, + ...(pairingHostId ? { pairingHostId } : {}) + } + } + }) as unknown as Pick + const hidden = (state: Pick) => [ + ...parseOrcaCloudHostScopeKey(selectOrcaCloudHostScopeKey(state)).hiddenHostIds + ] + expect(hidden(pairing())).toEqual([]) + expect(hidden(pairing('runtime:p'))).toEqual(['runtime:p']) + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.ts b/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.ts index ac77b801dd3..538b4601197 100644 --- a/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.ts +++ b/src/renderer/src/lib/orca-cloud/use-sidebar-hidden-checkouts.ts @@ -13,7 +13,12 @@ import { isOrcaCloudRuntimeEnvironment } from '../../../../shared/remote-runtime import type { Repo } from '../../../../shared/repo-types' type CloudScopeState = Pick & - Partial> + Partial< + Pick< + AppState, + 'orcaProfileAuthStatus' | 'cloudAccountIdByEnvironmentId' | 'pendingWorktreeCreations' + > + > /** * Every Orca Cloud server this desktop runs, `+host` when the active team owns it and `-host` @@ -30,7 +35,12 @@ type CloudScopeState = Pick & export function selectOrcaCloudHostScopeKey(state: CloudScopeState): string { const active = orcaCloudAccountId(state.orcaProfileAuthStatus?.cloud) const owners = state.cloudAccountIdByEnvironmentId ?? {} - return (state.runtimeEnvironments ?? []) + // GH-CREATE-NO-ROW: a GitHub-only create's pending row stands for its server's rows until the + // hand-off removes it; both change in one store update, so the row never shows twice. + const handingOff = Object.values(state.pendingWorktreeCreations ?? {}).flatMap((entry) => + entry.request.githubSource && entry.pairingHostId ? [`-${entry.pairingHostId}`] : [] + ) + const scoped = (state.runtimeEnvironments ?? []) .filter((environment) => isOrcaCloudRuntimeEnvironment(environment)) .flatMap((environment) => { const hostId = toRuntimeExecutionHostId(environment.id) @@ -41,7 +51,7 @@ export function selectOrcaCloudHostScopeKey(state: CloudScopeState): string { const inTeam = active !== null && owners[environment.id] === active return [`${inTeam ? '+' : '-'}${hostId}`] }) - .join('\n') + return [...scoped, ...handingOff].join('\n') } export function parseOrcaCloudHostScopeKey(key: string): { diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts index 6b8a9f043b4..d7b4b35f343 100644 --- a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts @@ -195,6 +195,8 @@ export type PendingWorktreeCreation = { resumedAt?: number /** VM creates: the provisioned VM's runtime environment, known once it answers. */ vmEnvironmentId?: string + /** GitHub-only Orca Cloud create: the server it is pairing to; its rows wait for the hand-off. */ + pairingHostId?: string // Local git checkout meter; absent when git emits none or creation runs over SSH/runtime. checkoutProgress?: WorktreeCheckoutProgress /** Phases entered so far with their start times, so the chat checklist can time each step. */ diff --git a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts index 177eb7bf2f6..3ac855a0cf8 100644 --- a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts +++ b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts @@ -149,13 +149,7 @@ export function createRemovePendingWorktreeCreation( .catch(() => undefined) } const cleanup = cleanUpCancelledVm(creationId, removedEntry.request, get) - // A GitHub-only create past its start is opening a sandbox that stays; nothing is deleted. - const opening = Boolean(removedEntry.request.githubSource) && removedEntry.phase === 'creating' - if ( - removedEntry.status === 'creating' && - isOrcaCloudCreateRequest(removedEntry.request) && - !opening - ) { + if (removedEntry.status === 'creating' && isOrcaCloudCreateRequest(removedEntry.request)) { beginOrcaCloudCancelCleanup(creationId, cleanup ? [cleanup] : [], { runtimeId: removedEntry.request.ephemeralVmRuntimeId, createStartedAt: removedEntry.startedAt, diff --git a/src/renderer/src/store/slices/worktrees/worktree-slice-contract.ts b/src/renderer/src/store/slices/worktrees/worktree-slice-contract.ts index f55349c25be..8fc823291c3 100644 --- a/src/renderer/src/store/slices/worktrees/worktree-slice-contract.ts +++ b/src/renderer/src/store/slices/worktrees/worktree-slice-contract.ts @@ -186,6 +186,7 @@ export type WorktreeSlice = { pausedMs?: number resumedAt?: number vmEnvironmentId?: string + pairingHostId?: string checkoutProgress?: PendingWorktreeCreation['checkoutProgress'] worktreeId?: string heldChatMessage?: string diff --git a/src/shared/sidebar-list/sidebar-row-plan.ts b/src/shared/sidebar-list/sidebar-row-plan.ts index 68dbcda8e62..195a5d30651 100644 --- a/src/shared/sidebar-list/sidebar-row-plan.ts +++ b/src/shared/sidebar-list/sidebar-row-plan.ts @@ -212,8 +212,10 @@ export function planSidebarRows(inputs: SidebarRowPlanInputs) { const naturalWorktrees = orderedGroups.flatMap(([, group]) => group.items) const render = (collapsedGroups: Set): Row[] => { const result: Row[] = [] - if (groupBy !== 'repo') { - for (const creation of pendingCreations) { + // By project, a create sits atop its own project; one with no project here yet (a GitHub-only + // Orca Cloud create, GH-CREATE-NO-ROW) sits atop the list, as in every other grouping. + for (const creation of pendingCreations) { + if (groupBy !== 'repo' || !repoMap.has(creation.repoId)) { result.push(buildPendingCreationRow(creation, repoMap)) } } diff --git a/src/shared/sidebar-list/worktree-grouping.ts b/src/shared/sidebar-list/worktree-grouping.ts index ad1d8dd639b..387aa316f96 100644 --- a/src/shared/sidebar-list/worktree-grouping.ts +++ b/src/shared/sidebar-list/worktree-grouping.ts @@ -71,7 +71,8 @@ export function buildOrderedGroups(args: { ([repoId, candidate]) => [repoId, candidate.repo] as const ) ], - pendingRepoIds: pendingByRepo.keys(), + // A create with no project here yet sits atop the list instead (GH-CREATE-NO-ROW). + pendingRepoIds: [...pendingByRepo.keys()].filter((repoId) => repoMap.has(repoId)), repoOrder, projectOrderBy }) From 52b838fb4252d05b7eaef059b90df5e89fe3f51b Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 21:34:27 -0800 Subject: [PATCH 26/28] fix(sidebar): a cloud create's billing refusal reads in muted text (design-squad #623) --- .../rows/PendingWorktreeRow.refusal.test.tsx | 60 +++++++++++++++++++ .../worktree-list/rows/PendingWorktreeRow.tsx | 11 +++- 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.refusal.test.tsx diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.refusal.test.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.refusal.test.tsx new file mode 100644 index 00000000000..438da0aac4a --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.refusal.test.tsx @@ -0,0 +1,60 @@ +// @vitest-environment happy-dom +// A cloud create's billing refusal is a precondition, not an error: its sidebar status reads in +// muted text (the glyph carries the state); a real failure stays red. +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it } from 'vitest' +import { useAppStore } from '@/store' +import { githubCreateRequest } from '@/lib/orca-cloud/start-cloud-workspace-from-github' +import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' +import { PendingWorktreeRow } from './PendingWorktreeRow' + +afterEach(cleanup) + +function failed( + errorCode: string | undefined, + log: string, + error: string +): PendingWorktreeCreation { + return { + creationId: 'c', + phase: 'provisioning-vm', + status: 'error', + startedAt: 1, + indeterminate: false, + loaderVisible: true, + error, + ...(errorCode ? { errorCode } : {}), + provisioningLog: log, + request: githubCreateRequest({ + repoUrl: 'https://github.com/acme/web', + fullName: 'acme/web', + prompt: 'Fix login', + agent: null + }) + } +} + +function statusLine(entry: PendingWorktreeCreation): HTMLElement { + useAppStore.setState({ pendingWorktreeCreations: { c: entry }, repos: [] }) + render() + return screen.getByText('Fix login').nextElementSibling as HTMLElement +} + +describe('pending row status colour', () => { + it('billing refusal: muted', () => { + const line = statusLine( + failed( + 'cloudPlanRequired', + '[orca-cloud] provisioning\nOrca Cloud: included_hours_exhausted', + 'Orca Cloud workspaces need a plan with cloud hours.' + ) + ) + expect(line.className).toContain('text-muted-foreground') + expect(line.className).not.toContain('text-destructive') + }) + + it('a real failure: red', () => { + const line = statusLine(failed(undefined, '[orca-cloud] provisioning', 'fetch failed')) + expect(line.className).toContain('text-destructive') + }) +}) diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx index ccc90ad092d..7dff544c420 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.tsx @@ -10,6 +10,10 @@ import { import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { vmBuildFailureSummary } from '@/components/worktree-creation/vm-build-failure-toast' +import { + classifyVmBuildFailure, + isBillingFailure +} from '@/components/worktree-creation/vm-build-failure' import type { Repo } from '../../../../../../shared/repo-types' function statusLabel( @@ -67,6 +71,11 @@ export function PendingWorktreeRow({ const isError = entry.status === 'error' const isOrcaCloud = entry.request.ephemeralVmRecipe?.provider === 'orca-cloud' + // A billing refusal is a precondition, not an error: muted text; the glyph carries the state. + const refused = + isError && + isOrcaCloud && + isBillingFailure(classifyVmBuildFailure({ entry, error: entry.error ?? null, cloud: true })) return (
{statusLabel(entry, repos, t)} From 849cf33d1c325f1b3f619d83628bb0a114d2e4d9 Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 21:45:15 -0800 Subject: [PATCH 27/28] test(sidebar): type guard instead of a cast in the refusal colour test --- .../worktree-list/rows/PendingWorktreeRow.refusal.test.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.refusal.test.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.refusal.test.tsx index 438da0aac4a..7765689b53e 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.refusal.test.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/PendingWorktreeRow.refusal.test.tsx @@ -37,7 +37,11 @@ function failed( function statusLine(entry: PendingWorktreeCreation): HTMLElement { useAppStore.setState({ pendingWorktreeCreations: { c: entry }, repos: [] }) render() - return screen.getByText('Fix login').nextElementSibling as HTMLElement + const line = screen.getByText('Fix login').nextElementSibling + if (!(line instanceof HTMLElement)) { + throw new Error('no status line') + } + return line } describe('pending row status colour', () => { From 18a79bcf4bb2dc4f57ebf15beb50b7eb38215f24 Mon Sep 17 00:00:00 2001 From: Neil Date: Fri, 13 Nov 2026 00:12:10 -0800 Subject: [PATCH 28/28] fix(cloud): MFA toast uses a plain button; toasts no longer take a Copy link source --- src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx | 2 +- src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx b/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx index fd4509e29fe..ee234a16b22 100644 --- a/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfa.fixture.tsx @@ -77,7 +77,7 @@ export const toast = frame( { key: 'mfa', text: 'Acme Engineering requires MFA from December 2, 2026.', - action: { label: 'Set up MFA', primary: true, link: setupUrl, onClick: noop } + action: { label: 'Set up MFA', primary: true, onClick: noop } } ] }} diff --git a/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx b/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx index f2d02d290be..4d2a862bb06 100644 --- a/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx +++ b/src/renderer/src/components/team-mfa/TeamMfaAppBanner.tsx @@ -42,8 +42,8 @@ export function TeamMfaSidebarBanner(): React.JSX.Element | null { action: { label: t('auto.components.teamMfa.setUp', 'Set up MFA'), primary: true, - // Opens the account page in the browser, so the chevron offers Copy link. - link: toast.setupUrl, + // A plain button: toasts no longer carry a Copy link chevron (AUTH-ONLY-COPY-LINK). + // The sidebar card and Settings, Account keep the split button. onClick: () => { void window.api.shell.openUrl(toast.setupUrl) hideCloudToast(id)