diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index ff125bd74d6..107660aeac1 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -14,7 +14,7 @@ 14 src/main/agent-launch/trust/agent-trust-presets.ts 2 src/main/agent-launch/trust/antigravity-workspace-trust-ownership.ts 1 src/main/agent-launch/trust/execution-host-workspace-trust.ts -2 src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts +1 src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts 1 src/main/ai-vault-search/session-search-worker-client.ts 4 src/main/ai-vault/parse-cache/session-parse-cache-legacy-json.ts 2 src/main/ai-vault/scan-service/session-scanner-service-entry-path.ts @@ -54,6 +54,7 @@ 5 src/main/browser/cookies/sources/browser-cookie-source-profiles.ts 11 src/main/browser/cookies/staging/browser-session-cookie-staging.ts 1 src/main/browser/downloads/browser-download-destination.ts +2 src/main/browser/electron-fixtures/popup-identity-electron-probe.ts 2 src/main/browser/extensions/api-runtime/browser-extension-worker-shim-source.ts 8 src/main/browser/extensions/installation/browser-extension-install-store.ts 1 src/main/browser/extensions/installation/browser-extension-load-directory.ts @@ -63,7 +64,6 @@ 4 src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.ts 3 src/main/browser/extensions/profile-storage/browser-extension-retired-profile-storage.ts 1 src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-cdp-probe.ts -2 src/main/browser/electron-fixtures/popup-identity-electron-probe.ts 1 src/main/browser/identity/mode/browser-identity-mode-record.ts 2 src/main/browser/identity/mode/browser-identity-mode-store.ts 2 src/main/browser/network/egress/browser-route-egress-electron-launch.ts @@ -117,7 +117,6 @@ 1 src/main/codex-accounts/codex-login-auth-snapshot.ts 5 src/main/codex-accounts/codex-managed-home-lifecycle.ts 6 src/main/codex-accounts/codex-managed-home-path.ts -17 src/main/filesystem/atomic-file-publication.ts 1 src/main/codex-accounts/guest-codex-account-homes.ts 6 src/main/codex-accounts/host-codex-managed-home-ownership.ts 2 src/main/codex-accounts/legacy-shared-auth-migration.ts @@ -247,6 +246,7 @@ 7 src/main/emulator/serve-sim-execution.ts 17 src/main/emulator/serve-sim-runtime-materializer.ts 12 src/main/external-editors/external-editor-launch.ts +17 src/main/filesystem/atomic-file-publication.ts 9 src/main/filesystem/durable-file-write.ts 2 src/main/filesystem/rolling-file-backup.ts 2 src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry-path.ts @@ -297,6 +297,7 @@ 13 src/main/kimi/hook-service.ts 3 src/main/kiro/hook-service.ts 1 src/main/kiro/standalone-hooks.ts +3 src/main/lib/hidden-probe-cwd.ts 4 src/main/linear/linear-credential-paths.ts 3 src/main/linear/linear-legacy-viewer-store.ts 1 src/main/linear/linear-token-store.ts @@ -465,7 +466,6 @@ 1 src/main/qoder/workspace-trust.ts 4 src/main/rate-limits/providers/cursor/cursor-auth.ts 2 src/main/rate-limits/providers/grok/grok-auth.ts -3 src/main/lib/hidden-probe-cwd.ts 2 src/main/rate-limits/providers/opencode-go/opencode-go-api-key-source.ts 1 src/main/rate-limits/providers/zcode/zcode-usage-credentials.ts 3 src/main/ripgrep/bundled-ripgrep-path.ts diff --git a/src/main/agent-config-sync/agent-config-digest.ts b/src/main/agent-config-sync/agent-config-digest.ts new file mode 100644 index 00000000000..798d38cd28a --- /dev/null +++ b/src/main/agent-config-sync/agent-config-digest.ts @@ -0,0 +1,21 @@ +import { createHash } from 'node:crypto' + +export type AgentConfigDigestEntry = { + /** Relative path inside a skill folder, or `.` for a command file. */ + path: string + executable: boolean + bytes: Buffer +} + +/** Content identity of one item. Desktop and host compute it the same way, so either side can tell + * whether a sandbox copy is exactly what this computer sent. */ +export function agentConfigDigest(entries: readonly AgentConfigDigestEntry[]): string { + const hash = createHash('sha256') + for (const entry of [...entries].sort((a, b) => + a.path < b.path ? -1 : a.path > b.path ? 1 : 0 + )) { + const body = createHash('sha256').update(entry.bytes).digest('hex') + hash.update(`${entry.path}\0${entry.executable ? 1 : 0}\0${body}\n`) + } + return hash.digest('hex') +} diff --git a/src/main/agent-config-sync/agent-config-roots.ts b/src/main/agent-config-sync/agent-config-roots.ts new file mode 100644 index 00000000000..a97863805b8 --- /dev/null +++ b/src/main/agent-config-sync/agent-config-roots.ts @@ -0,0 +1,69 @@ +import { homedir } from 'node:os' +import { join } from 'node:path' +import type { + AgentConfigItemKind, + AgentConfigItemScope +} from '../../shared/agent-config-sync/agent-config-sync-contract' +import { AGENT_CONFIG_FILE_KINDS } from '../../shared/agent-config-sync/agent-config-sync-contract' + +export type AgentConfigHomes = { + /** Claude Code's config dir: $CLAUDE_CONFIG_DIR or ~/.claude. */ + claudeDir: string + /** $CODEX_HOME or ~/.codex. */ + codexDir: string + home: string +} + +export function defaultAgentConfigHomes(env: NodeJS.ProcessEnv = process.env): AgentConfigHomes { + const home = homedir() + return { + claudeDir: env.CLAUDE_CONFIG_DIR?.trim() || join(home, '.claude'), + codexDir: env.CODEX_HOME?.trim() || join(home, '.codex'), + home + } +} + +/** The folder that holds every item of a kind; null when the kind has no such scope. */ +export function agentConfigRoot( + kind: AgentConfigItemKind, + scope: AgentConfigItemScope, + homes: AgentConfigHomes, + projectPath: string | null +): string | null { + if (scope === 'project') { + if (!projectPath) { + return null + } + switch (kind) { + case 'claude-skill': + return join(projectPath, '.claude', 'skills') + case 'claude-command': + return join(projectPath, '.claude', 'commands') + case 'agents-skill': + return join(projectPath, '.agents', 'skills') + // Codex reads prompts and its older skills folder from home only. + case 'codex-skill': + case 'codex-prompt': + return null + } + } + switch (kind) { + case 'claude-skill': + return join(homes.claudeDir, 'skills') + case 'claude-command': + return join(homes.claudeDir, 'commands') + case 'agents-skill': + return join(homes.home, '.agents', 'skills') + case 'codex-skill': + return join(homes.codexDir, 'skills') + case 'codex-prompt': + return join(homes.codexDir, 'prompts') + } +} + +/** Where one item lives under its root: a folder for skills, `.md` for commands. */ +export function agentConfigItemPath(root: string, kind: AgentConfigItemKind, name: string): string { + return AGENT_CONFIG_FILE_KINDS.has(kind) + ? join(root, ...`${name}.md`.split('/')) + : join(root, name) +} diff --git a/src/main/agent-config-sync/desktop/agent-config-secret-scan.ts b/src/main/agent-config-sync/desktop/agent-config-secret-scan.ts new file mode 100644 index 00000000000..4638368c1d9 --- /dev/null +++ b/src/main/agent-config-sync/desktop/agent-config-secret-scan.ts @@ -0,0 +1,41 @@ +/** + * Skills sometimes sit next to keys a script reads. Those files stay on this computer: names that + * hold credentials by convention, and text with a well-known key or token shape. + */ + +const SECRET_FILE_NAMES = [ + /^\.?env(\..*)?$/i, + /\.(pem|key|p12|pfx|jks|keystore|ppk|asc|gpg|kdbx|der|crt)$/i, + /^id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i, + /^(credentials?|secrets?|tokens?|auth|service[-_]?account)([-_.].*)?\.(json|ya?ml|toml|txt|ini|env)$/i, + /^\.?(npmrc|netrc|pypirc|htpasswd|git-credentials)$/i, + /^client_secret.*\.json$/i +] + +const SECRET_CONTENT = [ + /-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/, + /\bAKIA[0-9A-Z]{16}\b/, + /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}\b/, + /\bgithub_pat_[A-Za-z0-9_]{60,}\b/, + /\bglpat-[A-Za-z0-9_-]{20,}\b/, + /\bsk-ant-[A-Za-z0-9_-]{20,}\b/, + /\bsk-(?:proj-|live_|test_)?[A-Za-z0-9_-]{32,}\b/, + /\bxox[abposr]-[A-Za-z0-9-]{10,}\b/, + /\bAIza[0-9A-Za-z_-]{35}\b/, + /\bnpm_[A-Za-z0-9]{36}\b/, + /\b(?:rk|sk)_live_[A-Za-z0-9]{20,}\b/, + /\bvck_[A-Za-z0-9]{20,}\b/ +] + +export function isSecretFileName(name: string): boolean { + return SECRET_FILE_NAMES.some((pattern) => pattern.test(name)) +} + +/** Binary files are not scanned: the patterns are text shapes. */ +export function hasSecretContent(bytes: Buffer): boolean { + if (bytes.subarray(0, 8000).includes(0)) { + return false + } + const text = bytes.toString('utf8') + return SECRET_CONTENT.some((pattern) => pattern.test(text)) +} diff --git a/src/main/agent-config-sync/desktop/agent-config-sync-plan.ts b/src/main/agent-config-sync/desktop/agent-config-sync-plan.ts new file mode 100644 index 00000000000..9cd665f6660 --- /dev/null +++ b/src/main/agent-config-sync/desktop/agent-config-sync-plan.ts @@ -0,0 +1,190 @@ +import { + AGENT_CONFIG_LIMITS, + agentConfigItemKey, + type AgentConfigItemKind, + type AgentConfigItemPayload, + type AgentConfigItemRef, + type AgentConfigSyncPlanResult, + type AgentConfigSyncPutResult, + type AgentConfigSyncRow +} from '../../../shared/agent-config-sync/agent-config-sync-contract' +import type { AgentConfigDigestEntry } from '../agent-config-digest' +import type { LocalAgentConfigItem } from './local-agent-config-read' + +export type DesiredAgentConfigItem = AgentConfigItemRef & { + key: string + files: AgentConfigDigestEntry[] +} + +export type AgentConfigSyncPlan = { + rows: AgentConfigSyncRow[] + desired: DesiredAgentConfigItem[] +} + +/** The other agent's kind an item converts to; the formats match (SKILL.md folders, Markdown prompts). */ +function counterpartKind(item: LocalAgentConfigItem): AgentConfigItemKind | null { + switch (item.kind) { + case 'claude-skill': + return 'agents-skill' + case 'agents-skill': + case 'codex-skill': + return 'claude-skill' + case 'claude-command': + // Codex prompts are flat: a namespaced command has no Codex name. + return item.name.includes('/') ? null : 'codex-prompt' + case 'codex-prompt': + return 'claude-command' + } +} + +/** Kinds that already give the other agent an item of that name. */ +const NATIVE_FOR: Record = { + 'agents-skill': ['agents-skill', 'codex-skill'], + 'codex-skill': ['agents-skill', 'codex-skill'], + 'claude-skill': ['claude-skill'], + 'claude-command': ['claude-command'], + 'codex-prompt': ['codex-prompt'] +} + +function rowOf(item: LocalAgentConfigItem, key: string, included: boolean): AgentConfigSyncRow { + return { + key, + scope: item.scope, + kind: item.kind, + name: item.name, + bytes: item.bytes, + fileCount: item.fileCount, + withheldFiles: item.withheldFiles, + included, + state: 'pending' + } +} + +/** What to send and how each local item shows, before the host answers. */ +export function planAgentConfigSync(args: { + items: readonly LocalAgentConfigItem[] + excluded: ReadonlySet + shareAcrossAgents: boolean +}): AgentConfigSyncPlan { + const rows: AgentConfigSyncRow[] = [] + const candidates: { row: AgentConfigSyncRow; item: LocalAgentConfigItem }[] = [] + const names = new Set( + args.items.filter((item) => item.scope === 'user').map((item) => `${item.kind}:${item.name}`) + ) + const converted = new Set() + for (const item of args.items) { + const key = agentConfigItemKey(item.scope, item.kind, item.name) + const included = !args.excluded.has(key) + const row = rowOf(item, key, included) + if (item.skipReason) { + rows.push({ ...row, state: 'skipped', skipReason: item.skipReason }) + continue + } + if (!included) { + rows.push({ ...row, state: 'skipped', skipReason: 'turned-off' }) + continue + } + rows.push(row) + candidates.push({ row, item }) + const target = args.shareAcrossAgents && item.scope === 'user' ? counterpartKind(item) : null + if ( + !target || + NATIVE_FOR[target].some((kind) => names.has(`${kind}:${item.name}`)) || + converted.has(`${target}:${item.name}`) + ) { + continue + } + // One copy per name: .agents and the older .codex skills folder can both hold it. + converted.add(`${target}:${item.name}`) + const copy = { ...item, kind: target } + const copyRow: AgentConfigSyncRow = { + ...rowOf(copy, agentConfigItemKey('user', target, item.name), true), + convertedFrom: key + } + rows.push(copyRow) + candidates.push({ row: copyRow, item: copy }) + } + // Natives first, so a copy is what falls past the limit. + candidates.sort((a, b) => Number(!!a.row.convertedFrom) - Number(!!b.row.convertedFrom)) + const desired: DesiredAgentConfigItem[] = [] + let total = 0 + for (const { row, item } of candidates) { + if ( + desired.length >= AGENT_CONFIG_LIMITS.items || + total + item.bytes > AGENT_CONFIG_LIMITS.totalBytes || + !item.digest + ) { + row.state = 'skipped' + row.skipReason = 'over-limit' + continue + } + total += item.bytes + desired.push({ + key: row.key, + scope: item.scope, + kind: item.kind, + name: item.name, + digest: item.digest, + files: item.files + }) + } + return { rows, desired } +} + +/** Put calls that each stay under one item's byte budget (and so under the RPC frame). */ +export function agentConfigPutBatches( + items: readonly DesiredAgentConfigItem[] +): AgentConfigItemPayload[][] { + const batches: AgentConfigItemPayload[][] = [] + let current: AgentConfigItemPayload[] = [] + let bytes = 0 + for (const item of items) { + const size = item.files.reduce((sum, file) => sum + file.bytes.length, 0) + if ( + current.length > 0 && + (bytes + size > AGENT_CONFIG_LIMITS.itemBytes || + current.length >= AGENT_CONFIG_LIMITS.putItems) + ) { + batches.push(current) + current = [] + bytes = 0 + } + current.push({ + scope: item.scope, + kind: item.kind, + name: item.name, + digest: item.digest, + files: item.files.map((file) => ({ + path: file.path, + executable: file.executable, + base64: file.bytes.toString('base64') + })) + }) + bytes += size + } + if (current.length > 0) { + batches.push(current) + } + return batches +} + +const SYNCED_OUTCOMES: ReadonlySet = new Set(['added', 'updated', 'unchanged']) + +/** Rows after the host's plan and puts answered. */ +export function applyAgentConfigSyncResults( + rows: readonly AgentConfigSyncRow[], + plan: AgentConfigSyncPlanResult, + put: AgentConfigSyncPutResult['items'] +): AgentConfigSyncRow[] { + return rows.map((row) => { + if (row.state === 'skipped') { + return row + } + const outcome = put[row.key] ?? plan.items[row.key] + if (!outcome) { + return row + } + const synced = SYNCED_OUTCOMES.has(outcome) + return { ...row, state: synced ? 'synced' : 'skipped', outcome } + }) +} diff --git a/src/main/agent-config-sync/desktop/cloud-agent-config-sync-ipc.ts b/src/main/agent-config-sync/desktop/cloud-agent-config-sync-ipc.ts new file mode 100644 index 00000000000..830c47a73a1 --- /dev/null +++ b/src/main/agent-config-sync/desktop/cloud-agent-config-sync-ipc.ts @@ -0,0 +1,84 @@ +import { BrowserWindow, ipcMain } from 'electron' +import { + CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL, + CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL, + type CloudAgentConfigSyncPreferences +} from '../../../shared/agent-config-sync/agent-config-sync-contract' +import { createCloudAgentConfigSync, type CloudAgentConfigSync } from './cloud-agent-config-sync' + +let instance: CloudAgentConfigSync | null = null + +function send(channel: string, payload: unknown): void { + for (const window of BrowserWindow.getAllWindows()) { + if (!window.isDestroyed()) { + window.webContents.send(channel, payload) + } + } +} + +function environmentIdOf(value: unknown): string | null { + return typeof value === 'string' && value.length > 0 && value.length <= 256 ? value : null +} + +function preferencesOf(value: unknown): Partial { + if (!value || typeof value !== 'object') { + return {} + } + const raw = value as Record + return { + ...(typeof raw.autoSync === 'boolean' ? { autoSync: raw.autoSync } : {}), + ...(typeof raw.shareAcrossAgents === 'boolean' + ? { shareAcrossAgents: raw.shareAcrossAgents } + : {}) + } +} + +/** Orca Cloud builds only; other builds answer null so the renderer hides the pane. */ +export function installCloudAgentConfigSync(userDataPath: string): CloudAgentConfigSync { + instance ??= createCloudAgentConfigSync({ + userDataPath, + broadcast: (status) => send(CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL, status), + broadcastPreferences: (preferences) => + send(CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL, preferences) + }) + return instance +} + +const CHANNELS = [ + 'cloudAgentConfigSync:getStatus', + 'cloudAgentConfigSync:syncNow', + 'cloudAgentConfigSync:getPreferences', + 'cloudAgentConfigSync:setPreferences', + 'cloudAgentConfigSync:setItemIncluded' +] as const + +export function registerCloudAgentConfigSyncHandlers(): void { + for (const channel of CHANNELS) { + ipcMain.removeHandler(channel) + } + ipcMain.handle('cloudAgentConfigSync:getStatus', (_event, value: unknown) => { + const environmentId = environmentIdOf(value) + return environmentId && instance ? instance.getStatus(environmentId) : null + }) + ipcMain.handle('cloudAgentConfigSync:syncNow', (_event, value: unknown) => { + const environmentId = environmentIdOf(value) + return environmentId && instance ? instance.sync(environmentId, 'manual') : null + }) + ipcMain.handle('cloudAgentConfigSync:getPreferences', async () => { + if (!instance) { + return null + } + await instance.ready + return instance.getPreferences() + }) + ipcMain.handle('cloudAgentConfigSync:setPreferences', (_event, value: unknown) => + instance ? instance.setPreferences(preferencesOf(value)) : null + ) + ipcMain.handle( + 'cloudAgentConfigSync:setItemIncluded', + (_event, key: unknown, included: unknown) => + instance && typeof key === 'string' && key.length <= 300 && typeof included === 'boolean' + ? instance.setItemIncluded(key, included) + : null + ) +} diff --git a/src/main/agent-config-sync/desktop/cloud-agent-config-sync-support.ts b/src/main/agent-config-sync/desktop/cloud-agent-config-sync-support.ts new file mode 100644 index 00000000000..d8729ef0ff5 --- /dev/null +++ b/src/main/agent-config-sync/desktop/cloud-agent-config-sync-support.ts @@ -0,0 +1,59 @@ +import type { + AgentConfigSyncStatus, + CloudAgentConfigSyncPreferences +} from '../../../shared/agent-config-sync/agent-config-sync-contract' +import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' + +export const MAX_EXCLUDED = 1024 + +// Off until the user turns it on: a cloud workspace can be shared with a team, and skills are +// the user's own prompts. One switch in Settings is the consent. +export const DEFAULT_PREFERENCES: CloudAgentConfigSyncPreferences = { + autoSync: false, + shareAcrossAgents: false, + excluded: [] +} + +export class RuntimeCallError extends Error { + constructor( + message: string, + readonly code: string | undefined + ) { + super(message) + } +} + +export function errorCode(error: unknown): AgentConfigSyncStatus['error'] { + const code = + typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : '' + if (code === 'method_not_found') { + return 'host-outdated' + } + return /unavailable|timeout|unreachable/.test(code) ? 'host-unreachable' : 'failed' +} + +/** Repo-relative files git tracks under the project agent folders. */ +export async function trackedAgentConfigPaths(repoPath: string): Promise> { + const { stdout } = await gitExecFileAsync( + ['ls-files', '-z', '--', '.claude/skills', '.claude/commands', '.agents/skills'], + { cwd: repoPath, timeout: 10_000 } + ) + return new Set(stdout.split('\0').filter(Boolean)) +} + +export function parsePreferences(text: string): CloudAgentConfigSyncPreferences { + const raw: unknown = JSON.parse(text) + if (!raw || typeof raw !== 'object') { + return { ...DEFAULT_PREFERENCES, excluded: [] } + } + return { + autoSync: 'autoSync' in raw && raw.autoSync === true, + shareAcrossAgents: 'shareAcrossAgents' in raw && raw.shareAcrossAgents === true, + excluded: + 'excluded' in raw && Array.isArray(raw.excluded) + ? raw.excluded + .filter((key): key is string => typeof key === 'string' && key.length <= 300) + .slice(0, MAX_EXCLUDED) + : [] + } +} diff --git a/src/main/agent-config-sync/desktop/cloud-agent-config-sync.test.ts b/src/main/agent-config-sync/desktop/cloud-agent-config-sync.test.ts new file mode 100644 index 00000000000..1d52ae730cb --- /dev/null +++ b/src/main/agent-config-sync/desktop/cloud-agent-config-sync.test.ts @@ -0,0 +1,263 @@ +import { execFileSync } from 'node:child_process' +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync +} from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + AGENT_CONFIG_SYNC_PLAN_METHOD, + AGENT_CONFIG_SYNC_PUT_METHOD, + AgentConfigSyncPlanParams, + AgentConfigSyncPutParams, + type AgentConfigSyncStatus +} from '../../../shared/agent-config-sync/agent-config-sync-contract' +import type { AgentConfigHomes } from '../agent-config-roots' +import { planHostAgentConfigSync, putHostAgentConfig } from '../host/host-agent-config-sync' +import { createCloudAgentConfigSync } from './cloud-agent-config-sync' +import { readLocalAgentConfig } from './local-agent-config-read' + +type FakeRuntime = { + runtimeEnvironmentId: string + recipe: { provider: string } + repoPath: string + status: string +} +const runtimes = vi.hoisted((): { list: FakeRuntime[] } => ({ list: [] })) +vi.mock('../../../shared/ephemeral-vm-runtime-store', () => ({ + listEphemeralVmRuntimes: () => runtimes.list +})) + +let dir: string +let local: AgentConfigHomes +let host: AgentConfigHomes +let hostProject: string +let localRepo: string +let calls: { method: string; params: unknown }[] + +function put(path: string, text: string, mode?: number): void { + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, text) + if (mode) { + chmodSync(path, mode) + } +} + +function homesUnder(root: string): AgentConfigHomes { + return { home: root, claudeDir: join(root, '.claude'), codexDir: join(root, '.codex') } +} + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'cloud-agent-config-')) + local = homesUnder(join(dir, 'mac')) + host = homesUnder(join(dir, 'vm')) + localRepo = join(dir, 'mac-repo') + hostProject = join(dir, 'vm-project') + mkdirSync(localRepo, { recursive: true }) + mkdirSync(hostProject, { recursive: true }) + execFileSync('git', ['init', '-q', hostProject]) + calls = [] + runtimes.list = [ + { + runtimeEnvironmentId: 'env-1', + recipe: { provider: 'orca-cloud' }, + repoPath: localRepo, + // Not running, so turning sync on doesn't start its own sync under each test. + status: 'stopped' + } + ] +}) + +afterEach(() => { + rmSync(dir, { recursive: true, force: true }) +}) + +function create(patch: { outdated?: boolean } = {}) { + const statuses: AgentConfigSyncStatus[] = [] + const hostDeps = { homes: host, projectPath: hostProject, ledgerDir: join(dir, 'vm-userdata') } + const sync = createCloudAgentConfigSync({ + userDataPath: join(dir, 'mac-userdata'), + broadcast: (status) => statuses.push(status), + readLocal: (repoPath) => + readLocalAgentConfig({ homes: local, repoPath, trackedPaths: async () => new Set() }), + // The wire schemas run here as they do in orcad, so the test also checks what crosses. + call: async (_environmentId, method, params) => { + calls.push({ method, params }) + if (patch.outdated) { + throw Object.assign(new Error('nope'), { code: 'method_not_found' }) + } + if (method === AGENT_CONFIG_SYNC_PLAN_METHOD) { + return planHostAgentConfigSync(AgentConfigSyncPlanParams.parse(params), hostDeps) + } + if (method === AGENT_CONFIG_SYNC_PUT_METHOD) { + return putHostAgentConfig(AgentConfigSyncPutParams.parse(params), hostDeps) + } + throw new Error(`unexpected ${method}`) + }, + now: () => 1_000 + }) + mkdirSync(join(dir, 'mac-userdata'), { recursive: true }) + return { sync, statuses } +} + +const outcomes = (status: AgentConfigSyncStatus | null) => + Object.fromEntries((status?.rows ?? []).map((row) => [row.key, row.outcome ?? row.skipReason])) + +describe('cloud agent config sync, desktop to host', () => { + it('stays off on connect until the user turns it on, then copies skills and commands', async () => { + put(join(local.claudeDir, 'skills', 'deploy', 'SKILL.md'), '---\nname: deploy\n---\nShip.') + put(join(local.claudeDir, 'skills', 'deploy', 'run.sh'), '#!/bin/sh\n', 0o755) + put(join(local.claudeDir, 'commands', 'review.md'), 'Review $ARGUMENTS') + const { sync } = create() + expect(await sync.sync('env-1', 'connect')).toBeNull() + expect(calls).toEqual([]) + + sync.setPreferences({ autoSync: true }) + const status = await sync.sync('env-1', 'connect') + expect(status?.error).toBeNull() + expect(outcomes(status)).toEqual({ + 'user:claude-skill:deploy': 'added', + 'user:claude-command:review': 'added' + }) + expect(readFileSync(join(host.claudeDir, 'skills', 'deploy', 'SKILL.md'), 'utf8')).toContain( + 'Ship.' + ) + expect(statSync(join(host.claudeDir, 'skills', 'deploy', 'run.sh')).mode & 0o111).not.toBe(0) + expect(readFileSync(join(host.claudeDir, 'commands', 'review.md'), 'utf8')).toBe( + 'Review $ARGUMENTS' + ) + }) + + it('sends nothing the host already has, updates its own copies and removes what was dropped', async () => { + put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'one') + put(join(local.claudeDir, 'skills', 'b', 'SKILL.md'), 'bee') + const { sync } = create() + sync.setPreferences({ autoSync: true }) + await sync.sync('env-1', 'manual') + + calls = [] + expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({ + 'user:claude-skill:a': 'unchanged', + 'user:claude-skill:b': 'unchanged' + }) + expect(calls.map((call) => call.method)).toEqual([AGENT_CONFIG_SYNC_PLAN_METHOD]) + + put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'two') + rmSync(join(local.claudeDir, 'skills', 'b'), { recursive: true }) + expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({ + 'user:claude-skill:a': 'updated' + }) + expect(readFileSync(join(host.claudeDir, 'skills', 'a', 'SKILL.md'), 'utf8')).toBe('two') + expect(existsSync(join(host.claudeDir, 'skills', 'b'))).toBe(false) + }) + + it('never touches items made or edited in the sandbox', async () => { + put(join(local.claudeDir, 'skills', 'mine', 'SKILL.md'), 'from the mac') + put(join(local.claudeDir, 'skills', 'edited', 'SKILL.md'), 'from the mac') + put(join(host.claudeDir, 'skills', 'mine', 'SKILL.md'), 'made in the sandbox') + const { sync } = create() + sync.setPreferences({ autoSync: true }) + expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({ + 'user:claude-skill:mine': 'kept-host', + 'user:claude-skill:edited': 'added' + }) + put(join(host.claudeDir, 'skills', 'edited', 'SKILL.md'), 'changed in the sandbox') + rmSync(join(local.claudeDir, 'skills', 'edited'), { recursive: true }) + await sync.sync('env-1', 'manual') + expect(readFileSync(join(host.claudeDir, 'skills', 'mine', 'SKILL.md'), 'utf8')).toBe( + 'made in the sandbox' + ) + expect(readFileSync(join(host.claudeDir, 'skills', 'edited', 'SKILL.md'), 'utf8')).toBe( + 'changed in the sandbox' + ) + }) + + it('shares skills and commands across agents only when asked, keeping each agent’s own', async () => { + put(join(local.claudeDir, 'skills', 'deploy', 'SKILL.md'), 'claude deploy') + put(join(local.claudeDir, 'skills', 'both', 'SKILL.md'), 'claude both') + put(join(local.home, '.agents', 'skills', 'both', 'SKILL.md'), 'codex both') + put(join(local.home, '.agents', 'skills', 'lint', 'SKILL.md'), 'codex lint') + put(join(local.claudeDir, 'commands', 'review.md'), 'review') + put(join(local.claudeDir, 'commands', 'ns', 'deep.md'), 'namespaced') + put(join(local.codexDir, 'prompts', 'fix.md'), 'fix') + const { sync } = create() + sync.setPreferences({ autoSync: true }) + await sync.sync('env-1', 'manual') + expect(existsSync(join(host.home, '.agents', 'skills', 'deploy'))).toBe(false) + + sync.setPreferences({ shareAcrossAgents: true }) + const status = await sync.sync('env-1', 'manual') + const copies = status?.rows.filter((row) => row.convertedFrom).map((row) => row.key) + expect(copies?.sort()).toEqual([ + 'user:agents-skill:deploy', + 'user:claude-command:fix', + 'user:claude-skill:lint', + 'user:codex-prompt:review' + ]) + expect(readFileSync(join(host.home, '.agents', 'skills', 'deploy', 'SKILL.md'), 'utf8')).toBe( + 'claude deploy' + ) + expect(readFileSync(join(host.home, '.agents', 'skills', 'both', 'SKILL.md'), 'utf8')).toBe( + 'codex both' + ) + expect(readFileSync(join(host.codexDir, 'prompts', 'review.md'), 'utf8')).toBe('review') + expect(readFileSync(join(host.claudeDir, 'commands', 'fix.md'), 'utf8')).toBe('fix') + expect(existsSync(join(host.codexDir, 'prompts', 'deep.md'))).toBe(false) + + // Turning an original off takes its copy with it. + sync.setItemIncluded('user:claude-skill:deploy', false) + await sync.sync('env-1', 'manual') + expect(existsSync(join(host.claudeDir, 'skills', 'deploy'))).toBe(false) + expect(existsSync(join(host.home, '.agents', 'skills', 'deploy'))).toBe(false) + }) + + it('puts untracked project items in the workspace and keeps them out of its git status', async () => { + put(join(localRepo, '.claude', 'skills', 'proj', 'SKILL.md'), 'project skill') + const { sync } = create() + sync.setPreferences({ autoSync: true }) + expect(outcomes(await sync.sync('env-1', 'manual'))).toEqual({ + 'project:claude-skill:proj': 'added' + }) + expect(readFileSync(join(hostProject, '.claude', 'skills', 'proj', 'SKILL.md'), 'utf8')).toBe( + 'project skill' + ) + const exclude = readFileSync(join(hostProject, '.git', 'info', 'exclude'), 'utf8') + expect(exclude.split('\n')).toContain('/.claude/skills/proj/') + const porcelain = execFileSync('git', ['-C', hostProject, 'status', '--porcelain'], { + encoding: 'utf8' + }) + expect(porcelain).toBe('') + }) + + it('says the sandbox is outdated when its Orca has no skill sync', async () => { + put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'x') + const { sync } = create({ outdated: true }) + const status = await sync.sync('env-1', 'manual') + expect(status?.error).toBe('host-outdated') + expect(status?.rows.map((row) => row.state)).toEqual(['pending']) + }) + + it('syncs running workspaces as soon as sync is turned on', async () => { + put(join(local.claudeDir, 'skills', 'a', 'SKILL.md'), 'x') + runtimes.list[0].status = 'running' + const { sync, statuses } = create() + sync.setPreferences({ autoSync: true }) + await vi.waitFor(() => + expect(statuses.some((status) => status.lastSyncedAt !== null)).toBe(true) + ) + expect(existsSync(join(host.claudeDir, 'skills', 'a', 'SKILL.md'))).toBe(true) + }) + + it('answers null for workspaces that are not Orca Cloud', async () => { + const { sync } = create() + expect(await sync.getStatus('env-other')).toBeNull() + expect(await sync.sync('env-other', 'manual')).toBeNull() + }) +}) diff --git a/src/main/agent-config-sync/desktop/cloud-agent-config-sync.ts b/src/main/agent-config-sync/desktop/cloud-agent-config-sync.ts new file mode 100644 index 00000000000..b2aed817bf5 --- /dev/null +++ b/src/main/agent-config-sync/desktop/cloud-agent-config-sync.ts @@ -0,0 +1,295 @@ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { + AGENT_CONFIG_SYNC_PLAN_METHOD, + AGENT_CONFIG_SYNC_PUT_METHOD, + AgentConfigSyncPlanResult, + AgentConfigSyncPutResult, + type AgentConfigSyncStatus, + type CloudAgentConfigSyncPreferences +} from '../../../shared/agent-config-sync/agent-config-sync-contract' +import { listEphemeralVmRuntimes } from '../../../shared/ephemeral-vm-runtime-store' +import { writeFileAtomically } from '../../filesystem/atomic-file-publication' +import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing' +import { defaultAgentConfigHomes } from '../agent-config-roots' +import { + agentConfigPutBatches, + applyAgentConfigSyncResults, + planAgentConfigSync +} from './agent-config-sync-plan' +import { readLocalAgentConfig, type LocalAgentConfigItem } from './local-agent-config-read' +import { readOrCreateSyncerId } from './syncer-id' +import { + DEFAULT_PREFERENCES, + MAX_EXCLUDED, + RuntimeCallError, + errorCode, + parsePreferences, + trackedAgentConfigPaths +} from './cloud-agent-config-sync-support' + +const PLAN_TIMEOUT_MS = 30_000 +const PUT_TIMEOUT_MS = 60_000 + +export type CloudAgentConfigSyncDeps = { + userDataPath: string + broadcast: (status: AgentConfigSyncStatus) => void + broadcastPreferences?: (preferences: CloudAgentConfigSyncPreferences) => void + readLocal?: (repoPath: string | null) => Promise + call?: ( + environmentId: string, + method: string, + params: unknown, + timeoutMs: number + ) => Promise + now?: () => number +} + +export type CloudAgentConfigSync = { + isCloudEnvironment(environmentId: string): boolean + getStatus(environmentId: string): Promise + sync(environmentId: string, trigger: 'connect' | 'manual'): Promise + /** Settles once saved preferences are read; getPreferences answers defaults until then. */ + ready: Promise + getPreferences(): CloudAgentConfigSyncPreferences + setPreferences(next: Partial): CloudAgentConfigSyncPreferences + setItemIncluded(key: string, included: boolean): CloudAgentConfigSyncPreferences +} + +/** Mirrors this computer's skills and slash commands into each Orca Cloud workspace. */ +export function createCloudAgentConfigSync(deps: CloudAgentConfigSyncDeps): CloudAgentConfigSync { + const preferencesPath = join(deps.userDataPath, 'cloud-agent-config-sync.json') + const statuses = new Map() + const queues = new Map>() + const now = deps.now ?? Date.now + const readLocal = + deps.readLocal ?? + ((repoPath) => + readLocalAgentConfig({ + homes: defaultAgentConfigHomes(), + repoPath, + trackedPaths: trackedAgentConfigPaths + })) + const call = + deps.call ?? + (async (environmentId: string, method: string, params: unknown, timeoutMs: number) => { + const response = await callRuntimeEnvironment( + deps.userDataPath, + environmentId, + method, + params, + timeoutMs + ) + if (response.ok) { + return response.result + } + throw new RuntimeCallError(response.error.message, response.error.code) + }) + + let preferences: CloudAgentConfigSyncPreferences | null = null + const ready = readFile(preferencesPath, 'utf8') + .then(parsePreferences) + .catch(() => null) + .then((loaded) => { + // A change saved while this read ran wins. + preferences ??= loaded ?? { ...DEFAULT_PREFERENCES, excluded: [] } + }) + function getPreferences(): CloudAgentConfigSyncPreferences { + return preferences ?? { ...DEFAULT_PREFERENCES, excluded: [] } + } + + function cloudRuntime(environmentId: string) { + return listEphemeralVmRuntimes(deps.userDataPath).find( + (runtime) => + runtime.runtimeEnvironmentId === environmentId && runtime.recipe?.provider === 'orca-cloud' + ) + } + + async function plan(environmentId: string) { + const local = await readLocal(cloudRuntime(environmentId)?.repoPath ?? null) + const prefs = getPreferences() + return planAgentConfigSync({ + items: local, + excluded: new Set(prefs.excluded), + shareAcrossAgents: prefs.shareAcrossAgents + }) + } + + function publish(status: AgentConfigSyncStatus): AgentConfigSyncStatus { + statuses.set(status.environmentId, status) + deps.broadcast(status) + return status + } + + async function run(environmentId: string): Promise { + const previous = statuses.get(environmentId) + const planned = await plan(environmentId).catch(() => null) + if (!planned) { + return publish({ + environmentId, + running: false, + lastSyncedAt: previous?.lastSyncedAt ?? null, + error: 'failed', + rows: previous?.rows ?? [] + }) + } + publish({ + environmentId, + running: true, + lastSyncedAt: previous?.lastSyncedAt ?? null, + error: previous?.error ?? null, + rows: previous?.rows.length ? previous.rows : planned.rows + }) + const syncer = await readOrCreateSyncerId(deps.userDataPath) + try { + const hostPlan = AgentConfigSyncPlanResult.parse( + await call( + environmentId, + AGENT_CONFIG_SYNC_PLAN_METHOD, + { + syncer, + items: planned.desired.map(({ scope, kind, name, digest }) => ({ + scope, + kind, + name, + digest + })) + }, + PLAN_TIMEOUT_MS + ) + ) + const needed = planned.desired.filter((item) => hostPlan.items[item.key] === 'needed') + const put: AgentConfigSyncPutResult['items'] = {} + for (const batch of agentConfigPutBatches(needed)) { + const answer = AgentConfigSyncPutResult.parse( + await call( + environmentId, + AGENT_CONFIG_SYNC_PUT_METHOD, + { syncer, items: batch }, + PUT_TIMEOUT_MS + ) + ) + Object.assign(put, answer.items) + } + const rows = applyAgentConfigSyncResults(planned.rows, hostPlan, put) + const synced = rows.filter((row) => row.state === 'synced').length + console.info( + `[cloud-agent-config-sync] ${environmentId}: ${synced} synced, ${needed.length} sent, ${hostPlan.removed} removed, ${rows.length - synced} not synced` + ) + return publish({ environmentId, running: false, lastSyncedAt: now(), error: null, rows }) + } catch (error) { + const code = errorCode(error) + console.warn(`[cloud-agent-config-sync] ${environmentId}: sync failed (${code})`) + return publish({ + environmentId, + running: false, + lastSyncedAt: previous?.lastSyncedAt ?? null, + error: code, + rows: planned.rows + }) + } + } + + function enqueue(environmentId: string): Promise { + // One sync per workspace at a time; a click during an auto-sync runs after it. + const next = (queues.get(environmentId) ?? Promise.resolve()) + .catch(() => {}) + .then(() => run(environmentId)) + queues.set(environmentId, next) + void next.finally(() => { + if (queues.get(environmentId) === next) { + queues.delete(environmentId) + } + }) + return next + } + + /** After a settings change, bring every workspace that already synced in line with it. */ + function resyncSynced(): void { + for (const status of statuses.values()) { + if (status.lastSyncedAt !== null && cloudRuntime(status.environmentId)) { + void enqueue(status.environmentId).catch(() => {}) + } + } + } + + function setPreferences( + next: Partial + ): CloudAgentConfigSyncPreferences { + const current = getPreferences() + const merged: CloudAgentConfigSyncPreferences = { + autoSync: next.autoSync ?? current.autoSync, + shareAcrossAgents: next.shareAcrossAgents ?? current.shareAcrossAgents, + excluded: [...new Set(next.excluded ?? current.excluded)].sort().slice(0, MAX_EXCLUDED) + } + writeFileAtomically(preferencesPath, `${JSON.stringify(merged, null, 2)}\n`) + preferences = merged + deps.broadcastPreferences?.(merged) + return merged + } + + return { + ready, + isCloudEnvironment: (environmentId) => cloudRuntime(environmentId) !== undefined, + async getStatus(environmentId) { + await ready + if (!cloudRuntime(environmentId)) { + return null + } + const known = statuses.get(environmentId) + if (known) { + return known + } + // Before any sync: what would go, read from this computer only. + const planned = await plan(environmentId).catch(() => null) + return { + environmentId, + running: false, + lastSyncedAt: null, + error: planned ? null : 'failed', + rows: planned?.rows ?? [] + } + }, + async sync(environmentId, trigger) { + await ready + if (!cloudRuntime(environmentId)) { + return null + } + if (trigger === 'connect' && !getPreferences().autoSync) { + return statuses.get(environmentId) ?? null + } + return enqueue(environmentId) + }, + getPreferences, + setPreferences(next) { + const before = getPreferences() + const merged = setPreferences(next) + // Turning sync on reaches the running workspaces now, not at their next wake. + if (merged.autoSync && !before.autoSync) { + for (const runtime of listEphemeralVmRuntimes(deps.userDataPath)) { + if ( + runtime.recipe?.provider === 'orca-cloud' && + runtime.status === 'running' && + runtime.runtimeEnvironmentId + ) { + void enqueue(runtime.runtimeEnvironmentId).catch(() => {}) + } + } + } else if (merged.shareAcrossAgents !== before.shareAcrossAgents) { + resyncSynced() + } + return merged + }, + setItemIncluded(key, included) { + const excluded = new Set(getPreferences().excluded) + if (included) { + excluded.delete(key) + } else { + excluded.add(key) + } + const merged = setPreferences({ excluded: [...excluded] }) + resyncSynced() + return merged + } + } +} diff --git a/src/main/agent-config-sync/desktop/local-agent-config-read.test.ts b/src/main/agent-config-sync/desktop/local-agent-config-read.test.ts new file mode 100644 index 00000000000..445995e8815 --- /dev/null +++ b/src/main/agent-config-sync/desktop/local-agent-config-read.test.ts @@ -0,0 +1,137 @@ +import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import type { AgentConfigHomes } from '../agent-config-roots' +import { readLocalAgentConfig } from './local-agent-config-read' + +let dir: string +let homes: AgentConfigHomes + +function put(path: string, text: string | Buffer, mode?: number): void { + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, text) + if (mode) { + chmodSync(path, mode) + } +} + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'agent-config-read-')) + homes = { + home: join(dir, 'home'), + claudeDir: join(dir, 'home', '.claude'), + codexDir: join(dir, 'home', '.codex') + } +}) + +afterEach(() => { + rmSync(dir, { recursive: true, force: true }) +}) + +const read = (repoPath: string | null = null, tracked: string[] | null = []) => + readLocalAgentConfig({ + homes, + repoPath, + trackedPaths: async () => (tracked ? new Set(tracked) : null) + }) + +describe('readLocalAgentConfig', () => { + it('reads skills with their files and keeps likely secrets on this computer', async () => { + const skill = join(homes.claudeDir, 'skills', 'deploy') + put(join(skill, 'SKILL.md'), '---\nname: deploy\n---\nShip it.') + put(join(skill, 'scripts', 'run.sh'), '#!/bin/sh\necho hi\n', 0o755) + put(join(skill, 'service-account.json'), '{}') + put(join(skill, 'notes.txt'), 'token: ghp_0123456789abcdefghijABCDEFGHIJ0123456789') + put(join(skill, '.env'), 'X=1') + put(join(skill, 'node_modules', 'x', 'index.js'), 'x') + // Not a skill: no SKILL.md. + put(join(homes.claudeDir, 'skills', 'synced', 'blob.bin'), 'x') + // A link out of the skill folder is not followed. + put(join(dir, 'outside.txt'), 'outside') + symlinkSync(join(dir, 'outside.txt'), join(skill, 'link.txt')) + + const items = await read() + expect(items).toHaveLength(1) + const [item] = items + expect(item).toMatchObject({ + scope: 'user', + kind: 'claude-skill', + name: 'deploy', + withheldFiles: 2 + }) + expect(item.skipReason).toBeUndefined() + expect(item.files.map((file) => [file.path, file.executable])).toEqual([ + ['SKILL.md', false], + ['scripts/run.sh', true] + ]) + expect(item.digest).toMatch(/^[a-f0-9]{64}$/) + }) + + it('skips a skill whose SKILL.md holds a key, and one that is too large', async () => { + put( + join(homes.claudeDir, 'skills', 'leaky', 'SKILL.md'), + 'Use sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789' + ) + put(join(homes.claudeDir, 'skills', 'huge', 'SKILL.md'), 'x') + put(join(homes.claudeDir, 'skills', 'huge', 'data.bin'), Buffer.alloc(300 * 1024)) + const items = await read() + expect(Object.fromEntries(items.map((item) => [item.name, item.skipReason]))).toEqual({ + leaky: 'secret', + huge: 'too-large' + }) + expect(items.every((item) => item.files.length === 0)).toBe(true) + }) + + it('reads namespaced Claude commands, flat Codex prompts, and both Codex skill folders', async () => { + put(join(homes.claudeDir, 'commands', 'review.md'), 'Review $ARGUMENTS') + put(join(homes.claudeDir, 'commands', 'frontend', 'component.md'), 'Make a component') + put(join(homes.claudeDir, 'commands', 'README.txt'), 'not a command') + put(join(homes.codexDir, 'prompts', 'fix.md'), 'Fix it') + put(join(homes.codexDir, 'prompts', 'nested', 'ignored.md'), 'Codex prompts are flat') + put(join(homes.home, '.agents', 'skills', 'lint', 'SKILL.md'), 'Lint') + put(join(homes.codexDir, 'skills', '.system', 'builtin', 'SKILL.md'), 'Codex own') + put(join(homes.codexDir, 'skills', 'legacy', 'SKILL.md'), 'Old home') + const items = await read() + expect(items.map((item) => `${item.kind}:${item.name}`).sort()).toEqual([ + 'agents-skill:lint', + 'claude-command:frontend/component', + 'claude-command:review', + 'codex-prompt:fix', + 'codex-skill:legacy' + ]) + const review = items.find((item) => item.name === 'review') + expect(review?.files).toEqual([ + { path: '.', executable: false, bytes: Buffer.from('Review $ARGUMENTS') } + ]) + }) + + it('sends project items git does not track, and marks committed ones as already in the repo', async () => { + const repo = join(dir, 'repo') + put(join(repo, '.claude', 'skills', 'committed', 'SKILL.md'), 'in git') + put(join(repo, '.claude', 'skills', 'local-only', 'SKILL.md'), 'not in git') + put(join(repo, '.claude', 'commands', 'ship.md'), 'in git') + put(join(repo, '.claude', 'commands', 'mine.md'), 'not in git') + const items = await read(repo, [ + '.claude/skills/committed/SKILL.md', + '.claude/commands/ship.md' + ]) + expect( + Object.fromEntries( + items.map((item) => [`${item.scope}:${item.name}`, item.skipReason ?? 'send']) + ) + ).toEqual({ + 'project:committed': 'in-repo', + 'project:local-only': 'send', + 'project:ship': 'in-repo', + 'project:mine': 'send' + }) + }) + + it('treats project items as committed when git cannot answer', async () => { + const repo = join(dir, 'repo') + put(join(repo, '.claude', 'skills', 'a', 'SKILL.md'), 'x') + const items = await read(repo, null) + expect(items.map((item) => item.skipReason)).toEqual(['in-repo']) + }) +}) diff --git a/src/main/agent-config-sync/desktop/local-agent-config-read.ts b/src/main/agent-config-sync/desktop/local-agent-config-read.ts new file mode 100644 index 00000000000..a40626d3993 --- /dev/null +++ b/src/main/agent-config-sync/desktop/local-agent-config-read.ts @@ -0,0 +1,314 @@ +import { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises' +import { join, relative, sep } from 'node:path' +import { + AGENT_CONFIG_COMMAND_NAME, + AGENT_CONFIG_FILE_PATH, + AGENT_CONFIG_LIMITS, + AGENT_CONFIG_PROJECT_KINDS, + AGENT_CONFIG_SELF_PATH, + AGENT_CONFIG_SKILL_NAME, + AgentConfigItemKind, + isSkillKind, + type AgentConfigItemScope, + type AgentConfigSkipReason +} from '../../../shared/agent-config-sync/agent-config-sync-contract' +import { agentConfigDigest, type AgentConfigDigestEntry } from '../agent-config-digest' +import { agentConfigRoot, type AgentConfigHomes } from '../agent-config-roots' +import { hasSecretContent, isSecretFileName } from './agent-config-secret-scan' + +export type LocalAgentConfigItem = { + scope: AgentConfigItemScope + kind: AgentConfigItemKind + name: string + /** Empty when skipped. */ + files: AgentConfigDigestEntry[] + fileCount: number + bytes: number + withheldFiles: number + digest: string | null + skipReason?: Extract +} + +export type LocalAgentConfigReadDeps = { + homes: AgentConfigHomes + /** The workspace's checkout on this computer, for project items. */ + repoPath: string | null + /** Repo-relative paths git tracks under the project agent folders; null when git can't say. */ + trackedPaths: (repoPath: string) => Promise | null> +} + +/** Folders a skill never needs in the sandbox. */ +const SKIPPED_DIRS = new Set(['node_modules', '__pycache__', 'venv']) +const MAX_DEPTH = 8 +const SKILL_FILE = 'SKILL.md' + +type Walked = + | { ok: true; files: AgentConfigDigestEntry[]; withheld: number; bytes: number } + | { ok: false; reason: 'too-large' | 'secret' | 'invalid' } + +async function isExecutable(path: string): Promise { + try { + return ((await stat(path)).mode & 0o111) !== 0 + } catch { + return false + } +} + +/** One file's verdict: kept, kept back as a likely secret, or too big for any skill. */ +async function readItemFile( + path: string, + name: string +): Promise<'too-large' | 'withheld' | { bytes: Buffer; executable: boolean }> { + const info = await stat(path) + if (info.size > AGENT_CONFIG_LIMITS.fileBytes) { + return 'too-large' + } + if (isSecretFileName(name)) { + return 'withheld' + } + const bytes = await readFile(path) + if (hasSecretContent(bytes)) { + return 'withheld' + } + return { bytes, executable: await isExecutable(path) } +} + +/** Every regular file in a skill folder; symlinks only when they stay inside it. */ +async function walkSkill(dir: string): Promise { + const root = await realpath(dir) + const files: AgentConfigDigestEntry[] = [] + let withheld = 0 + let bytes = 0 + const visit = async (current: string, depth: number): Promise => { + const entries = await readdir(current, { withFileTypes: true }) + entries.sort((a, b) => (a.name < b.name ? -1 : 1)) + for (const entry of entries) { + if (entry.name.startsWith('.') || SKIPPED_DIRS.has(entry.name)) { + continue + } + const path = join(current, entry.name) + let resolved = path + if (entry.isSymbolicLink()) { + try { + resolved = await realpath(path) + } catch { + continue + } + if (resolved !== root && !resolved.startsWith(root + sep)) { + continue + } + } + const info = await stat(resolved).catch(() => null) + if (!info) { + continue + } + const rel = relative(dir, path).split(sep).join('/') + if (info.isDirectory()) { + if (depth >= MAX_DEPTH) { + continue + } + const nested = await visit(path, depth + 1) + if (nested) { + return nested + } + continue + } + if (!info.isFile()) { + continue + } + if (!AGENT_CONFIG_FILE_PATH.test(rel)) { + return { ok: false, reason: 'invalid' } + } + const read = await readItemFile(resolved, entry.name) + if (read === 'too-large') { + return { ok: false, reason: 'too-large' } + } + if (read === 'withheld') { + if (rel === SKILL_FILE) { + return { ok: false, reason: 'secret' } + } + withheld += 1 + continue + } + bytes += read.bytes.length + files.push({ path: rel, executable: read.executable, bytes: read.bytes }) + if ( + files.length > AGENT_CONFIG_LIMITS.filesPerItem || + bytes > AGENT_CONFIG_LIMITS.itemBytes + ) { + return { ok: false, reason: 'too-large' } + } + } + return null + } + const failed = await visit(dir, 0) + return failed ?? { ok: true, files, withheld, bytes } +} + +async function isDirectory(path: string): Promise { + return (await stat(path).catch(() => null))?.isDirectory() === true +} + +async function isFile(path: string): Promise { + return (await stat(path).catch(() => null))?.isFile() === true +} + +async function readSkills( + root: string, + kind: AgentConfigItemKind, + scope: AgentConfigItemScope +): Promise { + const entries = await readdir(root, { withFileTypes: true }).catch(() => []) + const items: LocalAgentConfigItem[] = [] + for (const entry of entries) { + const dir = join(root, entry.name) + // Hidden folders hold tool state (Codex's .system skills, trash), not the user's skills. + if (entry.name.startsWith('.') || !(await isDirectory(dir))) { + continue + } + if (!(await isFile(join(dir, SKILL_FILE)))) { + continue + } + const base = { scope, kind, name: entry.name, withheldFiles: 0 } + if (!AGENT_CONFIG_SKILL_NAME.test(entry.name)) { + items.push({ + ...base, + files: [], + fileCount: 0, + bytes: 0, + digest: null, + skipReason: 'invalid' + }) + continue + } + const walked = await walkSkill(dir).catch((): Walked => ({ ok: false, reason: 'invalid' })) + if (!walked.ok) { + items.push({ + ...base, + files: [], + fileCount: 0, + bytes: 0, + digest: null, + skipReason: walked.reason + }) + continue + } + items.push({ + ...base, + files: walked.files, + fileCount: walked.files.length, + bytes: walked.bytes, + withheldFiles: walked.withheld, + digest: agentConfigDigest(walked.files) + }) + } + return items +} + +/** Markdown commands, namespaced by folder (Claude) or flat (Codex prompts). */ +async function readCommands( + root: string, + kind: AgentConfigItemKind, + scope: AgentConfigItemScope +): Promise { + const maxDepth = kind === 'codex-prompt' ? 0 : 2 + const items: LocalAgentConfigItem[] = [] + const visit = async (dir: string, depth: number): Promise => { + const entries = await readdir(dir, { withFileTypes: true }).catch(() => []) + for (const entry of entries) { + if (entry.name.startsWith('.')) { + continue + } + const path = join(dir, entry.name) + const info = await stat(path).catch(() => null) + if (info?.isDirectory()) { + if (depth < maxDepth) { + await visit(path, depth + 1) + } + continue + } + if (!info?.isFile() || !entry.name.endsWith('.md')) { + continue + } + const name = relative(root, path).split(sep).join('/').slice(0, -'.md'.length) + const base = { scope, kind, name, withheldFiles: 0, fileCount: 1 } + const skipped = ( + skipReason: NonNullable + ): LocalAgentConfigItem => ({ + ...base, + files: [], + bytes: info.size, + digest: null, + skipReason + }) + if (!AGENT_CONFIG_COMMAND_NAME.test(name)) { + items.push(skipped('invalid')) + continue + } + const read = await readItemFile(path, entry.name).catch(() => 'invalid' as const) + if (read === 'too-large' || read === 'invalid') { + items.push(skipped(read)) + continue + } + if (read === 'withheld') { + items.push(skipped('secret')) + continue + } + const files = [ + { path: AGENT_CONFIG_SELF_PATH, executable: false, bytes: read.bytes } // commands are never run + ] + items.push({ ...base, files, bytes: read.bytes.length, digest: agentConfigDigest(files) }) + } + } + await visit(root, 0) + return items +} + +/** Repo-relative path of an item, as `git ls-files` prints it. */ +function repoRelative(repoPath: string, root: string, kind: AgentConfigItemKind, name: string) { + const rel = relative(repoPath, root).split(sep).join('/') + return isSkillKind(kind) ? `${rel}/${name}/` : `${rel}/${name}.md` +} + +/** This computer's Claude Code and Codex skills and commands, user scope and the workspace's project. */ +export async function readLocalAgentConfig( + deps: LocalAgentConfigReadDeps +): Promise { + const items: LocalAgentConfigItem[] = [] + for (const kind of AgentConfigItemKind.options) { + const root = agentConfigRoot(kind, 'user', deps.homes, null) + if (root) { + items.push(...(await (isSkillKind(kind) ? readSkills : readCommands)(root, kind, 'user'))) + } + } + const repoPath = deps.repoPath + if (repoPath) { + const tracked = await deps.trackedPaths(repoPath).catch(() => null) + for (const kind of AgentConfigItemKind.options) { + const root = AGENT_CONFIG_PROJECT_KINDS.has(kind) + ? agentConfigRoot(kind, 'project', deps.homes, repoPath) + : null + // A project folder that is a link elsewhere is not the repo's; leave it alone. + if (!root || (await lstat(root).catch(() => null))?.isSymbolicLink()) { + continue + } + for (const item of await (isSkillKind(kind) ? readSkills : readCommands)( + root, + kind, + 'project' + )) { + const path = repoRelative(repoPath, root, kind, item.name) + // Committed items reach the sandbox with the clone; unknown means assume committed. + const inRepo = + tracked === null || + [...tracked].some((file) => (isSkillKind(kind) ? file.startsWith(path) : file === path)) + items.push( + inRepo && !item.skipReason + ? { ...item, files: [], digest: null, skipReason: 'in-repo' } + : item + ) + } + } + } + return items +} diff --git a/src/main/agent-config-sync/desktop/syncer-id.ts b/src/main/agent-config-sync/desktop/syncer-id.ts new file mode 100644 index 00000000000..11d62650060 --- /dev/null +++ b/src/main/agent-config-sync/desktop/syncer-id.ts @@ -0,0 +1,37 @@ +import { randomBytes } from 'node:crypto' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { writeFileAtomically } from '../../filesystem/atomic-file-publication' + +// One read per profile; concurrent first syncs share it, so they can't mint two ids. +const cache = new Map>() + +async function load(userDataPath: string): Promise { + const path = join(userDataPath, 'mcp-sync-syncer-id') + try { + const stored = (await readFile(path, 'utf8')).trim() + if (/^[a-f0-9]{16}$/.test(stored)) { + return stored + } + } catch { + // First sync from this computer. + } + const id = randomBytes(8).toString('hex') + try { + writeFileAtomically(path, `${id}\n`) + } catch { + // Unwritable profile: this run still syncs as itself; the next launch gets a new id. + } + return id +} + +/** This computer's stable sync identity (random, not a device fingerprint). The host keeps one + * ledger per syncer, so two computers syncing one sandbox never remove each other's items. */ +export function readOrCreateSyncerId(userDataPath: string): Promise { + let id = cache.get(userDataPath) + if (!id) { + id = load(userDataPath) + cache.set(userDataPath, id) + } + return id +} diff --git a/src/main/agent-config-sync/host/host-agent-config-ledger.ts b/src/main/agent-config-sync/host/host-agent-config-ledger.ts new file mode 100644 index 00000000000..9242f4c3a46 --- /dev/null +++ b/src/main/agent-config-sync/host/host-agent-config-ledger.ts @@ -0,0 +1,74 @@ +import { runProcess } from '@orca/process-host' +import { appendFile, mkdir, readFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { writeFileAtomically } from '../../filesystem/atomic-file-publication' + +/** What this host last wrote for one syncing computer: item key -> digest. Never contents. */ +export type Ledger = { version: 1; items: Record } + +export function ledgerPath(ledgerDir: string, syncer: string): string { + return join(ledgerDir, `agent-config-sync-ledger-${syncer}.json`) +} + +export async function readLedger(path: string): Promise { + try { + const parsed: unknown = JSON.parse(await readFile(path, 'utf8')) + const items = + parsed && typeof parsed === 'object' && 'items' in parsed ? parsed.items : undefined + const clean: Record = {} + if (items && typeof items === 'object') { + for (const [key, value] of Object.entries(items)) { + if (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)) { + clean[key] = value + } + } + } + return { version: 1, items: clean } + } catch { + return { version: 1, items: {} } + } +} + +export async function writeLedger(path: string, ledger: Ledger): Promise { + await mkdir(dirname(path), { recursive: true }) + writeFileAtomically(path, `${JSON.stringify(ledger, null, 2)}\n`, { mode: 0o600 }) +} + +/** Keeps a synced project item out of the sandbox's git status (local exclude, never committed). */ +export async function excludeFromGit( + projectPath: string, + dest: string, + isDir: boolean +): Promise { + try { + const { code, stdout } = await runProcess({ + program: 'git', + args: [ + '-C', + projectPath, + 'rev-parse', + '--path-format=absolute', + '--git-path', + 'info/exclude' + ], + timeoutMs: 5_000 + }) + if (code !== 0) { + return + } + const excludePath = stdout.trim() + if (!excludePath) { + return + } + const rel = dest.slice(projectPath.length).split('\\').join('/') + const line = `${rel.startsWith('/') ? rel : `/${rel}`}${isDir ? '/' : ''}` + const current = await readFile(excludePath, 'utf8').catch(() => '') + if (current.split('\n').includes(line)) { + return + } + await mkdir(dirname(excludePath), { recursive: true }) + await appendFile(excludePath, `${current && !current.endsWith('\n') ? '\n' : ''}${line}\n`) + } catch { + // Not a git checkout here; the item still works, it just shows as untracked. + } +} diff --git a/src/main/agent-config-sync/host/host-agent-config-sync.test.ts b/src/main/agent-config-sync/host/host-agent-config-sync.test.ts new file mode 100644 index 00000000000..65f9949217e --- /dev/null +++ b/src/main/agent-config-sync/host/host-agent-config-sync.test.ts @@ -0,0 +1,143 @@ +import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { + AgentConfigSyncPlanParams, + AgentConfigSyncPutParams +} from '../../../shared/agent-config-sync/agent-config-sync-contract' +import { agentConfigDigest } from '../agent-config-digest' +import { + planHostAgentConfigSync, + putHostAgentConfig, + type HostAgentConfigSyncDeps +} from './host-agent-config-sync' + +let dir: string +let deps: HostAgentConfigSyncDeps + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'host-agent-config-')) + deps = { + homes: { home: dir, claudeDir: join(dir, '.claude'), codexDir: join(dir, '.codex') }, + projectPath: null, + ledgerDir: join(dir, 'userData') + } +}) + +afterEach(() => { + rmSync(dir, { recursive: true, force: true }) +}) + +const skillFiles = [{ path: 'SKILL.md', executable: false, bytes: Buffer.from('hello') }] +const digest = agentConfigDigest(skillFiles) +const payload = (patch: Record = {}) => ({ + scope: 'user' as const, + kind: 'claude-skill' as const, + name: 'hello', + digest, + files: [{ path: 'SKILL.md', executable: false, base64: Buffer.from('hello').toString('base64') }], + ...patch +}) + +describe('host agent config sync', () => { + it('rejects names and paths that could leave the agent folders', () => { + for (const name of ['../x', '.hidden', 'a/b', '']) { + expect( + AgentConfigSyncPlanParams.safeParse({ + syncer: 's', + items: [{ scope: 'user', kind: 'claude-skill', name, digest }] + }).success + ).toBe(false) + } + for (const path of ['../SKILL.md', '/etc/passwd', 'a/../../b', '.git/config']) { + expect( + AgentConfigSyncPutParams.safeParse({ + syncer: 's', + items: [payload({ files: [{ path, executable: false, base64: '' }] })] + }).success + ).toBe(false) + } + // Codex prompts and old Codex skills have no project scope. + expect( + AgentConfigSyncPlanParams.safeParse({ + syncer: 's', + items: [{ scope: 'project', kind: 'codex-prompt', name: 'x', digest }] + }).success + ).toBe(false) + }) + + it('refuses a payload that does not match its digest or lacks SKILL.md', async () => { + const result = await putHostAgentConfig( + { + syncer: 's', + items: [ + payload({ digest: '0'.repeat(64) }), + payload({ + name: 'nomain', + digest: agentConfigDigest([ + { path: 'other.md', executable: false, bytes: Buffer.from('x') } + ]), + files: [ + { path: 'other.md', executable: false, base64: Buffer.from('x').toString('base64') } + ] + }) + ] + }, + deps + ) + expect(result.items).toEqual({ + 'user:claude-skill:hello': 'invalid', + 'user:claude-skill:nomain': 'invalid' + }) + expect(existsSync(join(dir, '.claude', 'skills'))).toBe(false) + }) + + it('leaves a symlinked skill alone and keeps project items out without a workspace', async () => { + mkdirSync(join(dir, '.claude', 'skills'), { recursive: true }) + mkdirSync(join(dir, 'elsewhere')) + symlinkSync(join(dir, 'elsewhere'), join(dir, '.claude', 'skills', 'hello')) + const plan = await planHostAgentConfigSync( + { + syncer: 's', + items: [ + { scope: 'user', kind: 'claude-skill', name: 'hello', digest }, + { scope: 'project', kind: 'claude-skill', name: 'proj', digest } + ] + }, + deps + ) + expect(plan.items).toEqual({ + 'user:claude-skill:hello': 'kept-host', + 'project:claude-skill:proj': 'no-project' + }) + }) + + it('ignores ledger entries that do not name a valid item', async () => { + mkdirSync(deps.ledgerDir, { recursive: true }) + writeFileSync( + join(deps.ledgerDir, 'agent-config-sync-ledger-s.json'), + JSON.stringify({ version: 1, items: { 'user:claude-skill:../../victim': digest } }) + ) + mkdirSync(join(dir, 'victim')) + writeFileSync(join(dir, 'victim', 'SKILL.md'), 'hello') + const plan = await planHostAgentConfigSync({ syncer: 's', items: [] }, deps) + expect(plan.removed).toBe(0) + expect(existsSync(join(dir, 'victim', 'SKILL.md'))).toBe(true) + }) + + it('keeps each computer’s items separate', async () => { + await planHostAgentConfigSync( + { syncer: 'mac-a', items: [{ scope: 'user', kind: 'claude-skill', name: 'hello', digest }] }, + deps + ) + await putHostAgentConfig({ syncer: 'mac-a', items: [payload()] }, deps) + // Another computer that never sent it doesn't remove it. + const other = await planHostAgentConfigSync({ syncer: 'mac-b', items: [] }, deps) + expect(other.removed).toBe(0) + expect(existsSync(join(dir, '.claude', 'skills', 'hello', 'SKILL.md'))).toBe(true) + const own = await planHostAgentConfigSync({ syncer: 'mac-a', items: [] }, deps) + expect(own.removed).toBe(1) + expect(existsSync(join(dir, '.claude', 'skills', 'hello'))).toBe(false) + }) +}) diff --git a/src/main/agent-config-sync/host/host-agent-config-sync.ts b/src/main/agent-config-sync/host/host-agent-config-sync.ts new file mode 100644 index 00000000000..81a2c169543 --- /dev/null +++ b/src/main/agent-config-sync/host/host-agent-config-sync.ts @@ -0,0 +1,273 @@ +import { randomBytes } from 'node:crypto' +import { lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises' +import { dirname, isAbsolute, join, resolve } from 'node:path' +import { + AGENT_CONFIG_FILE_KINDS, + AGENT_CONFIG_LIMITS, + AGENT_CONFIG_SELF_PATH, + AgentConfigItemKind, + AgentConfigItemScope, + AgentConfigSyncPlanParams, + agentConfigItemKey, + isSkillKind, + type AgentConfigItemPayload, + type AgentConfigPlanOutcome, + type AgentConfigPutOutcome, + type AgentConfigSyncPlanResult, + type AgentConfigSyncPutParams, + type AgentConfigSyncPutResult +} from '../../../shared/agent-config-sync/agent-config-sync-contract' +import { writeFileAtomically } from '../../filesystem/atomic-file-publication' +import { excludeFromGit, ledgerPath, readLedger, writeLedger } from './host-agent-config-ledger' +import { agentConfigDigest, type AgentConfigDigestEntry } from '../agent-config-digest' +import { agentConfigItemPath, agentConfigRoot, type AgentConfigHomes } from '../agent-config-roots' + +export type HostAgentConfigSyncDeps = { + homes: AgentConfigHomes + /** The host workspace's checkout (ORCA_WORKSPACE_PATH); project items go there. */ + projectPath: string | null + /** Folder for this host's per-computer ledgers. */ + ledgerDir: string +} + +type ItemId = { scope: AgentConfigItemScope; kind: AgentConfigItemKind; name: string } + +function parseKey(key: string): ItemId | null { + const [scope, kind, ...rest] = key.split(':') + const parsedScope = AgentConfigItemScope.safeParse(scope) + const parsedKind = AgentConfigItemKind.safeParse(kind) + const name = rest.join(':') + if (!parsedScope.success || !parsedKind.success || !name) { + return null + } + // Same checks as a fresh request, so a tampered ledger can't name a path outside the roots. + const checked = AgentConfigSyncPlanParams.safeParse({ + syncer: 'ledger', + items: [{ scope, kind, name, digest: '0'.repeat(64) }] + }) + return checked.success ? { scope: parsedScope.data, kind: parsedKind.data, name } : null +} + +function destinationOf(item: ItemId, deps: HostAgentConfigSyncDeps): string | null { + const root = agentConfigRoot(item.kind, item.scope, deps.homes, deps.projectPath) + return root ? agentConfigItemPath(root, item.kind, item.name) : null +} + +/** Digest of what is on disk now: null when absent, 'foreign' for anything not a plain copy. */ +async function digestOnDisk(path: string, kind: AgentConfigItemKind): Promise { + const info = await lstat(path).catch(() => null) + if (!info) { + return null + } + if (info.isSymbolicLink()) { + return 'foreign' + } + if (AGENT_CONFIG_FILE_KINDS.has(kind)) { + if (!info.isFile()) { + return 'foreign' + } + return agentConfigDigest([ + { path: AGENT_CONFIG_SELF_PATH, executable: false, bytes: await readFile(path) } + ]) + } + if (!info.isDirectory()) { + return 'foreign' + } + const entries: AgentConfigDigestEntry[] = [] + const visit = async (dir: string, prefix: string): Promise => { + for (const entry of await readdir(dir, { withFileTypes: true })) { + const rel = prefix ? `${prefix}/${entry.name}` : entry.name + const full = join(dir, entry.name) + if (entry.isDirectory()) { + if (!(await visit(full, rel))) { + return false + } + } else if (entry.isFile()) { + const stat = await lstat(full) + entries.push({ + path: rel, + executable: (stat.mode & 0o111) !== 0, + bytes: await readFile(full) + }) + if (entries.length > AGENT_CONFIG_LIMITS.filesPerItem * 2) { + return false + } + } else { + return false + } + } + return true + } + try { + return (await visit(path, '')) ? agentConfigDigest(entries) : 'foreign' + } catch { + return 'foreign' + } +} + +/** Decides each item before any bytes move, and removes what this computer stopped sending. */ +export async function planHostAgentConfigSync( + params: AgentConfigSyncPlanParams, + deps: HostAgentConfigSyncDeps +): Promise { + const path = ledgerPath(deps.ledgerDir, params.syncer) + const ledger = await readLedger(path) + const items: Record = {} + const wanted = new Set() + for (const item of params.items) { + const key = agentConfigItemKey(item.scope, item.kind, item.name) + wanted.add(key) + const dest = destinationOf(item, deps) + if (!dest) { + items[key] = 'no-project' + continue + } + const onDisk = await digestOnDisk(dest, item.kind) + if (onDisk === null) { + items[key] = 'needed' + } else if (onDisk === item.digest) { + items[key] = 'unchanged' + ledger.items[key] = item.digest + } else if (ledger.items[key] === onDisk) { + items[key] = 'needed' + } else { + // Made or edited in the sandbox: it's the user's now. + items[key] = 'kept-host' + delete ledger.items[key] + } + } + let removed = 0 + for (const [key, digest] of Object.entries(ledger.items)) { + if (wanted.has(key)) { + continue + } + delete ledger.items[key] + const id = parseKey(key) + const dest = id ? destinationOf(id, deps) : null + // Only an untouched copy goes; an edited one stays as the user's. + if (id && dest && (await digestOnDisk(dest, id.kind)) === digest) { + await rm(dest, { recursive: true, force: true }) + removed += 1 + } + } + await writeLedger(path, ledger) + return { items, removed } +} + +function decodeFiles(item: AgentConfigItemPayload): AgentConfigDigestEntry[] | null { + const isFileKind = AGENT_CONFIG_FILE_KINDS.has(item.kind) + if (isFileKind && (item.files.length !== 1 || item.files[0].path !== AGENT_CONFIG_SELF_PATH)) { + return null + } + const paths = new Set() + const entries: AgentConfigDigestEntry[] = [] + let total = 0 + for (const file of item.files) { + if ((!isFileKind && file.path === AGENT_CONFIG_SELF_PATH) || paths.has(file.path)) { + return null + } + paths.add(file.path) + const bytes = Buffer.from(file.base64, 'base64') + total += bytes.length + if (bytes.length > AGENT_CONFIG_LIMITS.fileBytes || total > AGENT_CONFIG_LIMITS.itemBytes) { + return null + } + entries.push({ path: file.path, executable: !isFileKind && file.executable, bytes }) + } + if (!isFileKind && !paths.has('SKILL.md')) { + return null + } + return agentConfigDigest(entries) === item.digest ? entries : null +} + +async function writeItem( + dest: string, + kind: AgentConfigItemKind, + files: AgentConfigDigestEntry[] +): Promise { + const parent = dirname(dest) + await mkdir(parent, { recursive: true }) + const tag = randomBytes(6).toString('hex') + if (AGENT_CONFIG_FILE_KINDS.has(kind)) { + writeFileAtomically(dest, files[0].bytes, { mode: 0o644 }) + return + } + // Built beside the target, then swapped in, so an agent never reads half a skill. + const staged = join(parent, `.orca-sync-${tag}`) + try { + for (const file of files) { + const target = resolve(staged, file.path) + if (isAbsolute(file.path) || !target.startsWith(`${staged}/`)) { + throw new Error('Path escapes the skill folder.') + } + await mkdir(dirname(target), { recursive: true }) + await writeFile(target, file.bytes, { mode: file.executable ? 0o755 : 0o644 }) + } + const old = join(parent, `.orca-sync-old-${tag}`) + const existed = await lstat(dest).then( + () => true, + () => false + ) + if (existed) { + await rename(dest, old) + } + await rename(staged, dest) + if (existed) { + await rm(old, { recursive: true, force: true }) + } + } finally { + await rm(staged, { recursive: true, force: true }) + } +} + +/** Writes items the plan asked for. Rechecks ownership, so a file edited since the plan stays. */ +export async function putHostAgentConfig( + params: AgentConfigSyncPutParams, + deps: HostAgentConfigSyncDeps +): Promise { + const path = ledgerPath(deps.ledgerDir, params.syncer) + const ledger = await readLedger(path) + const items: Record = {} + for (const item of params.items) { + const key = agentConfigItemKey(item.scope, item.kind, item.name) + const id = parseKey(key) + const files = id ? decodeFiles(item) : null + if (!id || !files) { + items[key] = 'invalid' + continue + } + const dest = destinationOf(id, deps) + if (!dest) { + items[key] = 'no-project' + continue + } + try { + const onDisk = await digestOnDisk(dest, id.kind) + if (onDisk !== null && onDisk !== item.digest && ledger.items[key] !== onDisk) { + items[key] = 'kept-host' + continue + } + if (onDisk !== item.digest) { + await writeItem(dest, id.kind, files) + } + if (id.scope === 'project' && deps.projectPath) { + await excludeFromGit(deps.projectPath, dest, isSkillKind(id.kind)) + } + ledger.items[key] = item.digest + items[key] = onDisk === null ? 'added' : 'updated' + } catch { + items[key] = 'failed' + } + } + await writeLedger(path, ledger) + const counts = Object.values(items).reduce>((acc, outcome) => { + acc[outcome] = (acc[outcome] ?? 0) + 1 + return acc + }, {}) + console.info( + `[agent-config-sync] ${Object.entries(counts) + .map(([outcome, n]) => `${outcome}=${n}`) + .join(',')}` + ) + return { items } +} diff --git a/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts b/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts index 34056e67a44..da47d8e9391 100644 --- a/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts +++ b/src/main/agent-mcp-sync/desktop/cloud-mcp-sync.ts @@ -1,4 +1,3 @@ -import { randomBytes } from 'node:crypto' import { readFileSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' @@ -18,6 +17,7 @@ import { environmentHandleFromRecipeResult } from '../../environment-providers/e import { HOSTED_SANDBOX_DRIVER_ID } from '../../hosted-sandbox/hosted-sandbox-driver' import { readLocalMcpConfig, type LocalMcpConfig } from './local-mcp-config-read' import type { CloudMcpEgress } from './cloud-mcp-egress' +import { readOrCreateSyncerId } from '../../agent-config-sync/desktop/syncer-id' const SYNC_TIMEOUT_MS = 30_000 const MAX_EXCLUDED = 512 @@ -146,30 +146,7 @@ export function createCloudMcpSync(deps: CloudMcpSyncDeps): CloudMcpSync { } } - let syncer: string | null = null - /** This computer's stable sync identity (random, not a device fingerprint). */ - function syncerId(): string { - if (syncer) { - return syncer - } - const path = join(deps.userDataPath, 'mcp-sync-syncer-id') - try { - const stored = readFileSync(path, 'utf8').trim() - if (/^[a-f0-9]{16}$/.test(stored)) { - syncer = stored - return stored - } - } catch { - // First sync from this computer. - } - syncer = randomBytes(8).toString('hex') - try { - writeFileAtomically(path, `${syncer}\n`) - } catch { - // Unwritable profile: this run still syncs as itself; the next launch gets a new id. - } - return syncer - } + const syncerId = (): Promise => readOrCreateSyncerId(deps.userDataPath) async function plan(environmentId: string) { const runtime = cloudRuntime(environmentId) @@ -180,7 +157,7 @@ export function createCloudMcpSync(deps: CloudMcpSyncDeps): CloudMcpSync { repoServerNames: local.repoServerNames, homeDir: homedir() }) - return { ...planned, params: { ...planned.params, syncer: syncerId() } } + return { ...planned, params: { ...planned.params, syncer: await syncerId() } } } function publish(status: McpSyncStatus): McpSyncStatus { diff --git a/src/main/cloud-workspaces/cloud-pairing-prune.test.ts b/src/main/cloud-workspaces/cloud-pairing-prune.test.ts new file mode 100644 index 00000000000..9864a7a340d --- /dev/null +++ b/src/main/cloud-workspaces/cloud-pairing-prune.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, it, vi } from 'vitest' +import { + createCloudPairingPrune, + type CloudPairingBindings, + type CloudSandboxPresence +} from './cloud-pairing-prune' + +const A = 'sbx_aaaaaaaaaaaaaaaaaaaaaaaa' +const B = 'sbx_bbbbbbbbbbbbbbbbbbbbbbbb' + +function setup(options: { + bindings: CloudPairingBindings + listed?: string[] | null + presence?: Record + account?: () => string | null +}) { + let bindings = structuredClone(options.bindings) + const removed: string[] = [] + const presence = vi.fn(async (id: string) => options.presence?.[id] ?? 'unknown') + const listVisible = vi.fn(async () => + options.listed === null ? null : new Set(options.listed ?? []) + ) + let clock = 0 + const prune = createCloudPairingPrune({ + activeAccountId: options.account ?? (() => 'team-1'), + readBindings: async () => structuredClone(bindings), + updateBindings: async (change) => { + bindings = change(structuredClone(bindings)) + }, + listVisible, + presence, + removeEnvironment: async (id) => { + removed.push(id) + }, + now: () => clock + }) + return { + prune, + removed, + presence, + listVisible, + bindings: () => bindings, + advance: (ms: number) => { + clock += ms + } + } +} + +describe('cloud pairing prune (LC-1)', () => { + it('drops a pairing missing from the list once one more fetch confirms the sandbox is gone', async () => { + const t = setup({ + bindings: { + [A]: { environmentId: 'env-a', grantId: null, accountId: 'team-1' }, + [B]: { environmentId: 'env-b', grantId: null, accountId: 'team-1' } + }, + listed: [B], + presence: { [A]: 'gone' } + }) + await t.prune.run({ force: true }) + expect(t.presence).toHaveBeenCalledWith(A) + expect(t.presence).not.toHaveBeenCalledWith(B) + expect(t.removed).toEqual(['env-a']) + expect(Object.keys(t.bindings())).toEqual([B]) + }) + + it('a failed list never drops anything (network blip)', async () => { + const t = setup({ + bindings: { [A]: { environmentId: 'env-a', grantId: null, accountId: 'team-1' } }, + listed: null, + presence: { [A]: 'gone' } + }) + await t.prune.run({ force: true }) + expect(t.presence).not.toHaveBeenCalled() + expect(t.removed).toEqual([]) + }) + + it('keeps a pairing when the confirming fetch fails or finds the sandbox', async () => { + for (const answer of ['unknown', 'present'] as const) { + const t = setup({ + bindings: { [A]: { environmentId: 'env-a', grantId: null, accountId: 'team-1' } }, + listed: [], + presence: { [A]: answer } + }) + await t.prune.run({ force: true }) + expect(t.removed).toEqual([]) + expect(Object.keys(t.bindings())).toEqual([A]) + } + }) + + it("leaves another team's pairings alone", async () => { + const t = setup({ + bindings: { [A]: { environmentId: 'env-a', grantId: null, accountId: 'team-2' } }, + listed: [], + presence: { [A]: 'gone' } + }) + await t.prune.run({ force: true }) + expect(t.listVisible).not.toHaveBeenCalled() + expect(t.removed).toEqual([]) + }) + + it('keeps everything when the team switches mid-check', async () => { + let account = 'team-1' + const t = setup({ + bindings: { [A]: { environmentId: 'env-a', grantId: null, accountId: 'team-1' } }, + listed: [], + presence: { [A]: 'gone' }, + account: () => account + }) + t.presence.mockImplementation(async () => { + account = 'team-2' + return 'gone' + }) + await t.prune.run({ force: true }) + expect(t.removed).toEqual([]) + }) + + it('stamps older bindings with the team that lists them', async () => { + const t = setup({ + bindings: { [A]: { environmentId: 'env-a', grantId: null } }, + listed: [A] + }) + await t.prune.run({ force: true }) + expect(t.bindings()[A]?.accountId).toBe('team-1') + expect(t.removed).toEqual([]) + }) + + it('forget drops the pairing now, keeping a server another binding still uses', async () => { + const t = setup({ + bindings: { + [A]: { environmentId: 'env-shared', grantId: null, accountId: 'team-1' }, + [B]: { environmentId: 'env-shared', grantId: null, accountId: 'team-1' } + } + }) + await t.prune.forget(A) + expect(t.removed).toEqual([]) + await t.prune.forget(B) + expect(t.removed).toEqual(['env-shared']) + expect(t.bindings()).toEqual({}) + }) + + it('throttles list-triggered runs; a forced run always goes', async () => { + const t = setup({ + bindings: { [A]: { environmentId: 'env-a', grantId: null, accountId: 'team-1' } }, + listed: [A] + }) + await t.prune.run() + await t.prune.run() + expect(t.listVisible).toHaveBeenCalledTimes(1) + await t.prune.run({ force: true }) + expect(t.listVisible).toHaveBeenCalledTimes(2) + t.advance(60_000) + await t.prune.run() + expect(t.listVisible).toHaveBeenCalledTimes(3) + }) +}) diff --git a/src/main/cloud-workspaces/cloud-pairing-prune.ts b/src/main/cloud-workspaces/cloud-pairing-prune.ts new file mode 100644 index 00000000000..23213384bfb --- /dev/null +++ b/src/main/cloud-workspaces/cloud-pairing-prune.ts @@ -0,0 +1,137 @@ +// Drops this device's pairing with a cloud workspace whose sandbox no longer exists (LC-1). Opening +// a workspace this desktop does not own pairs it as a " (cloud)" server, and that server's +// projects mirror into the sidebar. Once the sandbox was deleted (from Home, another desktop, the +// control plane), the server, its struck-out host row and its projects stayed forever. +// +// Only an authoritative answer drops one: missing from the active team's successful list, then +// confirmed by one more fetch of that sandbox answering not found or destroyed. A failed list, a +// failed or ambiguous confirm, or a team switch mid-check keeps everything, so a network blip never +// wipes a pairing. (Owned workspaces are retired by cloud-sandbox-gone-prune; this is the pairing +// half.) + +export type CloudPairingBinding = { + environmentId: string + grantId: string | null + /** The team the sandbox belongs to; absent on bindings saved before LC-1. */ + accountId?: string | null +} + +export type CloudPairingBindings = Record + +/** What one fetch of a sandbox said: only `gone` (not found, or destroyed) lets a pairing go. */ +export type CloudSandboxPresence = 'gone' | 'present' | 'unknown' + +export type CloudPairingPrune = { + /** Startup and each cloud list refresh. Single-flight; list-triggered runs are throttled. */ + run(options?: { force?: boolean }): Promise + /** The sandbox was deleted from here: drop its pairing now, no fetch needed. */ + forget(sandboxId: string): Promise + /** A pairing was just saved: stamp it with the active team. */ + accountForNewBinding(): string | null +} + +export function createCloudPairingPrune(deps: { + activeAccountId: () => string | null + readBindings: () => Promise + updateBindings: (change: (current: CloudPairingBindings) => CloudPairingBindings) => Promise + /** Ids of every sandbox the active team's list shows this user; null when the list failed. */ + listVisible: () => Promise | null> + /** One fetch of a single sandbox. */ + presence: (sandboxId: string) => Promise + /** Remove the paired server; the window's catalog refresh then purges its projects. */ + removeEnvironment: (environmentId: string) => Promise + minIntervalMs?: number + now?: () => number + log?: (line: string) => void +}): CloudPairingPrune { + const now = deps.now ?? Date.now + const minIntervalMs = deps.minIntervalMs ?? 60_000 + let lastRunAt = Number.NEGATIVE_INFINITY + let running: Promise | null = null + + async function forget(sandboxId: string): Promise { + let dropped: CloudPairingBinding | undefined + let stillUsed = false + await deps.updateBindings((current) => { + dropped = current[sandboxId] + if (!dropped) { + return current + } + const next = { ...current } + delete next[sandboxId] + stillUsed = Object.values(next).some((b) => b.environmentId === dropped?.environmentId) + return next + }) + if (dropped && !stillUsed) { + await deps.removeEnvironment(dropped.environmentId) + } + } + + async function prune(): Promise { + const account = deps.activeAccountId() + if (!account) { + return + } + const bindings = await deps.readBindings() + // Another team's pairing is not this list's to judge. Unstamped ones are judged by the confirm. + const candidates = Object.entries(bindings).filter( + ([, binding]) => !binding.accountId || binding.accountId === account + ) + if (candidates.length === 0) { + return + } + const listed = await deps.listVisible() + if (!listed || deps.activeAccountId() !== account) { + return + } + // Listed means it is this team's: stamp older bindings so later team switches leave them be. + const unstampedListed = candidates.filter(([id, b]) => !b.accountId && listed.has(id)) + if (unstampedListed.length > 0) { + await deps.updateBindings((current) => { + const next = { ...current } + for (const [id] of unstampedListed) { + if (next[id] && !next[id].accountId) { + next[id] = { ...next[id], accountId: account } + } + } + return next + }) + } + for (const [sandboxId] of candidates) { + if (listed.has(sandboxId)) { + continue + } + const presence = await deps.presence(sandboxId) + // The confirming answer must still be for the team the list was for. + if (presence !== 'gone' || deps.activeAccountId() !== account) { + continue + } + try { + await forget(sandboxId) + deps.log?.(`[cloud-workspaces] dropped the pairing with ${sandboxId}: sandbox is gone`) + } catch (error) { + deps.log?.(`[cloud-workspaces] could not drop a gone sandbox's pairing: ${String(error)}`) + } + } + } + + return { + run(options) { + if (running) { + return running + } + if (!options?.force && now() - lastRunAt < minIntervalMs) { + return Promise.resolve() + } + lastRunAt = now() + running = prune() + .catch((error) => deps.log?.(`[cloud-workspaces] pairing prune failed: ${String(error)}`)) + .finally(() => { + running = null + }) + return running + }, + forget, + accountForNewBinding: () => deps.activeAccountId() + } +} diff --git a/src/main/hosted-sandbox/hosted-sandbox-install.ts b/src/main/hosted-sandbox/hosted-sandbox-install.ts index 97de012ff10..ffc04efd2b4 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-install.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-install.ts @@ -61,6 +61,10 @@ import { installCloudMcpSync, registerCloudMcpSyncHandlers } from '../agent-mcp-sync/desktop/cloud-mcp-sync-ipc' +import { + installCloudAgentConfigSync, + registerCloudAgentConfigSyncHandlers +} from '../agent-config-sync/desktop/cloud-agent-config-sync-ipc' /** Capability Orca Cloud auth grants per account (stablyai/orca-cloud#689). */ export const ORCA_CLOUD_SANDBOX_CAPABILITY = 'sandbox' @@ -87,6 +91,7 @@ export function installHostedSandbox( restartHostedWorkspace(args.workspaceId) ) registerCloudMcpSyncHandlers() + registerCloudAgentConfigSyncHandlers() const userDataPath = app.getPath('userData') const config = getHostedSandboxConfig( userDataPath, @@ -121,6 +126,7 @@ export function installHostedSandbox( baseUrl: config.controlPlaneUrl, getAccessToken: config.getAccessToken }) + const agentConfigSync = installCloudAgentConfigSync(userDataPath) // Dev rehearsals shorten idle sleep; packaged builds always use the provider's default. const idleOverride = app.isPackaged ? Number.NaN @@ -147,7 +153,11 @@ export function installHostedSandbox( userDataPath, driver, windows: () => BrowserWindow.getAllWindows(), - onConnected: (runtimeEnvironmentId) => void mcpSync.sync(runtimeEnvironmentId, 'connect'), + // Create and wake both connect: MCP servers, skills and commands follow this computer's. + onConnected: (runtimeEnvironmentId) => { + void mcpSync.sync(runtimeEnvironmentId, 'connect') + void agentConfigSync.sync(runtimeEnvironmentId, 'connect') + }, onRunningChange: (anyRunning) => usageRefresh.setRunning(anyRunning), activeAccountId }) diff --git a/src/main/hosted-sandbox/remote-desktop-guest.test.ts b/src/main/hosted-sandbox/remote-desktop-guest.test.ts index e7ca3436614..c890b016f2b 100644 --- a/src/main/hosted-sandbox/remote-desktop-guest.test.ts +++ b/src/main/hosted-sandbox/remote-desktop-guest.test.ts @@ -175,7 +175,7 @@ describe('remote desktop page driver', () => { failMint('asleep') guest.ask('ticket') await flush() - expect(guest.calls.at(-2)).toContain('This sandbox is asleep.') + expect(guest.calls.at(-2)).toContain('This workspace is asleep.') // Open remote desktop again: main wakes the paused page. registerRemoteDesktopSession( { diff --git a/src/main/hosted-sandbox/remote-desktop-pause-copy.ts b/src/main/hosted-sandbox/remote-desktop-pause-copy.ts index bd50b2619d0..65056218d02 100644 --- a/src/main/hosted-sandbox/remote-desktop-pause-copy.ts +++ b/src/main/hosted-sandbox/remote-desktop-pause-copy.ts @@ -7,7 +7,7 @@ export function remoteDesktopPauseMessage(reason: RemoteDesktopPauseReason): str case 'asleep': return translateMain( 'components.cloudRemoteDesktop.pageAsleep', - 'This sandbox is asleep. Wake it in Orca, then reconnect.' + 'This workspace is asleep. Wake it in Orca, then reconnect.' ) case 'archived': return translateMain( @@ -17,7 +17,7 @@ export function remoteDesktopPauseMessage(reason: RemoteDesktopPauseReason): str case 'starting': return translateMain( 'components.cloudRemoteDesktop.pageStarting', - 'The sandbox is starting or waking. Reconnect in a moment.' + 'The workspace is starting or waking. Reconnect in a moment.' ) case 'signed_out': return translateMain( diff --git a/src/main/ipc/cloud-workspaces-pairings.ts b/src/main/ipc/cloud-workspaces-pairings.ts new file mode 100644 index 00000000000..fa38b90e24e --- /dev/null +++ b/src/main/ipc/cloud-workspaces-pairings.ts @@ -0,0 +1,141 @@ +// This device's pairings with cloud workspaces it does not own (the " (cloud)" servers made +// by Open), the file that binds them to their sandboxes, and the prune that drops a pairing once its +// sandbox is gone (LC-1). Split from cloud-workspaces.ts, which registers the IPC handlers. +import { readFile, rename, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { app } from 'electron' +import { z } from 'zod' +import type { CloudWorkspacesService } from '../cloud-workspaces/cloud-workspaces-service' +import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' +import { orcaCloudAccountId } from '../../shared/hosted-sandbox/orca-cloud-account' +import { + listEnvironments, + removeEnvironment +} from '../../shared/remote-runtime/host-store/runtime-environment-store' +import { + createCloudPairingPrune, + type CloudPairingPrune, + type CloudSandboxPresence +} from '../cloud-workspaces/cloud-pairing-prune' +import { + retireRemovedRuntimeEnvironment, + type RemovedServerStore +} from './runtime-environments/runtime-environment-removal-cleanup' +import { invalidateRuntimeEnvironmentTransport } from './runtime-environments/runtime-environments' +import { publishRuntimeEnvironmentCatalogChanged } from './runtime-environments/runtime-environment-catalog-broadcast' + +const Id = z.string().regex(/^sbx_[0-9a-f]{24}$/) +const GrantId = z.string().regex(/^grt_[0-9a-f]{24}$/) + +type GetService = () => Promise + +export type CloudWorkspacesPairings = { + prune: CloudPairingPrune + readBindings: () => Promise> + updateBindings: ( + change: (current: Record) => Record + ) => Promise +} + +const bindingsFile = () => join(app.getPath('userData'), 'cloud-workspaces-environments.json') + +type Binding = { environmentId: string; grantId: string | null; accountId?: string | null } + +export const CloudEnvironmentId = z.string().min(1).max(256) +// Older builds stored the bare environment id; read it as a binding with an unknown grant. +const StoredBinding = z.union([ + CloudEnvironmentId.transform((environmentId): Binding => ({ environmentId, grantId: null })), + z.object({ + environmentId: CloudEnvironmentId, + grantId: GrantId.nullable(), + accountId: z.string().min(1).max(256).nullable().optional() + }) +]) + +async function readBindings(): Promise> { + try { + const parsed = z + .record(Id, StoredBinding) + .safeParse(JSON.parse(await readFile(bindingsFile(), 'utf8'))) + return parsed.success ? parsed.data : {} + } catch { + return {} + } +} + +// Read-modify-write updates run one at a time so two quick pairings cannot drop each other. +let bindingsWrite: Promise = Promise.resolve() + +/** Temp file + rename so a crash mid-write never leaves a truncated bindings file. */ +function updateBindings( + change: (current: Record) => Record +): Promise { + bindingsWrite = bindingsWrite + .catch(() => undefined) + .then(async () => { + const file = bindingsFile() + const temp = `${file}.${process.pid}.tmp` + await writeFile(temp, JSON.stringify(change(await readBindings())), { mode: 0o600 }) + await rename(temp, file) + }) + return bindingsWrite +} + +let pairings: CloudWorkspacesPairings | null = null +export const STARTUP_PRUNE_DELAY_MS = 15_000 + +/** One fetch of a sandbox: not found (deleted, or never visible) or destroyed means gone. */ +async function sandboxPresence(getService: GetService, id: string): Promise { + const s = await getService().catch(() => null) + const result = await s?.get(id) + if (!result) { + return 'unknown' + } + if (result.ok) { + return result.value.status === 'destroyed' ? 'gone' : 'present' + } + return result.status === 404 && result.error === 'not_found' ? 'gone' : 'unknown' +} + +/** The pairing prune for this process; servers it drops are retired like a Settings removal. */ +export function createCloudWorkspacesPairings( + getService: GetService, + removedServerStore: RemovedServerStore | undefined +): CloudWorkspacesPairings { + if (pairings) { + return pairings + } + const prune = createCloudPairingPrune({ + activeAccountId: () => + orcaCloudAccountId(ensureActiveOrcaProfile(app.getPath('userData')).profile.cloud), + readBindings, + updateBindings, + listVisible: async () => { + const s = await getService().catch(() => null) + // Everything this user can see in the team, archived and routine runs included. + const result = await s?.list({ scope: 'team', archived: 'include', routines: 'include' }) + return result?.ok ? new Set(result.value.map((w) => w.id)) : null + }, + presence: (id) => sandboxPresence(getService, id), + removeEnvironment: async (environmentId) => { + const userDataPath = app.getPath('userData') + if (!listEnvironments(userDataPath).some((e) => e.id === environmentId)) { + return + } + removeEnvironment(userDataPath, environmentId) + if (removedServerStore) { + await retireRemovedRuntimeEnvironment( + environmentId, + invalidateRuntimeEnvironmentTransport, + removedServerStore, + userDataPath + ) + } + // The window re-reads its servers and purges the dropped host's projects and setups. + publishRuntimeEnvironmentCatalogChanged() + }, + log: (line) => console.warn(line) + }) + pairings = { prune, readBindings, updateBindings } + return pairings +} diff --git a/src/main/ipc/cloud-workspaces.ts b/src/main/ipc/cloud-workspaces.ts index d7cf104c2f2..1024b3da202 100644 --- a/src/main/ipc/cloud-workspaces.ts +++ b/src/main/ipc/cloud-workspaces.ts @@ -1,7 +1,7 @@ // IPC for team cloud workspaces. Every handler answers `not_configured` when this build has no // Orca Cloud control plane, so the renderer can hide the section instead of erroring. import { randomUUID } from 'node:crypto' -import { readFile, rename, writeFile } from 'node:fs/promises' +import { readFile, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { app, ipcMain } from 'electron' import { z } from 'zod' @@ -20,6 +20,12 @@ import { registerTeamPresenceHandlers } from './cloud-workspaces-team-presence' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' import { registerCloudWorkspacePrefsHandlers } from './cloud-workspaces-prefs' import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state' +import type { RemovedServerStore } from './runtime-environments/runtime-environment-removal-cleanup' +import { + CloudEnvironmentId as EnvironmentId, + createCloudWorkspacesPairings, + STARTUP_PRUNE_DELAY_MS +} from './cloud-workspaces-pairings' const Id = z.string().regex(/^sbx_[0-9a-f]{24}$/) const GrantId = z.string().regex(/^grt_[0-9a-f]{24}$/) @@ -147,52 +153,18 @@ async function clientIdFor(userDataPath: string): Promise { return id } -const bindingsFile = () => join(app.getPath('userData'), 'cloud-workspaces-environments.json') - -type Binding = { environmentId: string; grantId: string | null } - -const EnvironmentId = z.string().min(1).max(256) -// Older builds stored the bare environment id; read it as a binding with an unknown grant. -const StoredBinding = z.union([ - EnvironmentId.transform((environmentId): Binding => ({ environmentId, grantId: null })), - z.object({ environmentId: EnvironmentId, grantId: GrantId.nullable() }) -]) - -async function readBindings(): Promise> { - try { - const parsed = z - .record(Id, StoredBinding) - .safeParse(JSON.parse(await readFile(bindingsFile(), 'utf8'))) - return parsed.success ? parsed.data : {} - } catch { - return {} - } -} - -// Read-modify-write updates run one at a time so two quick pairings cannot drop each other. -let bindingsWrite: Promise = Promise.resolve() - -/** Temp file + rename so a crash mid-write never leaves a truncated bindings file. */ -function updateBindings( - change: (current: Record) => Record -): Promise { - bindingsWrite = bindingsWrite - .catch(() => undefined) - .then(async () => { - const file = bindingsFile() - const temp = `${file}.${process.pid}.tmp` - await writeFile(temp, JSON.stringify(change(await readBindings())), { mode: 0o600 }) - await rename(temp, file) - }) - return bindingsWrite -} - let quitHookInstalled = false const NOT_CONFIGURED = { ok: false as const, error: 'not_configured' } const INVALID = { ok: false as const, error: 'invalid_request' } -export function registerCloudWorkspacesHandlers(): void { +export function registerCloudWorkspacesHandlers( + options: { removedServerStore?: RemovedServerStore } = {} +): void { + const { prune, readBindings, updateBindings } = createCloudWorkspacesPairings( + getService, + options.removedServerStore + ) const handle = (channel: string, fn: (args: unknown) => unknown): void => { ipcMain.removeHandler(channel) ipcMain.handle(channel, (_event, args: unknown) => fn(args)) @@ -201,7 +173,15 @@ export function registerCloudWorkspacesHandlers(): void { handle('cloudWorkspaces:list', async (args) => { const query = ListQuery.safeParse(args ?? {}) const s = await getService() - return !s ? NOT_CONFIGURED : query.success ? s.list(query.data) : INVALID + if (!s || !query.success) { + return !s ? NOT_CONFIGURED : INVALID + } + const result = await s.list(query.data) + // Each successful refresh also checks this device's pairings (throttled, in the background). + if (result.ok) { + void prune.run() + } + return result }) handle('cloudWorkspaces:get', async (args) => { const parsed = z.object({ id: Id }).safeParse(args) @@ -259,13 +239,24 @@ export function registerCloudWorkspacesHandlers(): void { ? s.revokeGrant(parsed.data.id, parsed.data.grantId) : INVALID }) - for (const action of ['sleep', 'destroy'] as const) { - handle(`cloudWorkspaces:${action}`, async (args) => { - const parsed = z.object({ id: Id }).safeParse(args) - const s = await getService() - return !s ? NOT_CONFIGURED : parsed.success ? s[action](parsed.data.id) : INVALID - }) - } + handle('cloudWorkspaces:sleep', async (args) => { + const parsed = z.object({ id: Id }).safeParse(args) + const s = await getService() + return !s ? NOT_CONFIGURED : parsed.success ? s.sleep(parsed.data.id) : INVALID + }) + handle('cloudWorkspaces:destroy', async (args) => { + const parsed = z.object({ id: Id }).safeParse(args) + const s = await getService() + if (!s || !parsed.success) { + return !s ? NOT_CONFIGURED : INVALID + } + const result = await s.destroy(parsed.data.id) + // Deleted from here: its pairing, server and projects go now, not at the next list. + if (result.ok) { + await prune.forget(parsed.data.id).catch(() => undefined) + } + return result + }) handle( 'cloudWorkspaces:localWorkspaces', async () => (await getService())?.localWorkspaces() ?? [] @@ -281,9 +272,10 @@ export function registerCloudWorkspacesHandlers(): void { .safeParse(args) if (parsed.success) { const { sandboxId, runtimeEnvironmentId, grantId } = parsed.data + const accountId = prune.accountForNewBinding() await updateBindings((current) => ({ ...current, - [sandboxId]: { environmentId: runtimeEnvironmentId, grantId: grantId ?? null } + [sandboxId]: { environmentId: runtimeEnvironmentId, grantId: grantId ?? null, accountId } })) } }) @@ -321,6 +313,9 @@ export function registerCloudWorkspacesHandlers(): void { // Handlers are re-registered per main window; the quit hook must only be added once. if (!quitHookInstalled) { quitHookInstalled = true + // Startup: pairings whose sandbox was deleted while this app was closed go now. Delayed so + // the Orca session is restored first; a list that still fails just leaves everything alone. + setTimeout(() => void prune.run({ force: true }), STARTUP_PRUNE_DELAY_MS).unref?.() app.once('will-quit', () => service?.dispose()) } } diff --git a/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts b/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts index efee902a662..b88fc0aa0b6 100644 --- a/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts +++ b/src/main/ipc/profiles/orca-profile-auth-status-broadcast.ts @@ -2,6 +2,7 @@ import { BrowserWindow } from 'electron' import { ORCA_PROFILE_AUTH_STATUS_CHANGED_CHANNEL, ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, + type OrcaCloudSignInEnd, type OrcaCloudSignInProgress } from '../../../shared/orca-profiles' @@ -23,7 +24,8 @@ export function broadcastOrcaProfileAuthStatusChanged(): void { } export function broadcastOrcaProfileSignInProgressChanged( - progress: OrcaCloudSignInProgress | null + progress: OrcaCloudSignInProgress | null, + end?: OrcaCloudSignInEnd ): void { - broadcast(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, progress) + broadcast(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, progress, end ?? null) } diff --git a/src/main/orca-profiles/profile-cloud-pkce.test.ts b/src/main/orca-profiles/profile-cloud-pkce.test.ts index ca13f97a480..747b3bb3843 100644 --- a/src/main/orca-profiles/profile-cloud-pkce.test.ts +++ b/src/main/orca-profiles/profile-cloud-pkce.test.ts @@ -6,7 +6,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ app: { isPackaged: false }, shell: { openExternal: vi.fn() } })) import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' -import { beginOrcaCloudPkceFlow } from './profile-cloud-pkce' +import { + beginOrcaCloudPkceFlow, + ORCA_CLOUD_SIGN_IN_TIMEOUT_MS, + orcaCloudSignInTimeoutMs +} from './profile-cloud-pkce' const base = 'https://auth.test' const config: OrcaCloudAuthConfig = { @@ -27,6 +31,7 @@ const config: OrcaCloudAuthConfig = { afterEach(() => { delete process.env.ORCA_CLOUD_DEV_OPEN_URL_FILE + delete process.env.ORCA_CLOUD_SIGN_IN_TIMEOUT_MS }) describe('PKCE loopback for cloud setup', () => { @@ -76,3 +81,55 @@ describe('PKCE loopback for cloud setup', () => { expect((await browser).status).toBe(200) }) }) + +describe('PKCE loopback cancel and timeout', () => { + async function start(signal?: AbortSignal): Promise<{ + flow: Promise + redirect: URL + }> { + process.env.ORCA_CLOUD_DEV_OPEN_URL_FILE = join(mkdtempSync(join(tmpdir(), 'pkce-')), 'urls') + let authorize = '' + const flow = beginOrcaCloudPkceFlow(config, 'profile-1', { + onAuthorizeUrl: (url) => (authorize = url), + ...(signal ? { signal } : {}) + }) + flow.catch(() => undefined) + await vi.waitFor(() => expect(authorize).not.toBe('')) + return { flow, redirect: new URL(new URL(authorize).searchParams.get('redirect_uri')!) } + } + + it('Cancel rejects the wait and closes the loopback listener', async () => { + const abort = new AbortController() + const { flow, redirect } = await start(abort.signal) + abort.abort() + await expect(flow).rejects.toThrow('orca_cloud_auth_cancelled') + // A late browser callback finds nothing listening. + await expect(fetch(redirect)).rejects.toThrow() + }) + + it('an already-cancelled attempt never opens a listener', async () => { + const abort = new AbortController() + abort.abort() + const onAuthorizeUrl = vi.fn() + await expect( + beginOrcaCloudPkceFlow(config, 'profile-1', { signal: abort.signal, onAuthorizeUrl }) + ).rejects.toThrow('orca_cloud_auth_cancelled') + expect(onAuthorizeUrl).not.toHaveBeenCalled() + }) + + it('times out a sign-in the browser never finishes', async () => { + process.env.ORCA_CLOUD_SIGN_IN_TIMEOUT_MS = '1000' + const { flow, redirect } = await start() + await expect(flow).rejects.toThrow('orca_cloud_auth_timeout') + await expect(fetch(redirect)).rejects.toThrow() + }) + + it('waits five minutes by default; only unpackaged dev runs may shorten it', () => { + expect(ORCA_CLOUD_SIGN_IN_TIMEOUT_MS).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({}, false)).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: '60000' }, false)).toBe(60_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: '60000' }, true)).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: '10' }, false)).toBe(300_000) + expect(orcaCloudSignInTimeoutMs({ ORCA_CLOUD_SIGN_IN_TIMEOUT_MS: 'x' }, false)).toBe(300_000) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-pkce.ts b/src/main/orca-profiles/profile-cloud-pkce.ts index be85d68036f..43127271205 100644 --- a/src/main/orca-profiles/profile-cloud-pkce.ts +++ b/src/main/orca-profiles/profile-cloud-pkce.ts @@ -24,7 +24,17 @@ export type OrcaCloudAuthorizationCode = { /** How long a held browser tab waits for the caller before it gets the "signed in" page. */ const HOLD_BROWSER_MS = 30_000 -const AUTH_TIMEOUT_MS = 5 * 60 * 1000 +/** A sign-in the browser never answers ends after this, with "Sign-in didn’t finish. Try again." */ +export const ORCA_CLOUD_SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000 + +/** Dev automation only (unpackaged): ORCA_CLOUD_SIGN_IN_TIMEOUT_MS shortens the wait for a test run. */ +export function orcaCloudSignInTimeoutMs( + env: NodeJS.ProcessEnv = process.env, + packaged: boolean = app.isPackaged +): number { + const override = packaged ? Number.NaN : Number(env.ORCA_CLOUD_SIGN_IN_TIMEOUT_MS) + return Number.isFinite(override) && override >= 1_000 ? override : ORCA_CLOUD_SIGN_IN_TIMEOUT_MS +} function base64Url(buffer: Buffer): string { return buffer.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '') @@ -159,7 +169,7 @@ export function beginOrcaCloudPkceFlow( const timeout = setTimeout(() => { rejectFlow(new Error('orca_cloud_auth_timeout')) - }, AUTH_TIMEOUT_MS) + }, orcaCloudSignInTimeoutMs()) const cancel = (): void => rejectFlow(new Error('orca_cloud_auth_cancelled')) options.signal?.addEventListener('abort', cancel, { once: true }) server.once('close', () => { @@ -167,6 +177,10 @@ export function beginOrcaCloudPkceFlow( options.signal?.removeEventListener('abort', cancel) }) server.once('error', rejectFlow) + if (options.signal?.aborted) { + cancel() + return + } server.listen(0, '127.0.0.1', () => { const address = server.address() if (!address || typeof address === 'string') { diff --git a/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts b/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts index 04dd63f7e67..4417aad27a3 100644 --- a/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts +++ b/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts @@ -184,7 +184,8 @@ describe('Orca cloud overlapping connect', () => { redirectUri: 'http://127.0.0.1:4100/auth/callback', state: 'earlier-state' }) - await expect(earlier).resolves.toMatchObject({ status: 'connected' }) + // The later sign-in replaced the earlier one, so the earlier callback can't link anything. + await expect(earlier).resolves.toMatchObject({ status: 'cancelled' }) await expect(signOutCurrentOrcaProfile(userDataPath)).resolves.toMatchObject({ status: 'signed-out' }) @@ -196,7 +197,7 @@ describe('Orca cloud overlapping connect', () => { state: 'later-state' }) await expect(later).resolves.toMatchObject({ status: 'cancelled' }) - expect(exchangeOrcaCloudAuthCodeMock).toHaveBeenCalledTimes(1) + expect(exchangeOrcaCloudAuthCodeMock).not.toHaveBeenCalled() expect(getCurrentOrcaProfileAuthStatus(userDataPath)).toMatchObject({ state: 'local' }) }) }) diff --git a/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts b/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts new file mode 100644 index 00000000000..6b7dab91dd5 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-service-sign-in-cancel.test.ts @@ -0,0 +1,171 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { OrcaCloudSignInEnd, OrcaProfileCloudSummary } from '../../shared/orca-profiles' + +const { beginOrcaCloudPkceFlowMock, exchangeOrcaCloudAuthCodeMock, safeStorageMock } = vi.hoisted( + () => ({ + beginOrcaCloudPkceFlowMock: vi.fn(), + exchangeOrcaCloudAuthCodeMock: vi.fn(), + safeStorageMock: { + decryptString: vi.fn((value: Buffer) => value.toString('utf-8')), + encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), + isEncryptionAvailable: vi.fn(() => true) + } + }) +) + +let userDataPath = '' + +vi.mock('electron', () => ({ + app: { getPath: () => userDataPath }, + safeStorage: safeStorageMock +})) + +vi.mock('./profile-cloud-pkce', () => ({ + beginOrcaCloudPkceFlow: beginOrcaCloudPkceFlowMock +})) + +vi.mock('./profile-cloud-client', () => ({ + createOrcaCloudProfile: vi.fn(), + exchangeOrcaCloudAuthCode: exchangeOrcaCloudAuthCodeMock, + revokeOrcaCloudSession: vi.fn(async () => undefined), + selectOrcaCloudOrg: vi.fn() +})) + +import { connectCurrentOrcaProfile, getCurrentOrcaProfileAuthStatus } from './profile-cloud-service' +import { + cancelOrcaCloudSignIn, + getOrcaCloudSignInProgress, + onOrcaCloudSignInProgressChanged, + resetOrcaCloudSignInProgressForTests +} from './profile-cloud-sign-in-progress' + +const cloud: OrcaProfileCloudSummary = { + cloudProfileId: 'cloud-profile-1', + userId: 'user-1', + email: 'nina@example.com', + displayName: 'Nina', + linkedAt: 10 +} + +// A fixed far-future expiry: no wall clock in tests. +const EXPIRES_AT = 4_102_444_800_000 + +const code = { + code: 'the-code', + codeVerifier: 'verifier', + nonce: 'nonce', + redirectUri: 'http://127.0.0.1:4100/auth/callback', + state: 'state' +} + +/** Waits for the browser like the real loopback: rejects when the attempt is aborted. */ +function pendingBrowser(): { + answer: (value: typeof code) => void + fail: (error: Error) => void +} { + const handle = { + answer: (_value: typeof code): void => undefined, + fail: (_error: Error): void => undefined + } + beginOrcaCloudPkceFlowMock.mockImplementationOnce( + (_config: unknown, _profile: string, options: { signal?: AbortSignal }) => + new Promise((resolve, reject) => { + handle.answer = resolve + handle.fail = reject + options.signal?.addEventListener('abort', () => + reject(new Error('orca_cloud_auth_cancelled')) + ) + }) + ) + return handle +} + +describe('Orca Cloud sign-in cancel, supersede and timeout', () => { + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-cloud-sign-in-cancel-')) + beginOrcaCloudPkceFlowMock.mockReset() + exchangeOrcaCloudAuthCodeMock.mockReset() + exchangeOrcaCloudAuthCodeMock.mockResolvedValue({ + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: EXPIRES_AT, + cloud, + organizations: [], + capabilities: { flags: {}, refreshedAt: 1 } + }) + vi.stubEnv('ORCA_CLOUD_API_URL', 'https://orca-cloud.example') + vi.stubEnv('ORCA_CLOUD_CLIENT_ID', 'desktop-client') + }) + + afterEach(() => { + resetOrcaCloudSignInProgressForTests() + rmSync(userDataPath, { recursive: true, force: true }) + vi.unstubAllEnvs() + }) + + it('Cancel while the browser is open ends the sign-in and clears progress', async () => { + pendingBrowser() + const connect = connectCurrentOrcaProfile(userDataPath) + await vi.waitFor(() => expect(getOrcaCloudSignInProgress()).not.toBeNull()) + cancelOrcaCloudSignIn() + expect(getOrcaCloudSignInProgress()).toBeNull() + await expect(connect).resolves.toMatchObject({ status: 'cancelled' }) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).state).not.toBe('connected') + }) + + it('Cancel after the browser answered still wins: the session is not saved', async () => { + const browser = pendingBrowser() + let finishExchange!: () => void + exchangeOrcaCloudAuthCodeMock.mockImplementationOnce(async () => { + await new Promise((resolve) => (finishExchange = resolve)) + return { + accessToken: 'access-token', + refreshToken: 'refresh-token', + expiresAt: EXPIRES_AT, + cloud, + organizations: [], + capabilities: { flags: {}, refreshedAt: 1 } + } + }) + const connect = connectCurrentOrcaProfile(userDataPath) + await vi.waitFor(() => expect(beginOrcaCloudPkceFlowMock).toHaveBeenCalled()) + browser.answer(code) + await vi.waitFor(() => expect(exchangeOrcaCloudAuthCodeMock).toHaveBeenCalled()) + cancelOrcaCloudSignIn() + finishExchange() + await expect(connect).resolves.toMatchObject({ status: 'cancelled' }) + expect(getCurrentOrcaProfileAuthStatus(userDataPath).state).not.toBe('connected') + }) + + it('a second sign-in replaces the first: the first closes, the second signs in', async () => { + pendingBrowser() + const second = pendingBrowser() + const first = connectCurrentOrcaProfile(userDataPath) + const later = connectCurrentOrcaProfile(userDataPath) + await expect(first).resolves.toMatchObject({ status: 'cancelled' }) + expect(getOrcaCloudSignInProgress()).not.toBeNull() + second.answer(code) + await expect(later).resolves.toMatchObject({ status: 'connected' }) + expect(getOrcaCloudSignInProgress()).toBeNull() + expect(getCurrentOrcaProfileAuthStatus(userDataPath).cloud?.email).toBe('nina@example.com') + }) + + it('a timed-out sign-in clears progress and says it did not finish', async () => { + const ends: (OrcaCloudSignInEnd | undefined)[] = [] + onOrcaCloudSignInProgressChanged((progress, end) => { + if (!progress) { + ends.push(end) + } + }) + const browser = pendingBrowser() + const connect = connectCurrentOrcaProfile(userDataPath) + await vi.waitFor(() => expect(beginOrcaCloudPkceFlowMock).toHaveBeenCalled()) + browser.fail(new Error('orca_cloud_auth_timeout')) + await expect(connect).resolves.toMatchObject({ status: 'timed-out' }) + expect(getOrcaCloudSignInProgress()).toBeNull() + expect(ends).toEqual(['timed-out']) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/profile-cloud-service.ts index 4bd70e0412f..616151ba594 100644 --- a/src/main/orca-profiles/profile-cloud-service.ts +++ b/src/main/orca-profiles/profile-cloud-service.ts @@ -39,6 +39,7 @@ import { import { getOrcaProfileAuthStatusFromProfile } from './profile-cloud-auth-status' import { selectCloudOrg } from './profile-cloud-org-selection' import { + cancelOrcaCloudSignIn, endOrcaCloudSignInProgress, setOrcaCloudSignInLink, startOrcaCloudSignInProgress @@ -53,7 +54,8 @@ let linkedCloudConnectAttempt = 0 function invalidateOutstandingCloudConnectAttempts(): void { nextCloudConnectAttempt += 1 linkedCloudConnectAttempt = nextCloudConnectAttempt - endOrcaCloudSignInProgress() + // Also closes the pending loopback listener, so a late browser callback has nowhere to land. + cancelOrcaCloudSignIn() } function activeAuth( @@ -100,23 +102,27 @@ export async function connectCurrentOrcaProfile( } const attempt = ++nextCloudConnectAttempt - const browserWait = new AbortController() - startOrcaCloudSignInProgress(attempt, () => browserWait.abort()) + // Cancel (or a newer attempt) aborts this one at any stage before the session is saved. + const attemptAbort = new AbortController() + const cancelled = (): ConnectCurrentOrcaProfileResult => ({ + status: 'cancelled', + auth: getCurrentOrcaProfileAuthStatus(userDataPath) + }) + const stale = (): boolean => attempt < linkedCloudConnectAttempt || attemptAbort.signal.aborted + let end: 'timed-out' | undefined + startOrcaCloudSignInProgress(attempt, () => attemptAbort.abort()) let finishBrowser: ((location: string | null) => void) | undefined try { const code = await beginOrcaCloudPkceFlow(configState.config, active.profile.id, { - signal: browserWait.signal, + signal: attemptAbort.signal, onAuthorizeUrl: (link) => setOrcaCloudSignInLink(attempt, link), ...(setup ? { authorizeParams: setup.authorizeParams, holdBrowser: true } : {}) }) finishBrowser = code.finishBrowser // The callback listener has closed, so its browser link is dead. setOrcaCloudSignInLink(attempt, null) - if (attempt < linkedCloudConnectAttempt) { - return { - status: 'cancelled', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + if (stale()) { + return cancelled() } const exchange = await exchangeOrcaCloudAuthCode(configState.config, { code: code.code, @@ -126,11 +132,8 @@ export async function connectCurrentOrcaProfile( state: code.state, localProfileId: active.profile.id }) - if (attempt < linkedCloudConnectAttempt) { - return { - status: 'cancelled', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + if (stale()) { + return cancelled() } signInCloudSession(active.profile.id, userDataPath, exchange) const list = linkOrcaProfileToCloud(active.profile.id, exchange.cloud, userDataPath) @@ -148,21 +151,17 @@ export async function connectCurrentOrcaProfile( } } catch (error) { const message = error instanceof Error ? error.message : String(error) - if (message === 'orca_cloud_auth_timeout' && attempt === nextCloudConnectAttempt) { - return { - status: 'timed-out', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + if (!stale() && message === 'orca_cloud_auth_timeout' && attempt === nextCloudConnectAttempt) { + end = 'timed-out' + return { status: 'timed-out', auth: getCurrentOrcaProfileAuthStatus(userDataPath) } } - if ( - message === 'orca_cloud_auth_timeout' || - message === 'orca_cloud_auth_denied' || - message === 'orca_cloud_auth_cancelled' - ) { - return { - status: 'cancelled', - auth: getCurrentOrcaProfileAuthStatus(userDataPath) - } + const stopped = [ + 'orca_cloud_auth_timeout', + 'orca_cloud_auth_denied', + 'orca_cloud_auth_cancelled' + ] + if (attemptAbort.signal.aborted || stopped.includes(message)) { + return cancelled() } return { status: 'failed', @@ -171,7 +170,7 @@ export async function connectCurrentOrcaProfile( } } finally { finishBrowser?.(null) - endOrcaCloudSignInProgress(attempt) + endOrcaCloudSignInProgress(attempt, end) } } diff --git a/src/main/orca-profiles/profile-cloud-sign-in-progress.test.ts b/src/main/orca-profiles/profile-cloud-sign-in-progress.test.ts new file mode 100644 index 00000000000..2e4135c9cb7 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-sign-in-progress.test.ts @@ -0,0 +1,73 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { OrcaCloudSignInEnd, OrcaCloudSignInProgress } from '../../shared/orca-profiles' +import { + cancelOrcaCloudSignIn, + endOrcaCloudSignInProgress, + getOrcaCloudSignInProgress, + onOrcaCloudSignInProgressChanged, + resetOrcaCloudSignInProgressForTests, + setOrcaCloudSignInLink, + startOrcaCloudSignInProgress +} from './profile-cloud-sign-in-progress' + +afterEach(() => resetOrcaCloudSignInProgressForTests()) + +function record(): [OrcaCloudSignInProgress | null, OrcaCloudSignInEnd | undefined][] { + const events: [OrcaCloudSignInProgress | null, OrcaCloudSignInEnd | undefined][] = [] + onOrcaCloudSignInProgressChanged((progress, end) => events.push([progress, end])) + return events +} + +describe('Orca Cloud sign-in progress', () => { + it('Cancel aborts the pending attempt and clears progress at once', () => { + const events = record() + const abort = vi.fn() + startOrcaCloudSignInProgress(1, abort) + setOrcaCloudSignInLink(1, 'https://auth.test/authorize') + cancelOrcaCloudSignIn() + expect(abort).toHaveBeenCalledOnce() + expect(getOrcaCloudSignInProgress()).toBeNull() + expect(events.at(-1)).toEqual([null, undefined]) + // The aborted attempt ending later changes nothing. + endOrcaCloudSignInProgress(1) + expect(events).toHaveLength(3) + }) + + it('clears progress even when aborting throws', () => { + startOrcaCloudSignInProgress(1, () => { + throw new Error('already closed') + }) + expect(() => cancelOrcaCloudSignIn()).not.toThrow() + expect(getOrcaCloudSignInProgress()).toBeNull() + }) + + it('a second sign-in replaces the first and cancels it', () => { + const first = vi.fn() + const second = vi.fn() + startOrcaCloudSignInProgress(1, first) + setOrcaCloudSignInLink(1, 'https://auth.test/one') + startOrcaCloudSignInProgress(2, second) + expect(first).toHaveBeenCalledOnce() + expect(second).not.toHaveBeenCalled() + expect(getOrcaCloudSignInProgress()).toEqual({ link: null }) + // The replaced attempt can neither set its link nor end the newer one. + setOrcaCloudSignInLink(1, 'https://auth.test/stale') + endOrcaCloudSignInProgress(1) + expect(getOrcaCloudSignInProgress()).toEqual({ link: null }) + setOrcaCloudSignInLink(2, 'https://auth.test/two') + expect(getOrcaCloudSignInProgress()).toEqual({ link: 'https://auth.test/two' }) + }) + + it('says when a sign-in timed out', () => { + const events = record() + startOrcaCloudSignInProgress(3, vi.fn()) + endOrcaCloudSignInProgress(3, 'timed-out') + expect(events.at(-1)).toEqual([null, 'timed-out']) + }) + + it('Cancel with nothing pending is a no-op', () => { + const events = record() + cancelOrcaCloudSignIn() + expect(events).toHaveLength(0) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-sign-in-progress.ts b/src/main/orca-profiles/profile-cloud-sign-in-progress.ts index 88cb98cc23d..5c33fb6873c 100644 --- a/src/main/orca-profiles/profile-cloud-sign-in-progress.ts +++ b/src/main/orca-profiles/profile-cloud-sign-in-progress.ts @@ -1,8 +1,9 @@ -import type { OrcaCloudSignInProgress } from '../../shared/orca-profiles' +import type { OrcaCloudSignInEnd, OrcaCloudSignInProgress } from '../../shared/orca-profiles' -type ProgressListener = (progress: OrcaCloudSignInProgress | null) => void +type ProgressListener = (progress: OrcaCloudSignInProgress | null, end?: OrcaCloudSignInEnd) => void -// Only the newest attempt owns progress; late updates from older attempts are ignored. +// One sign-in at a time: a newer attempt cancels the older one (its loopback listener closes), and +// Cancel clears the pending state at once, so nothing can leave the app stuck on "Signing in…". let current: { attempt: number; link: string | null; cancel: () => void } | null = null const listeners = new Set() @@ -10,18 +11,26 @@ function snapshot(): OrcaCloudSignInProgress | null { return current ? { link: current.link } : null } -function update(next: typeof current): void { +function update(next: typeof current, end?: OrcaCloudSignInEnd): void { current = next const progress = snapshot() for (const listener of listeners) { try { - listener(progress) + listener(progress, end) } catch (error) { console.warn('[orca-profiles] Sign-in progress listener failed:', error) } } } +function cancelQuietly(cancel: () => void): void { + try { + cancel() + } catch (error) { + console.warn('[orca-profiles] Cancelling a sign-in failed:', error) + } +} + export function getOrcaCloudSignInProgress(): OrcaCloudSignInProgress | null { return snapshot() } @@ -33,8 +42,13 @@ export function onOrcaCloudSignInProgressChanged(listener: ProgressListener): () } } +/** Starts tracking `attempt`; an older pending attempt is cancelled (a second click supersedes it). */ export function startOrcaCloudSignInProgress(attempt: number, cancel: () => void): void { + const previous = current update({ attempt, link: null, cancel }) + if (previous && previous.attempt !== attempt) { + cancelQuietly(previous.cancel) + } } export function setOrcaCloudSignInLink(attempt: number, link: string | null): void { @@ -43,12 +57,24 @@ export function setOrcaCloudSignInLink(attempt: number, link: string | null): vo } } -export function endOrcaCloudSignInProgress(attempt?: number): void { +export function endOrcaCloudSignInProgress(attempt?: number, end?: OrcaCloudSignInEnd): void { if (current && (attempt === undefined || current.attempt === attempt)) { - update(null) + update(null, end) } } +/** Cancel: aborts the pending attempt (closing its loopback listener) and clears progress now. */ export function cancelOrcaCloudSignIn(): void { - current?.cancel() + const pending = current + if (!pending) { + return + } + update(null) + cancelQuietly(pending.cancel) +} + +/** Test-only. */ +export function resetOrcaCloudSignInProgressForTests(): void { + current = null + listeners.clear() } diff --git a/src/main/ports/host-managed-listeners.test.ts b/src/main/ports/host-managed-listeners.test.ts index 366458ce6c5..3ba814d2776 100644 --- a/src/main/ports/host-managed-listeners.test.ts +++ b/src/main/ports/host-managed-listeners.test.ts @@ -7,7 +7,7 @@ const config = (roots: string[] = ['/opt/orca'], unownedPorts: number[] = [23456 }) describe('host-managed listeners', () => { - it('reads absolute roots and platform ports from the environment', () => { + it('reads absolute roots and platform ports from the environment', async () => { const parsed = hostManagedListenerConfig({ ORCA_HOST_MANAGED_LISTENER_PATHS: '/opt/orca/:relative:/srv/tools', ORCA_HOST_MANAGED_UNOWNED_PORTS: '23456, x,70000' @@ -17,17 +17,17 @@ describe('host-managed listeners', () => { expect(hostManagedListenerConfig({})).toEqual({ roots: [], unownedPorts: new Set() }) }) - it('marks the server itself and programs started from a managed root', () => { - expect(isHostManagedListener({ pid: 27, port: 6768 }, config(), 27)).toBe(true) + it('marks the server itself and programs started from a managed root', async () => { + expect(await isHostManagedListener({ pid: 27, port: 6768 }, config(), 27)).toBe(true) expect( - isHostManagedListener( + await isHostManagedListener( { pid: 90, port: 2222, commandLine: '/opt/orca/openssh/sbin/sshd -D -f x' }, config(), 27 ) ).toBe(true) expect( - isHostManagedListener( + await isHostManagedListener( { pid: 91, port: 6080, @@ -39,40 +39,80 @@ describe('host-managed listeners', () => { ).toBe(true) }) - it('marks a pid-less listener only on a declared platform port', () => { - expect(isHostManagedListener({ port: 23456 }, config(), 27)).toBe(true) + it('marks a pid-less listener only on a declared platform port', async () => { + expect(await isHostManagedListener({ port: 23456 }, config(), 27)).toBe(true) // A root-run postgres or Docker-published port has no visible pid but is the user's. - expect(isHostManagedListener({ port: 5432 }, config(), 27)).toBe(false) - expect(isHostManagedListener({ port: 23456 }, config(['/opt/orca'], []), 27)).toBe(false) + expect(await isHostManagedListener({ port: 5432 }, config(), 27)).toBe(false) + expect(await isHostManagedListener({ port: 23456 }, config(['/opt/orca'], []), 27)).toBe(false) }) - it('leaves user servers alone, matching by program path rather than port', () => { + it('leaves user servers alone, matching by program path rather than port', async () => { expect( - isHostManagedListener( + await isHostManagedListener( { pid: 92, port: 6768, commandLine: 'python3 -m http.server 6768' }, config(), 27 ) ).toBe(false) expect( - isHostManagedListener( + await isHostManagedListener( { pid: 92, port: 23456, commandLine: 'python3 -m http.server 23456' }, config(), 27 ) ).toBe(false) expect( - isHostManagedListener( + await isHostManagedListener( { pid: 93, port: 5173, commandLine: 'node vite --config /opt/orca/x.js' }, config(), 27 ) ).toBe(false) expect( - isHostManagedListener({ pid: 94, port: 1, commandLine: '/opt/orcaother/bin/x' }, config(), 27) + await isHostManagedListener( + { pid: 94, port: 1, commandLine: '/opt/orcaother/bin/x' }, + config(), + 27 + ) ).toBe(false) expect( - isHostManagedListener({ pid: 95, port: 1, commandLine: '/opt/orca/bin/x' }, config([]), 27) + await isHostManagedListener( + { pid: 95, port: 1, commandLine: '/opt/orca/bin/x' }, + config([]), + 27 + ) ).toBe(false) }) + + it('walks ancestry to a managed tool, stopping at the server and at shells', async () => { + const parents: Record = { + 985: { pid: 941, commandLine: '/opt/orca/runtime/orcad/agent-browser-linux-x64' }, + 1018: { pid: 985, commandLine: '/usr/bin/google-chrome --headless' }, + 300: { pid: 27, commandLine: 'node /opt/orca/runtime/orcad/orcad-server.js' }, + 400: { pid: 399, commandLine: '/bin/bash' }, + 399: { pid: 27, commandLine: 'node /opt/orca/runtime/orcad/orcad-server.js' }, + 500: { pid: 499, commandLine: '-bash' }, + 499: { pid: 498, commandLine: '/opt/orca/openssh/sbin/sshd -D -f x' } + } + const read = async (pid: number) => parents[pid] + const chrome = { pid: 985, port: 42063, commandLine: '/usr/bin/google-chrome --headless' } + expect(await isHostManagedListener(chrome, config(), 27, read)).toBe(true) + // Grandchild: a Chrome helper two levels below agent-browser. + expect( + await isHostManagedListener( + { pid: 1018, port: 42064, commandLine: '/opt/google/chrome/chrome --type=utility' }, + config(), + 27, + read + ) + ).toBe(true) + expect(await isHostManagedListener(chrome, config([]), 27, read)).toBe(false) + const user = (pid: number) => ({ pid, port: 8123, commandLine: 'python3 -m http.server' }) + // `exec python3 -m http.server` in a terminal: its parent is the server. + expect(await isHostManagedListener(user(300), config(), 27, read)).toBe(false) + // Terminal shell under the server. + expect(await isHostManagedListener(user(400), config(), 27, read)).toBe(false) + // An SSH session's shell under the managed sshd. + expect(await isHostManagedListener(user(500), config(), 27, read)).toBe(false) + }) }) diff --git a/src/main/ports/host-managed-listeners.ts b/src/main/ports/host-managed-listeners.ts index fcdfe7fdb21..396270e307f 100644 --- a/src/main/ports/host-managed-listeners.ts +++ b/src/main/ports/host-managed-listeners.ts @@ -1,3 +1,4 @@ +import { readFile } from 'node:fs/promises' import type { RawListeningPort } from './local-workspace-port-scan-state' /** Colon-separated install roots whose binaries are the host's own services (e.g. a sandbox image's tools). */ @@ -28,27 +29,79 @@ export function hostManagedListenerConfig( /** * Listeners the host runs itself: this server process, a program started from a managed root - * (checked on argv[0] and argv[1], so `python3 /root/bin/tool` counts too), or a declared platform - * port whose owner is invisible. A pid-less listener on any other port (a root-run postgres or + * (checked on argv[0] and argv[1], so `python3 /root/bin/tool` counts too) or its descendant, or a + * declared platform port whose owner is invisible. A pid-less listener on any other port (a root-run postgres or * Docker-published port) is still the user's. */ -export function isHostManagedListener( +export async function isHostManagedListener( port: Pick, config: HostManagedListenerConfig, - serverPid: number = process.pid -): boolean { + serverPid: number = process.pid, + readParent: (pid: number) => Promise = readLinuxParentProcess +): Promise { if (port.pid === undefined) { return config.unownedPorts.has(port.port) } if (port.pid === serverPid) { return true } - if (config.roots.length === 0 || !port.commandLine) { + if (config.roots.length === 0) { return false } - return port.commandLine + if (startedFromRoot(port.commandLine, config.roots)) { + return true + } + // A managed tool's descendant (agent-browser's Chrome DevTools port). The walk stops at the server + // (it spawns the user's terminals) and at a shell (a user session, e.g. over the managed sshd). + let pid = port.pid + for (let depth = 0; depth < MAX_ANCESTRY_DEPTH; depth++) { + const parent = await readParent(pid) + if (!parent || parent.pid === serverPid || isShell(parent.commandLine)) { + return false + } + if (startedFromRoot(parent.commandLine, config.roots)) { + return true + } + pid = parent.pid + } + return false +} + +const MAX_ANCESTRY_DEPTH = 8 +const SHELLS = new Set(['sh', 'bash', 'dash', 'zsh', 'fish', 'ksh', 'tcsh', 'csh', 'nu', 'pwsh']) + +function isShell(commandLine: string): boolean { + const argv0 = commandLine.trim().split(/\s+/)[0] ?? '' + return SHELLS.has(argv0.replace(/^-/, '').split('/').pop() ?? '') +} + +export type ParentProcess = { pid: number; commandLine: string } + +function startedFromRoot(commandLine: string | undefined, roots: readonly string[]): boolean { + return (commandLine ?? '') .trim() .split(/\s+/) .slice(0, 2) - .some((token) => config.roots.some((root) => token === root || token.startsWith(`${root}/`))) + .some((token) => roots.some((root) => token === root || token.startsWith(`${root}/`))) +} + +async function readLinuxParentProcess(pid: number): Promise { + if (process.platform !== 'linux') { + return undefined + } + try { + // /proc//stat: "pid (comm) state ppid ..."; comm may contain spaces or parens. + const stat = await readFile(`/proc/${pid}/stat`, 'utf8') + const ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]) + if (!Number.isInteger(ppid) || ppid <= 1) { + return undefined + } + const commandLine = (await readFile(`/proc/${ppid}/cmdline`, 'utf8')) + .split('\0') + .join(' ') + .trim() + return { pid: ppid, commandLine } + } catch { + return undefined + } } diff --git a/src/main/ports/local-workspace-port-scanner.ts b/src/main/ports/local-workspace-port-scanner.ts index 5b85224fda5..7b370e9b421 100644 --- a/src/main/ports/local-workspace-port-scanner.ts +++ b/src/main/ports/local-workspace-port-scanner.ts @@ -42,9 +42,12 @@ export async function scanWorkspacePorts( options.requireMetadata ) const hostManaged = hostManagedListenerConfig() + const managedFlags = await Promise.all( + rawPorts.map((port) => isHostManagedListener(port, hostManaged)) + ) const managed = new Set( rawPorts - .filter((port) => isHostManagedListener(port, hostManaged)) + .filter((_, index) => managedFlags[index]) .map((port) => `${port.host}:${port.port}:${port.pid ?? 'unknown'}`) ) // Orca's own listeners (runtime socket, hook server) run with a workspace in their command line but are not its servers. diff --git a/src/main/runtime/rpc/methods/agent-config/agent-mcp-sync-method.ts b/src/main/runtime/rpc/methods/agent-config/agent-mcp-sync-method.ts index 31ae2593116..feb8184dc7a 100644 --- a/src/main/runtime/rpc/methods/agent-config/agent-mcp-sync-method.ts +++ b/src/main/runtime/rpc/methods/agent-config/agent-mcp-sync-method.ts @@ -1,11 +1,31 @@ import { defineMethod } from '../../core' import { AgentMcpSyncParams } from '../../../../../shared/agent-mcp-sync/mcp-sync-contract' import { getAppEnvironment } from '../../../../../shared/app-environment' +import { + AgentConfigSyncPlanParams, + AgentConfigSyncPutParams +} from '../../../../../shared/agent-config-sync/agent-config-sync-contract' +import { + planHostAgentConfigSync, + putHostAgentConfig, + type HostAgentConfigSyncDeps +} from '../../../../agent-config-sync/host/host-agent-config-sync' +import { defaultAgentConfigHomes } from '../../../../agent-config-sync/agent-config-roots' import { defaultHostMcpSyncPaths, syncHostMcpServers } from '../../../../agent-mcp-sync/host/host-mcp-sync' +function hostAgentConfigDeps(): HostAgentConfigSyncDeps { + return { + homes: defaultAgentConfigHomes(), + projectPath: process.env.ORCA_WORKSPACE_PATH?.trim() || null, + ledgerDir: getAppEnvironment().getPath('userData') + } +} + +const DESKTOP_ONLY = 'Only an Orca desktop can sync its skills and commands to this host.' + export const AGENT_CONFIG_METHODS = [ // The owning desktop mirrors its own MCP servers into this host's agent configs. defineMethod({ @@ -21,5 +41,29 @@ export const AGENT_CONFIG_METHODS = [ projectPath: process.env.ORCA_WORKSPACE_PATH?.trim() || null }) } + }), + // The owning desktop mirrors its own skills and slash commands into this host's agent configs: + // plan first (no bytes), then put only what the host lacks. + defineMethod({ + name: 'agentConfig.planSkillSync', + permission: 'accounts-admin', + params: AgentConfigSyncPlanParams, + handler: async (params, { clientKind }) => { + if (clientKind === 'mobile') { + throw new Error(DESKTOP_ONLY) + } + return planHostAgentConfigSync(params, hostAgentConfigDeps()) + } + }), + defineMethod({ + name: 'agentConfig.putSkills', + permission: 'accounts-admin', + params: AgentConfigSyncPutParams, + handler: async (params, { clientKind }) => { + if (clientKind === 'mobile') { + throw new Error(DESKTOP_ONLY) + } + return putHostAgentConfig(params, hostAgentConfigDeps()) + } }) ] diff --git a/src/main/startup/main-window-core-services.ts b/src/main/startup/main-window-core-services.ts index 72b0dd15af0..b1cc046a0de 100644 --- a/src/main/startup/main-window-core-services.ts +++ b/src/main/startup/main-window-core-services.ts @@ -73,7 +73,7 @@ export function attachMainWindowCoreServices( // Server status probes start inside registerCoreHandlers; held hosts must be marked first. holdLaunchReconnectOptOuts(store.getSshTargets()) registerAgentApiKeyHandlers(app.getPath('userData')) - registerCloudWorkspacesHandlers() + registerCloudWorkspacesHandlers({ removedServerStore: store }) registerCloudApiHandlers() registerCloudSecretsHandlers(app.getPath('userData')) registerOrcaCloudAgentsHandlers(app.getPath('userData')) diff --git a/src/preload/api/orca-profile-api.ts b/src/preload/api/orca-profile-api.ts index c572bd04513..20dd9cb6684 100644 --- a/src/preload/api/orca-profile-api.ts +++ b/src/preload/api/orca-profile-api.ts @@ -10,6 +10,7 @@ import type { OrcaProfileOrgLeaveArgs } from '../../shared/orca-org-management' import type { + OrcaCloudSignInEnd, OrcaCloudSignInProgress, ConnectCurrentOrcaProfileResult, CreateCloudLinkedOrcaProfileArgs, @@ -68,7 +69,8 @@ export type OrcaProfileApi = { connectCurrent: () => Promise signInProgress: () => Promise onSignInProgressChanged: ( - callback: (progress: OrcaCloudSignInProgress | null) => void + /** `end` says why a sign-in stopped when the UI should tell the user (it timed out). */ + callback: (progress: OrcaCloudSignInProgress | null, end: OrcaCloudSignInEnd | null) => void ) => () => void cancelSignIn: () => Promise refreshAuth: () => Promise diff --git a/src/preload/api/orca-profiles-bridge.ts b/src/preload/api/orca-profiles-bridge.ts index 15bc3fb5991..3f32e5a26f5 100644 --- a/src/preload/api/orca-profiles-bridge.ts +++ b/src/preload/api/orca-profiles-bridge.ts @@ -3,6 +3,7 @@ import type { PreloadApi } from '../api-types' import { ORCA_PROFILE_AUTH_STATUS_CHANGED_CHANNEL, ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, + type OrcaCloudSignInEnd, type OrcaCloudSignInProgress, type OrcaProfileListResult, type SwitchOrcaProfileResult, @@ -29,10 +30,13 @@ export const orcaProfilesApi = { return () => ipcRenderer.removeListener(ORCA_PROFILE_AUTH_STATUS_CHANGED_CHANNEL, listener) }, onSignInProgressChanged: ( - callback: (progress: OrcaCloudSignInProgress | null) => void + callback: (progress: OrcaCloudSignInProgress | null, end: OrcaCloudSignInEnd | null) => void ): (() => void) => { - const listener = (_event: unknown, progress: OrcaCloudSignInProgress | null): void => - callback(progress) + const listener = ( + _event: unknown, + progress: OrcaCloudSignInProgress | null, + end?: OrcaCloudSignInEnd | null + ): void => callback(progress, end ?? null) ipcRenderer.on(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, listener) return () => ipcRenderer.removeListener(ORCA_PROFILE_SIGN_IN_PROGRESS_CHANGED_CHANNEL, listener) }, diff --git a/src/preload/api/runtime-api.ts b/src/preload/api/runtime-api.ts index 8ad6551c98c..f659b71f542 100644 --- a/src/preload/api/runtime-api.ts +++ b/src/preload/api/runtime-api.ts @@ -10,6 +10,10 @@ import type { } from '../../shared/auth-callback-forward' import type { McpSyncStatus } from '../../shared/agent-mcp-sync/mcp-sync-contract' import type { CloudMcpSyncPreferences } from '../../shared/agent-mcp-sync/mcp-sync-preferences' +import type { + AgentConfigSyncStatus, + CloudAgentConfigSyncPreferences +} from '../../shared/agent-config-sync/agent-config-sync-contract' import type { CrewSubscriptionAttemptArgs, CrewSubscriptionAttemptCallbacks, @@ -135,6 +139,21 @@ export type RuntimeApi = { included: boolean ) => Promise onMcpSyncChanged?: (callback: (status: McpSyncStatus) => void) => () => void + // Orca Cloud skills and slash commands sync; desktop only, like MCP sync. + getAgentConfigSyncStatus?: (environmentId: string) => Promise + syncAgentConfigNow?: (environmentId: string) => Promise + getAgentConfigSyncPreferences?: () => Promise + setAgentConfigSyncPreferences?: ( + preferences: Partial> + ) => Promise + setAgentConfigItemIncluded?: ( + key: string, + included: boolean + ) => Promise + onAgentConfigSyncChanged?: (callback: (status: AgentConfigSyncStatus) => void) => () => void + onAgentConfigSyncPreferencesChanged?: ( + callback: (preferences: CloudAgentConfigSyncPreferences) => void + ) => () => void getStatusSnapshots: () => Promise onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void) => () => void // Absent in the web client, whose catalog lives in the browser rather than a CLI-editable file. diff --git a/src/preload/api/runtime-environments-bridge.ts b/src/preload/api/runtime-environments-bridge.ts index 0752762c826..db8be96f984 100644 --- a/src/preload/api/runtime-environments-bridge.ts +++ b/src/preload/api/runtime-environments-bridge.ts @@ -38,6 +38,12 @@ import type { } from '../../shared/auth-callback-forward' import type { McpSyncStatus } from '../../shared/agent-mcp-sync/mcp-sync-contract' import type { CloudMcpSyncPreferences } from '../../shared/agent-mcp-sync/mcp-sync-preferences' +import { + CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL, + CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL, + type AgentConfigSyncStatus, + type CloudAgentConfigSyncPreferences +} from '../../shared/agent-config-sync/agent-config-sync-contract' import { managedOrcadApi } from './managed-orcad-api' import { getWslHostsApi } from './wsl-hosts-api' @@ -89,6 +95,37 @@ export const runtimeEnvironmentsApi = { ipcRenderer.on(CLOUD_MCP_SYNC_CHANGED_CHANNEL, listener) return () => ipcRenderer.removeListener(CLOUD_MCP_SYNC_CHANGED_CHANNEL, listener) }, + getAgentConfigSyncStatus: (environmentId: string): Promise => + ipcRenderer.invoke('cloudAgentConfigSync:getStatus', environmentId), + syncAgentConfigNow: (environmentId: string): Promise => + ipcRenderer.invoke('cloudAgentConfigSync:syncNow', environmentId), + getAgentConfigSyncPreferences: (): Promise => + ipcRenderer.invoke('cloudAgentConfigSync:getPreferences'), + setAgentConfigSyncPreferences: ( + preferences: Partial> + ): Promise => + ipcRenderer.invoke('cloudAgentConfigSync:setPreferences', preferences), + setAgentConfigItemIncluded: ( + key: string, + included: boolean + ): Promise => + ipcRenderer.invoke('cloudAgentConfigSync:setItemIncluded', key, included), + onAgentConfigSyncChanged: (callback: (status: AgentConfigSyncStatus) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, status: AgentConfigSyncStatus): void => + callback(status) + ipcRenderer.on(CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL, listener) + return () => ipcRenderer.removeListener(CLOUD_AGENT_CONFIG_SYNC_CHANGED_CHANNEL, listener) + }, + onAgentConfigSyncPreferencesChanged: ( + callback: (preferences: CloudAgentConfigSyncPreferences) => void + ): (() => void) => { + const listener = ( + _event: Electron.IpcRendererEvent, + preferences: CloudAgentConfigSyncPreferences + ): void => callback(preferences) + ipcRenderer.on(CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL, listener) + return () => ipcRenderer.removeListener(CLOUD_AGENT_CONFIG_SYNC_PREFERENCES_CHANNEL, listener) + }, getStatusSnapshots: (): Promise => ipcRenderer.invoke('runtimeEnvironments:getStatusSnapshots'), onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void): (() => void) => { diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index 5e5f9c61cba..a72ac6f45ab 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -39,6 +39,7 @@ import { getFolderWorkspacePrimaryActionLabel } from '@/components/sidebar/works import { useAgentMenuObservation } from '@/components/tab-bar/use-new-tab-agent-menu-rows' import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router' import { useComposerCloudStart } from './new-workspace/run-on/use-composer-cloud-start' +import { composerAgentSelection } from './new-workspace/composer-agent-cli' import { HiddenComposer, useCloudAutoStartReveal } from './new-workspace/composer-cloud-auto-start' // Keep Add Project’s clone/SSH machinery outside the composer entry render, matching App loading. @@ -396,7 +397,7 @@ function QuickTabBody({ agentMenuModel ? { model: agentMenuModel, - selection: launchSelection, + selection: composerAgentSelection(launchSelection, orcaCloud), surface: quickAgentSurface, contextKey: observation.contextKey, onPick: handleQuickAgentChange diff --git a/src/renderer/src/components/OrcaSignInProgress.tsx b/src/renderer/src/components/OrcaSignInProgress.tsx index 10caa6e6dae..55fcbd11d2d 100644 --- a/src/renderer/src/components/OrcaSignInProgress.tsx +++ b/src/renderer/src/components/OrcaSignInProgress.tsx @@ -1,5 +1,7 @@ -import { Loader2 } from 'lucide-react' +import { useEffect } from 'react' +import { ExternalLink, Loader2 } from 'lucide-react' import { toast } from 'sonner' +import { registerSignInNotice } from '@/lib/orca-cloud/sign-in-notice-visibility' import { Button } from './ui/button' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' @@ -18,25 +20,31 @@ async function copySignInLink(link: string): Promise { } } +/** + * Never disabled by a pending sign-in, so a closed or lost tab can't strand the user. While the + * browser is out it reads "Reopen browser" and reopens the same sign-in link; otherwise a click + * starts a sign-in, replacing any pending one (main cancels it). + */ export function OrcaSignInButton({ children, - disabled, ...props }: Omit, 'onClick' | 'type'>): React.JSX.Element { const t = useTranslate() const connect = useAppStore((state) => state.connectCurrentOrcaProfile) - const signingIn = useAppStore((state) => Boolean(state.orcaProfileSignInProgress)) + const link = useAppStore((state) => state.orcaProfileSignInProgress?.link ?? null) + const onClick = (): void => { + if (!link) { + void connect() + return + } + void window.api.shell.openUrl(link).catch(() => void connect()) + } return ( - + + ) : null} · - - · - diff --git a/src/renderer/src/components/billing/PlanBillingUsage.tsx b/src/renderer/src/components/billing/PlanBillingUsage.tsx index c6cd5e128a5..116155244b8 100644 --- a/src/renderer/src/components/billing/PlanBillingUsage.tsx +++ b/src/renderer/src/components/billing/PlanBillingUsage.tsx @@ -9,7 +9,7 @@ import type { OrcaBillingEntitlement, OrcaBillingOverageArgs } from '../../../../shared/orca-billing' -import { formatHours, includedUsagePercent } from './plan-billing-format' +import { formatHours, formatHoursUsed, includedUsagePercent } from './plan-billing-format' import { includedUsageTone, sandboxHoursLeftLine, @@ -79,7 +79,7 @@ export function UsageSummary({ 'auto.components.billing.sandboxHoursUsedMonth', '{{value0}} of {{value1}} sandbox hours used this month', { - value0: formatHours(Math.min(entitlement.usedSeconds, entitlement.includedSeconds)), + value0: formatHoursUsed(Math.min(entitlement.usedSeconds, entitlement.includedSeconds)), value1: formatHours(entitlement.includedSeconds) } )} diff --git a/src/renderer/src/components/billing/checkout/use-checkout-flow.ts b/src/renderer/src/components/billing/checkout/use-checkout-flow.ts index 753c6b2afff..b4b983241bf 100644 --- a/src/renderer/src/components/billing/checkout/use-checkout-flow.ts +++ b/src/renderer/src/components/billing/checkout/use-checkout-flow.ts @@ -66,7 +66,7 @@ export function useCheckoutFlow({ onPaid }: { onPaid: (seats: number) => void }) // O1: a plan always lands on a team. The browser makes or picks the team, then Checkout; // the setup session switches this profile to that team when it's there. const started = await startCloudSetupSession({ needs: ['team', 'plan'], chooseTeam: true }) - return started ? { status: 'opened' } : result + return started && 'sessionId' in started ? { status: 'opened' } : result }) .then((result) => { if (id === runId.current) { diff --git a/src/renderer/src/components/billing/plan-billing-format.ts b/src/renderer/src/components/billing/plan-billing-format.ts index d839ccc4908..a604542ee6a 100644 --- a/src/renderer/src/components/billing/plan-billing-format.ts +++ b/src/renderer/src/components/billing/plan-billing-format.ts @@ -1,10 +1,45 @@ import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing' +// One rounding rule for sandbox hours on every surface (JA-07: home, billing, composer and the +// account menu showed four different numbers). Tenths of an hour; "left" rounds down and "used" +// rounds up, so the two always add up to the included amount and "left" never overstates. + +/** Absorbs float noise (177.4 h is 1773.9999… tenths) without moving a real boundary. */ +const TENTHS_EPSILON = 1e-6 + +/** Hours left, in tenths, rounded down. The last few minutes read 0.1, not a misleading 0. */ +export function sandboxHoursLeft(seconds: number): number { + if (seconds <= 0) { + return 0 + } + return Math.max(0.1, Math.floor(seconds / 360 + TENTHS_EPSILON) / 10) +} + +/** Hours used, in tenths, rounded up (any use at all reads at least 0.1). */ +export function sandboxHoursUsed(seconds: number): number { + if (seconds <= 0) { + return 0 + } + return Math.ceil(seconds / 360 - TENTHS_EPSILON) / 10 +} + +/** An amount of hours (included, offered), in tenths, rounded to nearest. */ +export function sandboxHoursAmount(seconds: number): number { + return Math.round(Math.max(0, seconds) / 360) / 10 +} + /** Hours with at most one decimal; whole numbers drop the decimal. */ export function formatHours(seconds: number): string { - const hours = Math.max(0, seconds) / 3600 - const rounded = Math.round(hours * 10) / 10 - return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1) + return formatHoursNumber(sandboxHoursAmount(seconds)) +} + +/** Used hours as text, rounded up like `sandboxHoursUsed`. */ +export function formatHoursUsed(seconds: number): string { + return formatHoursNumber(sandboxHoursUsed(seconds)) +} + +function formatHoursNumber(hours: number): string { + return Number.isInteger(hours) ? String(hours) : hours.toFixed(1) } /** Percent of included hours used, clamped to 0..100 (overage shows as full). */ diff --git a/src/renderer/src/components/billing/plan-billing-usage-copy.ts b/src/renderer/src/components/billing/plan-billing-usage-copy.ts index 54b3ca26c95..43685182d82 100644 --- a/src/renderer/src/components/billing/plan-billing-usage-copy.ts +++ b/src/renderer/src/components/billing/plan-billing-usage-copy.ts @@ -7,15 +7,20 @@ import { type OrcaBillingStatusResult } from '../../../../shared/orca-billing' import { usageAlertSentence } from '../../../../shared/orca-billing-usage-alerts' -import { includedUsagePercent } from './plan-billing-format' +import { + includedUsagePercent, + sandboxHoursAmount, + sandboxHoursLeft, + sandboxHoursUsed +} from './plan-billing-format' import { isActivePlan } from './team/team-seat-math' /** The included-hours bar turns to the warning tone from this share of the month's hours. */ export const INCLUDED_HOURS_WARNING_PERCENT = 90 -/** Hours as a plural count: one decimal, whole numbers without it (41.5, 78, 1). */ +/** Hours left as a plural count (41.5, 78, 1): the one rounding every surface uses (JA-07). */ export function sandboxHoursCount(seconds: number): number { - return Math.round(Math.max(0, seconds) / 360) / 10 + return sandboxHoursLeft(seconds) } export function includedUsageTone(entitlement: OrcaBillingEntitlement): 'default' | 'warning' { @@ -43,7 +48,7 @@ export function sandboxHoursOverLine( entitlement: OrcaBillingEntitlement, t: Translate ): string | null { - const count = sandboxHoursCount(hoursOverIncludedSeconds(entitlement)) + const count = sandboxHoursUsed(hoursOverIncludedSeconds(entitlement)) if (count <= 0) { return null } @@ -87,8 +92,8 @@ export function accountMenuUsageLines( /** "0.6 of 2 sandbox hours used": the trial's hours never reset, so no "this month". */ export function trialHoursUsedLine(entitlement: OrcaBillingEntitlement, t: Translate): string { return t('auto.components.billing.trialHoursUsed', '{{used}} of {{count}} sandbox hours used', { - used: String(sandboxHoursCount(Math.min(entitlement.usedSeconds, entitlement.includedSeconds))), - count: sandboxHoursCount(entitlement.includedSeconds), + used: String(sandboxHoursUsed(Math.min(entitlement.usedSeconds, entitlement.includedSeconds))), + count: sandboxHoursAmount(entitlement.includedSeconds), defaultValue_one: '{{used}} of {{count}} sandbox hour used' }) } diff --git a/src/renderer/src/components/billing/plan-billing-usage-history.test.ts b/src/renderer/src/components/billing/plan-billing-usage-history.test.ts index 770de7653b7..d740997011c 100644 --- a/src/renderer/src/components/billing/plan-billing-usage-history.test.ts +++ b/src/renderer/src/components/billing/plan-billing-usage-history.test.ts @@ -70,6 +70,15 @@ describe('top workspaces and members', () => { ]) }) + it('drops an others line that rounds to 0 hours', () => { + const history = { + ...sampleUsageHistory, + members: { top: [{ id: 'u-grace', seconds: 2 * HOUR }], otherCount: 1, otherSeconds: 30 } + } + const rows = topMemberRows(history, sampleUsageNames, translate)! + expect(rows.map((row) => row.label)).toEqual(['Grace Hopper']) + }) + it('titles workspaces and folds the rest into one line', () => { const rows = topWorkspaceRows(sampleUsageHistory, sampleUsageNames, translate)! expect(rows.map((row) => row.label)).toEqual([ diff --git a/src/renderer/src/components/billing/plan-billing-usage-history.ts b/src/renderer/src/components/billing/plan-billing-usage-history.ts index 91e8f1208c1..2b18122f94e 100644 --- a/src/renderer/src/components/billing/plan-billing-usage-history.ts +++ b/src/renderer/src/components/billing/plan-billing-usage-history.ts @@ -90,7 +90,8 @@ function rows( share: share(unknown.seconds, total) }) } - if (others.seconds > 0) { + // An others line that shows as 0 hours is noise: leave it out. + if (formatHours(others.seconds) !== '0') { list.push({ key: 'other', label: othersLabel(others.count), diff --git a/src/renderer/src/components/billing/plans/PlansView.tsx b/src/renderer/src/components/billing/plans/PlansView.tsx index 4a013f4efc8..39036f34880 100644 --- a/src/renderer/src/components/billing/plans/PlansView.tsx +++ b/src/renderer/src/components/billing/plans/PlansView.tsx @@ -15,7 +15,7 @@ import { PaymentIssueNotice } from '../PaymentIssueNotice' import { PlanStatusBadge } from '../PlanStatusBadge' import type { PlanBillingNotice } from '../PlanBillingSection' import { seatCountLabel } from '../team/team-copy' -import { formatHours, includedUsagePercent } from '../plan-billing-format' +import { formatHours, formatHoursUsed, includedUsagePercent } from '../plan-billing-format' import { includedUsageTone, sandboxHoursCount, @@ -131,7 +131,7 @@ function CurrentPlanStrip({ 'auto.components.billing.sandboxHoursUsedMonth', '{{value0}} of {{value1}} sandbox hours used this month', { - value0: formatHours(Math.min(entitlement.usedSeconds, entitlement.includedSeconds)), + value0: formatHoursUsed(Math.min(entitlement.usedSeconds, entitlement.includedSeconds)), value1: formatHours(entitlement.includedSeconds) } )} diff --git a/src/renderer/src/components/billing/sandbox-hours-agree.test.ts b/src/renderer/src/components/billing/sandbox-hours-agree.test.ts new file mode 100644 index 00000000000..d2cdf9588bc --- /dev/null +++ b/src/renderer/src/components/billing/sandbox-hours-agree.test.ts @@ -0,0 +1,42 @@ +// JA-07: home, Plan & billing, the composer and the account menu once showed four numbers for the +// same hours. Every surface now goes through one rounding rule; these pin it. +import { describe, expect, it } from 'vitest' +import { getOrcaCloudHoursLeft } from '../new-workspace/orca-cloud-run-target-access' +import { formatHoursUsed, sandboxHoursLeft, sandboxHoursUsed } from './plan-billing-format' +import { sandboxHoursCount } from './plan-billing-usage-copy' + +const HOUR = 3600 + +describe('sandbox hours: one rule on every surface', () => { + it('rounds left down and used up, in tenths', () => { + expect(sandboxHoursLeft(177.38 * HOUR)).toBe(177.3) + expect(sandboxHoursUsed(2.62 * HOUR)).toBe(2.7) + expect(formatHoursUsed(2.62 * HOUR)).toBe('2.7') + expect(sandboxHoursLeft(41 * HOUR)).toBe(41) + expect(sandboxHoursUsed(3 * HOUR)).toBe(3) + }) + + it('keeps the last minutes visible and never goes negative', () => { + expect(sandboxHoursLeft(60)).toBe(0.1) + expect(sandboxHoursLeft(0)).toBe(0) + expect(sandboxHoursLeft(-5)).toBe(0) + expect(sandboxHoursUsed(1)).toBe(0.1) + expect(sandboxHoursUsed(0)).toBe(0) + }) + + it('composer and account menu agree with Plan & billing', () => { + for (const left of [0.04, 0.5, 9.95, 10.04, 177.38, 177.42, 179.99]) { + const seconds = left * HOUR + expect(getOrcaCloudHoursLeft(seconds)).toBe(sandboxHoursCount(seconds)) + } + }) + + // The one exception is the last six minutes, where "left" holds at 0.1 on purpose. + it('used plus left adds up to the included hours', () => { + const included = 180 * HOUR + for (const usedSeconds of [1, 9420, 2.62 * HOUR, 90 * HOUR + 7, 179.8 * HOUR + 1]) { + const total = sandboxHoursUsed(usedSeconds) + sandboxHoursLeft(included - usedSeconds) + expect(Math.round(total * 10) / 10).toBe(180) + } + }) +}) diff --git a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts index 5870a9ccb9b..7d894746866 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts @@ -1,3 +1,4 @@ +import { consumeReopenAfterSleep } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep' import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useAppStore } from '@/store' import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/workspace/ownership/worktree-runtime-owner' @@ -147,6 +148,17 @@ export function useRemoteBrowserPageLifecycle({ state.removeRemoteBrowserPageHandle(browserTab.id, remotePageId) } lifecycle.abandonRemotePage() + // Slept with its VM (NEW-01): the tab stays. While asleep it waits; once the workspace is + // open again it opens a new host page at its URL. + if (state.asleepBrowserWorktreeIds[browserTab.worktreeId]) { + clearStreamFrame() + return + } + if (consumeReopenAfterSleep(browserTab.id)) { + clearStreamFrame() + lifecycle.open() + return + } if (remoteViewportTimerRef.current !== null) { window.clearTimeout(remoteViewportTimerRef.current) remoteViewportTimerRef.current = null @@ -166,6 +178,7 @@ export function useRemoteBrowserPageLifecycle({ [ browserTab.id, browserTab.workspaceId, + browserTab.worktreeId, clearStreamFrame, closeBrowserPage, closeBrowserTab, diff --git a/src/renderer/src/components/cloud-environment/EnvironmentForm.tsx b/src/renderer/src/components/cloud-environment/EnvironmentForm.tsx index fc7fb97d2fc..c31b1d202ec 100644 --- a/src/renderer/src/components/cloud-environment/EnvironmentForm.tsx +++ b/src/renderer/src/components/cloud-environment/EnvironmentForm.tsx @@ -124,7 +124,7 @@ export function EnvironmentForm({ {t( 'cloudEnvironment.form.importHint', - 'Reads Conductor and dev container setup from a local project.' + 'Reads Conductor and Dev Container setup from a local project.' )} {importProjects.map((project) => ( diff --git a/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx b/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx index 3477fad70f5..fc781c928d6 100644 --- a/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx +++ b/src/renderer/src/components/cloud-remote-desktop/CloudRemoteDesktopToast.tsx @@ -48,7 +48,7 @@ export function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): } case 'not_running': return { - title: t('components.cloudRemoteDesktop.asleepTitle', 'This sandbox is asleep.'), + title: t('components.cloudRemoteDesktop.asleepTitle', 'This workspace is asleep.'), detail: t( 'components.cloudRemoteDesktop.asleepDetail', 'Wake it to open the remote desktop. Your files are safe.' @@ -77,7 +77,7 @@ export function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): return { title: t( 'components.cloudRemoteDesktop.startingTitle', - 'The sandbox is still starting or waking.' + 'The workspace is still starting or waking.' ), detail: t( 'components.cloudRemoteDesktop.startingDetail', @@ -142,7 +142,7 @@ export function failureCopy(t: Translate, code: CloudRemoteDesktopToastFailure): export function actionLabel(t: Translate, action: CloudRemoteDesktopNextAction): string { switch (action) { case 'wake': - return t('components.cloudRemoteDesktop.wake', 'Wake sandbox') + return t('components.cloudRemoteDesktop.wake', 'Wake workspace') case 'unarchive': return t('components.cloudRemoteDesktop.unarchive', 'Unarchive') case 'sign_in': diff --git a/src/renderer/src/components/cloud-remote-desktop/RemoteDesktopPauseCard.fixture.tsx b/src/renderer/src/components/cloud-remote-desktop/RemoteDesktopPauseCard.fixture.tsx index 24226ec4f64..fdbd2a86daf 100644 --- a/src/renderer/src/components/cloud-remote-desktop/RemoteDesktopPauseCard.fixture.tsx +++ b/src/renderer/src/components/cloud-remote-desktop/RemoteDesktopPauseCard.fixture.tsx @@ -50,7 +50,7 @@ export const pausedDisconnected = pauseFixture( 'error' ) export const pausedAsleep = pauseFixture( - 'This sandbox is asleep. Wake it in Orca, then reconnect.', + 'This workspace is asleep. Wake it in Orca, then reconnect.', 'neutral' ) export const pausedArchived = pauseFixture( diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index ed97ac39407..f05aa90db3f 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -4,7 +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 { useIntlLocale, useTranslate } from '@/i18n/use-translate' +import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import type { @@ -23,7 +23,7 @@ import { useCloudHomeFilters } from './use-cloud-home-filters' import { CloudWorkspaceConfirmDialog, type PendingConfirm } from './CloudWorkspaceConfirmDialog' import { CloudReadSnapshotSheet } from './CloudReadSnapshotSheet' import { useCloudReadPanel } from './use-cloud-read-panel' -import { formatSandboxHours, sandboxHours, type MemberDirectory } from './cloud-workspace-format' +import type { MemberDirectory } from './cloud-workspace-format' import { refreshCloudMessageSenders } from '@/lib/cloud-message-sender' import { describeError } from './cloud-workspace-errors' import { focusCloudChat } from './cloud-chat-focus' @@ -76,7 +76,6 @@ export function CloudWorkspacesHome({ highlightId?: string | null }): React.JSX.Element | null { const t = useTranslate() - const intlLocale = useIntlLocale() const cloud = useAppStore((s) => s.orcaProfileAuthStatus?.cloud) const available = useCloudWorkspacesAvailable() const orgId = cloud?.activeOrgId @@ -149,10 +148,6 @@ export function CloudWorkspacesHome({ [directory, selfId, t] ) const routineRuns = state.status === 'ready' ? state.routineRuns : undefined - // Hidden routine runs leave the count but not the hours: they are still the team's usage. - const totalMs = - visible.reduce((sum, w) => sum + w.cost.computeMs, 0) + - (filters.routines ? 0 : (routineRuns?.hiddenComputeMs ?? 0)) /** Opens the workspace, then (going to a teammate's chat) the chat they have in front. */ const open = useCallback( @@ -265,18 +260,11 @@ export function CloudWorkspacesHome({ metaStale={stale} meta={ state.status === 'ready' - ? t('auto.components.cloudWorkspaces.listMeta2', '{{count}} workspaces · {{usage}}', { + ? // Why: no hours here. A sum over the listed workspaces isn't the team's month, and it + // disagreed with Plan & billing and the account menu (JA-07). + t('auto.components.cloudWorkspaces.listMetaCount', '{{count}} workspaces', { count: visible.length, - usage: t( - 'auto.components.cloudWorkspaces.listSandboxHours', - '{{hours}} sandbox hours used', - { - count: sandboxHours(totalMs), - hours: formatSandboxHours(totalMs, intlLocale), - defaultValue_one: '{{hours}} sandbox hour used' - } - ), - defaultValue_one: '{{count}} workspace · {{usage}}' + defaultValue_one: '{{count}} workspace' }) : null } diff --git a/src/renderer/src/components/new-workspace/NewWorkspaceComposerAgentSection.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerAgentSection.tsx index f31b3565d47..fe6436698b2 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerAgentSection.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerAgentSection.tsx @@ -59,7 +59,8 @@ export function NewWorkspaceComposerAgentSection({
diff --git a/src/renderer/src/components/new-workspace/composer-agent-cli.test.ts b/src/renderer/src/components/new-workspace/composer-agent-cli.test.ts new file mode 100644 index 00000000000..d57107cbbbe --- /dev/null +++ b/src/renderer/src/components/new-workspace/composer-agent-cli.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { composerAgentSelection } from './composer-agent-cli' + +describe('composerAgentSelection (PC-9)', () => { + it('Orca Cloud: the one Claude never reads "(CLI)"', () => { + expect(composerAgentSelection({ cli: true, ready: true }, true)).toEqual({ + cli: false, + ready: true + }) + }) + + it('this computer with a chat surface keeps "(CLI)" on the terminal pick', () => { + const local = { cli: true, ready: true } + expect(composerAgentSelection(local, false)).toBe(local) + }) +}) diff --git a/src/renderer/src/components/new-workspace/composer-agent-cli.ts b/src/renderer/src/components/new-workspace/composer-agent-cli.ts new file mode 100644 index 00000000000..2bf482cfdd6 --- /dev/null +++ b/src/renderer/src/components/new-workspace/composer-agent-cli.ts @@ -0,0 +1,8 @@ +// The closed agent picker says "Claude (CLI)" only when the same agent also has a chat to tell it +// apart from. Orca Cloud is terminal-only, so its one Claude is just "Claude" (PC-9). +export function composerAgentSelection( + selection: T, + orcaCloud: boolean +): T { + return orcaCloud && selection.cli ? { ...selection, cli: false } : selection +} diff --git a/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts b/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts index e3f1108c37d..28c1ebb3976 100644 --- a/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts +++ b/src/renderer/src/components/new-workspace/orca-cloud-run-target-access.ts @@ -1,6 +1,7 @@ import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' import { openPlansPage } from '@/components/billing/plans/plans-page-store' import { useAppStore } from '@/store/index' +import { sandboxHoursLeft } from '@/components/billing/plan-billing-format' import { cancelOrcaCloudSelectionAfterSignIn, requestOrcaCloudSelectionAfterSignIn @@ -153,14 +154,10 @@ function openOverageSettings(): void { state.openSettingsPage() } -/** Whole hours from 10 up, one decimal below so the last hours stay legible. */ +/** Hours left in tenths, rounded down: the one rule shared with Plan & billing. */ export function getOrcaCloudHoursLeft(remainingSeconds: number): number { - const hours = remainingSeconds / 3600 - if (hours >= 10) { - return Math.floor(hours) - } - // The last few minutes read 0.1 rather than a misleading 0 while starts are still allowed. - return remainingSeconds > 0 ? Math.max(0.1, Math.floor(hours * 10) / 10) : 0 + // Why: the same rounding as Plan & billing and the account menu, so every surface agrees (JA-07). + return sandboxHoursLeft(remainingSeconds) } /** Whether a create on Orca Cloud can start now (or may: still loading or unknown). */ diff --git a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx index 6c0301cabbc..255e7e0e41b 100644 --- a/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx +++ b/src/renderer/src/components/orca-cloud-setup/CloudSetupPage.tsx @@ -130,6 +130,11 @@ function BrowserWaiting({ flow }: { flow: CloudSetupFlow }): React.JSX.Element { {t('cloudSetupPage.waitingBrowser', 'Waiting for your browser…')} + {flow.signingIn ? ( + + ) : null} {flow.copyLink ? ( diff --git a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts index 680274cf170..4c7bd0b3e05 100644 --- a/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts +++ b/src/renderer/src/components/orca-cloud-setup/use-cloud-setup-flow.ts @@ -3,6 +3,7 @@ // one-trip setup session (#255) with its deep-link return (#257), B2's team switch, and the // tracker's error parsing (#260). Only the UI moved: from a card in the dialog to this page. import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useAppStore } from '@/store' import { claimOrcaCloudTrial } from '@/components/billing/claim-trial' import { invalidateOrcaCloudBilling, @@ -76,6 +77,13 @@ function useLiveAvailability( export type CloudSetupFlow = CloudSetupPageModel & { /** True from the click until the browser opens or the trial answers. */ busy: boolean + /** This page's browser sign-in is pending: the page offers Cancel and keeps Reopen browser live. */ + signingIn: boolean + /** The last sign-in stopped on its own (it timed out): "Sign-in didn’t finish. Try again." */ + signInDidNotFinish: boolean + cancelSignIn: () => void + /** Leaving setup (Back): cancels a sign-in this page started. */ + abandon: () => void /** The browser trip is open: the current step reads "Waiting for your browser". */ inBrowser: boolean error: ReturnType @@ -160,6 +168,12 @@ export function useCloudSetupFlow( [access, availability] ) + const runRef = useRef(0) + const [startedSignIn, setStartedSignIn] = useState(false) + const signInPending = useAppStore((state) => Boolean(state.orcaProfileSignInProgress)) + const signInTimedOut = useAppStore((state) => state.orcaProfileSignInEnd === 'timed-out') + const signingIn = busy && startedSignIn && signInPending + // One browser trip for everything still open from here (sign-in, team, trial or Checkout, GitHub). const continueInBrowser = useCallback(() => { const needs = sessionNeedsFrom(stepsRef.current) @@ -174,9 +188,19 @@ export function useCloudSetupFlow( fallback() return } + // Each click is a new run. An older run that ends late (its sign-in was replaced or cancelled) + // must not touch the page or open anything. + const run = ++runRef.current + const isCurrent = (): boolean => run === runRef.current setBusy(true) + setBrowserStep(null) + setStartedSignIn(cloudSetupPageModel(stepsRef.current).current?.id === 'account') void start({ repoId: request.repoId, needs }) .then((opened) => { + if (!isCurrent() || (opened && 'cancelled' in opened)) { + // Cancelled, timed out or replaced: back to the step's own button; nothing reopens. + return + } markInBrowser() if (opened) { setSessionId(opened.sessionId) @@ -184,10 +208,31 @@ export function useCloudSetupFlow( fallback() } }) - .catch(() => fallback()) - .finally(() => setBusy(false)) + .catch(() => { + if (isCurrent()) { + fallback() + } + }) + .finally(() => { + if (isCurrent()) { + setBusy(false) + setStartedSignIn(false) + } + }) }, [fallback, markInBrowser, openInstall, request.repoId]) + const cancelSignIn = useCallback(() => { + void window.api.orcaProfiles.cancelSignIn().catch(() => {}) + }, []) + + const abandon = useCallback(() => { + if (busy && startedSignIn) { + // Back means "not now": the tab this page opened must not sign in behind the user's back. + runRef.current++ + cancelSignIn() + } + }, [busy, cancelSignIn, startedSignIn]) + const startTrial = useCallback(() => { setBusy(true) void claimOrcaCloudTrial() @@ -215,7 +260,11 @@ export function useCloudSetupFlow( return { ...model, - busy, + busy: busy && !signingIn, + signingIn, + signInDidNotFinish: !busy && signInTimedOut && model.action === 'sign-in', + cancelSignIn, + abandon, inBrowser: browserStep !== null && (sessionId !== null || model.current?.id === browserStep), error, canManageBilling: access.state === 'no-plan' ? access.canManageBilling : true, diff --git a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx index 6d86e12acc1..3a806702159 100644 --- a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx +++ b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx @@ -1,4 +1,3 @@ -import { useReopenRemoteDesktopAfterWake } from '@/lib/cloud-remote-desktop/desktop-sleep-reopen' import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store' @@ -224,7 +223,6 @@ function useInertSiblings(cover: React.RefObject, active: bo function CloudSurface({ workspaceId }: { workspaceId: string }): React.JSX.Element | null { const t = useTranslate() const view = useCloudWorkspaceView(workspaceId) - useReopenRemoteDesktopAfterWake(workspaceId, view.state === 'running') const name = useAppStore((state) => findWorktreeById(state, workspaceId)?.displayName ?? null) // Ready means the server answers; the pill stays ("Connecting…") until the pane in front has // re-attached and can take keys. diff --git a/src/renderer/src/components/orca-cloud/offline/CloudAsleepFilesPanel.test.tsx b/src/renderer/src/components/orca-cloud/offline/CloudAsleepFilesPanel.test.tsx index 9e59f5470ca..cc50e09c7bf 100644 --- a/src/renderer/src/components/orca-cloud/offline/CloudAsleepFilesPanel.test.tsx +++ b/src/renderer/src/components/orca-cloud/offline/CloudAsleepFilesPanel.test.tsx @@ -114,4 +114,35 @@ describe('asleep Files tab (RA-10)', () => { container.querySelector('[data-cloud-asleep-files]')?.getAttribute('data-cloud-asleep-files') ).toBe('none') }) + + it('archived: says "archived", never "went to sleep", and offers no Wake (DS-h)', async () => { + serve( + snapshot({ + branch: 'master', + head: 'abc', + at: NOW - 47_000, + changeCount: 1, + changes: [{ path: 'README.md', status: 'M', area: 'unstaged' }], + commits: [] + }) + ) + const { container } = render() + await waitFor(() => expect(container.textContent).toContain('README.md')) + const text = container.textContent ?? '' + expect(text).toContain('Changed files when this workspace was archived · 47s ago') + expect(text).toContain('Unarchive the workspace to browse all its files.') + expect(text).not.toContain('sleep') + expect(container.querySelector('button')).toBeNull() + }) + + it('archived without a snapshot: the archived note, no Wake', async () => { + serve(null) + const { container } = render() + await waitFor(() => + expect(container.textContent).toContain( + 'Files aren’t available while the workspace is archived.' + ) + ) + expect(container.querySelector('button')).toBeNull() + }) }) diff --git a/src/renderer/src/components/orca-cloud/offline/CloudAsleepFilesPanel.tsx b/src/renderer/src/components/orca-cloud/offline/CloudAsleepFilesPanel.tsx index 97910b16f5e..a38262eecbc 100644 --- a/src/renderer/src/components/orca-cloud/offline/CloudAsleepFilesPanel.tsx +++ b/src/renderer/src/components/orca-cloud/offline/CloudAsleepFilesPanel.tsx @@ -35,17 +35,23 @@ export function formatWhen(at: number, now: number, locale: string, t: Translate */ export function CloudAsleepFilesPanel({ workspaceId, - waking = false + waking = false, + archived = false }: { workspaceId: string /** Opening an asleep workspace wakes it: the files arrive when it is up, nothing to press. */ waking?: boolean + /** + * Archived, not asleep (DS-h): the copy says "archived", and there is no Wake here, since the + * archived view beside it already has Unarchive as its one action. + */ + archived?: boolean }): React.JSX.Element { const t = useTranslate() const { snapshot } = useCloudOfflineData(workspaceId, true) const now = useNow(30_000) const git = snapshot?.git ?? null - const wake = waking ? ( + const wake = archived ? null : waking ? (