mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 02:47:34 +00:00
Merge remote-tracking branch 'private/cloud/integration' into train/375
# Conflicts: # src/renderer/src/i18n/locales/en.json
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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')
|
||||
}
|
||||
@@ -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, `<name>.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)
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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<AgentConfigItemKind, AgentConfigItemKind[]> = {
|
||||
'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<string>
|
||||
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<string>()
|
||||
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<string> = 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 }
|
||||
})
|
||||
}
|
||||
@@ -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<CloudAgentConfigSyncPreferences> {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return {}
|
||||
}
|
||||
const raw = value as Record<string, unknown>
|
||||
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
|
||||
)
|
||||
}
|
||||
@@ -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<ReadonlySet<string>> {
|
||||
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)
|
||||
: []
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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<LocalAgentConfigItem[]>
|
||||
call?: (
|
||||
environmentId: string,
|
||||
method: string,
|
||||
params: unknown,
|
||||
timeoutMs: number
|
||||
) => Promise<unknown>
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
export type CloudAgentConfigSync = {
|
||||
isCloudEnvironment(environmentId: string): boolean
|
||||
getStatus(environmentId: string): Promise<AgentConfigSyncStatus | null>
|
||||
sync(environmentId: string, trigger: 'connect' | 'manual'): Promise<AgentConfigSyncStatus | null>
|
||||
/** Settles once saved preferences are read; getPreferences answers defaults until then. */
|
||||
ready: Promise<void>
|
||||
getPreferences(): CloudAgentConfigSyncPreferences
|
||||
setPreferences(next: Partial<CloudAgentConfigSyncPreferences>): 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<string, AgentConfigSyncStatus>()
|
||||
const queues = new Map<string, Promise<unknown>>()
|
||||
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<AgentConfigSyncStatus> {
|
||||
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<AgentConfigSyncStatus> {
|
||||
// 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>
|
||||
): 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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'])
|
||||
})
|
||||
})
|
||||
@@ -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<AgentConfigSkipReason, 'in-repo' | 'too-large' | 'secret' | 'invalid'>
|
||||
}
|
||||
|
||||
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<ReadonlySet<string> | 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<boolean> {
|
||||
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<Walked> {
|
||||
const root = await realpath(dir)
|
||||
const files: AgentConfigDigestEntry[] = []
|
||||
let withheld = 0
|
||||
let bytes = 0
|
||||
const visit = async (current: string, depth: number): Promise<Walked | null> => {
|
||||
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<boolean> {
|
||||
return (await stat(path).catch(() => null))?.isDirectory() === true
|
||||
}
|
||||
|
||||
async function isFile(path: string): Promise<boolean> {
|
||||
return (await stat(path).catch(() => null))?.isFile() === true
|
||||
}
|
||||
|
||||
async function readSkills(
|
||||
root: string,
|
||||
kind: AgentConfigItemKind,
|
||||
scope: AgentConfigItemScope
|
||||
): Promise<LocalAgentConfigItem[]> {
|
||||
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<LocalAgentConfigItem[]> {
|
||||
const maxDepth = kind === 'codex-prompt' ? 0 : 2
|
||||
const items: LocalAgentConfigItem[] = []
|
||||
const visit = async (dir: string, depth: number): Promise<void> => {
|
||||
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['skipReason']>
|
||||
): 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<LocalAgentConfigItem[]> {
|
||||
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
|
||||
}
|
||||
@@ -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<string, Promise<string>>()
|
||||
|
||||
async function load(userDataPath: string): Promise<string> {
|
||||
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<string> {
|
||||
let id = cache.get(userDataPath)
|
||||
if (!id) {
|
||||
id = load(userDataPath)
|
||||
cache.set(userDataPath, id)
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -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<string, string> }
|
||||
|
||||
export function ledgerPath(ledgerDir: string, syncer: string): string {
|
||||
return join(ledgerDir, `agent-config-sync-ledger-${syncer}.json`)
|
||||
}
|
||||
|
||||
export async function readLedger(path: string): Promise<Ledger> {
|
||||
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<string, string> = {}
|
||||
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<void> {
|
||||
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<void> {
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -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<string, unknown> = {}) => ({
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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<string | null> {
|
||||
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<boolean> => {
|
||||
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<AgentConfigSyncPlanResult> {
|
||||
const path = ledgerPath(deps.ledgerDir, params.syncer)
|
||||
const ledger = await readLedger(path)
|
||||
const items: Record<string, AgentConfigPlanOutcome> = {}
|
||||
const wanted = new Set<string>()
|
||||
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<string>()
|
||||
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<void> {
|
||||
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<AgentConfigSyncPutResult> {
|
||||
const path = ledgerPath(deps.ledgerDir, params.syncer)
|
||||
const ledger = await readLedger(path)
|
||||
const items: Record<string, AgentConfigPutOutcome> = {}
|
||||
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<Record<string, number>>((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 }
|
||||
}
|
||||
@@ -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<string> => 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 {
|
||||
|
||||
@@ -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<string, CloudSandboxPresence>
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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 "<name> (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<string, CloudPairingBinding>
|
||||
|
||||
/** 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<void>
|
||||
/** The sandbox was deleted from here: drop its pairing now, no fetch needed. */
|
||||
forget(sandboxId: string): Promise<void>
|
||||
/** A pairing was just saved: stamp it with the active team. */
|
||||
accountForNewBinding(): string | null
|
||||
}
|
||||
|
||||
export function createCloudPairingPrune(deps: {
|
||||
activeAccountId: () => string | null
|
||||
readBindings: () => Promise<CloudPairingBindings>
|
||||
updateBindings: (change: (current: CloudPairingBindings) => CloudPairingBindings) => Promise<void>
|
||||
/** Ids of every sandbox the active team's list shows this user; null when the list failed. */
|
||||
listVisible: () => Promise<ReadonlySet<string> | null>
|
||||
/** One fetch of a single sandbox. */
|
||||
presence: (sandboxId: string) => Promise<CloudSandboxPresence>
|
||||
/** Remove the paired server; the window's catalog refresh then purges its projects. */
|
||||
removeEnvironment: (environmentId: string) => Promise<void>
|
||||
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<void> | null = null
|
||||
|
||||
async function forget(sandboxId: string): Promise<void> {
|
||||
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<void> {
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
})
|
||||
|
||||
@@ -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(
|
||||
{
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
// This device's pairings with cloud workspaces it does not own (the "<name> (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<CloudWorkspacesService | null>
|
||||
|
||||
export type CloudWorkspacesPairings = {
|
||||
prune: CloudPairingPrune
|
||||
readBindings: () => Promise<Record<string, Binding>>
|
||||
updateBindings: (
|
||||
change: (current: Record<string, Binding>) => Record<string, Binding>
|
||||
) => Promise<void>
|
||||
}
|
||||
|
||||
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<Record<string, Binding>> {
|
||||
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<void> = Promise.resolve()
|
||||
|
||||
/** Temp file + rename so a crash mid-write never leaves a truncated bindings file. */
|
||||
function updateBindings(
|
||||
change: (current: Record<string, Binding>) => Record<string, Binding>
|
||||
): Promise<void> {
|
||||
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<CloudSandboxPresence> {
|
||||
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
|
||||
}
|
||||
@@ -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<string> {
|
||||
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<Record<string, Binding>> {
|
||||
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<void> = Promise.resolve()
|
||||
|
||||
/** Temp file + rename so a crash mid-write never leaves a truncated bindings file. */
|
||||
function updateBindings(
|
||||
change: (current: Record<string, Binding>) => Record<string, Binding>
|
||||
): Promise<void> {
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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<unknown>
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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') {
|
||||
|
||||
@@ -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' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<void>((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'])
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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<ProgressListener>()
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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<number, { pid: number; commandLine: string }> = {
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<RawListeningPort, 'pid' | 'commandLine' | 'port'>,
|
||||
config: HostManagedListenerConfig,
|
||||
serverPid: number = process.pid
|
||||
): boolean {
|
||||
serverPid: number = process.pid,
|
||||
readParent: (pid: number) => Promise<ParentProcess | undefined> = readLinuxParentProcess
|
||||
): Promise<boolean> {
|
||||
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<ParentProcess | undefined> {
|
||||
if (process.platform !== 'linux') {
|
||||
return undefined
|
||||
}
|
||||
try {
|
||||
// /proc/<pid>/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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
})
|
||||
]
|
||||
|
||||
@@ -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'))
|
||||
|
||||
@@ -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<ConnectCurrentOrcaProfileResult>
|
||||
signInProgress: () => Promise<OrcaCloudSignInProgress | null>
|
||||
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<void>
|
||||
refreshAuth: () => Promise<RefreshCurrentOrcaProfileAuthResult>
|
||||
|
||||
@@ -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)
|
||||
},
|
||||
|
||||
@@ -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<CloudMcpSyncPreferences | null>
|
||||
onMcpSyncChanged?: (callback: (status: McpSyncStatus) => void) => () => void
|
||||
// Orca Cloud skills and slash commands sync; desktop only, like MCP sync.
|
||||
getAgentConfigSyncStatus?: (environmentId: string) => Promise<AgentConfigSyncStatus | null>
|
||||
syncAgentConfigNow?: (environmentId: string) => Promise<AgentConfigSyncStatus | null>
|
||||
getAgentConfigSyncPreferences?: () => Promise<CloudAgentConfigSyncPreferences | null>
|
||||
setAgentConfigSyncPreferences?: (
|
||||
preferences: Partial<Omit<CloudAgentConfigSyncPreferences, 'excluded'>>
|
||||
) => Promise<CloudAgentConfigSyncPreferences | null>
|
||||
setAgentConfigItemIncluded?: (
|
||||
key: string,
|
||||
included: boolean
|
||||
) => Promise<CloudAgentConfigSyncPreferences | null>
|
||||
onAgentConfigSyncChanged?: (callback: (status: AgentConfigSyncStatus) => void) => () => void
|
||||
onAgentConfigSyncPreferencesChanged?: (
|
||||
callback: (preferences: CloudAgentConfigSyncPreferences) => void
|
||||
) => () => void
|
||||
getStatusSnapshots: () => Promise<RuntimeHostStatusSnapshot[]>
|
||||
onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void) => () => void
|
||||
// Absent in the web client, whose catalog lives in the browser rather than a CLI-editable file.
|
||||
|
||||
@@ -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<AgentConfigSyncStatus | null> =>
|
||||
ipcRenderer.invoke('cloudAgentConfigSync:getStatus', environmentId),
|
||||
syncAgentConfigNow: (environmentId: string): Promise<AgentConfigSyncStatus | null> =>
|
||||
ipcRenderer.invoke('cloudAgentConfigSync:syncNow', environmentId),
|
||||
getAgentConfigSyncPreferences: (): Promise<CloudAgentConfigSyncPreferences | null> =>
|
||||
ipcRenderer.invoke('cloudAgentConfigSync:getPreferences'),
|
||||
setAgentConfigSyncPreferences: (
|
||||
preferences: Partial<Omit<CloudAgentConfigSyncPreferences, 'excluded'>>
|
||||
): Promise<CloudAgentConfigSyncPreferences | null> =>
|
||||
ipcRenderer.invoke('cloudAgentConfigSync:setPreferences', preferences),
|
||||
setAgentConfigItemIncluded: (
|
||||
key: string,
|
||||
included: boolean
|
||||
): Promise<CloudAgentConfigSyncPreferences | null> =>
|
||||
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<RuntimeHostStatusSnapshot[]> =>
|
||||
ipcRenderer.invoke('runtimeEnvironments:getStatusSnapshots'),
|
||||
onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void): (() => void) => {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<React.ComponentProps<typeof Button>, '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 (
|
||||
<Button
|
||||
{...props}
|
||||
type="button"
|
||||
disabled={disabled || signingIn}
|
||||
onClick={() => void connect()}
|
||||
>
|
||||
{signingIn ? (
|
||||
<Button {...props} type="button" onClick={onClick}>
|
||||
{link ? (
|
||||
<>
|
||||
<Loader2 className="animate-spin" />
|
||||
{t('auto.components.OrcaSignInProgress.signingIn', 'Signing in…')}
|
||||
{t('auto.components.OrcaSignInProgress.reopenBrowser', 'Reopen browser')}
|
||||
<ExternalLink aria-hidden />
|
||||
</>
|
||||
) : (
|
||||
children
|
||||
@@ -45,16 +53,32 @@ export function OrcaSignInButton({
|
||||
)
|
||||
}
|
||||
|
||||
function cancelSignIn(): void {
|
||||
void window.api.orcaProfiles.cancelSignIn().catch(() => {})
|
||||
}
|
||||
|
||||
export function OrcaSignInWaitNotice({
|
||||
className
|
||||
}: {
|
||||
className?: string
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const link = useAppStore((state) => state.orcaProfileSignInProgress?.link)
|
||||
if (!link) {
|
||||
return null
|
||||
const progress = useAppStore((state) => state.orcaProfileSignInProgress)
|
||||
const timedOut = useAppStore((state) => state.orcaProfileSignInEnd === 'timed-out')
|
||||
const signedIn = useAppStore((state) => state.orcaProfileAuthStatus?.state === 'connected')
|
||||
// While this is on screen a timeout is said here, not in a toast.
|
||||
useEffect(() => registerSignInNotice(), [])
|
||||
if (!progress) {
|
||||
if (!timedOut || signedIn) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<p role="status" className={cn('text-xs text-muted-foreground', className)}>
|
||||
{t('auto.components.OrcaSignInProgress.didNotFinish', 'Sign-in didn’t finish. Try again.')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
const link = progress.link
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
@@ -63,20 +87,22 @@ export function OrcaSignInWaitNotice({
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Loader2 className="mr-1.5 size-3 motion-safe:animate-spin" aria-hidden />
|
||||
<span className="pr-2">
|
||||
{t('auto.components.OrcaSignInProgress.waiting', 'Waiting for sign-in in your browser')}
|
||||
{link
|
||||
? t('auto.components.OrcaSignInProgress.waiting', 'Waiting for sign-in in your browser')
|
||||
: t('auto.components.OrcaSignInProgress.signingIn', 'Signing in…')}
|
||||
</span>
|
||||
{link ? (
|
||||
<>
|
||||
<span aria-hidden>·</span>
|
||||
<Button type="button" variant="link" size="xs" onClick={() => void copySignInLink(link)}>
|
||||
{t('auto.components.OrcaSignInProgress.copyLink', 'Copy sign-in link')}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
<span aria-hidden>·</span>
|
||||
<Button type="button" variant="link" size="xs" onClick={() => void copySignInLink(link)}>
|
||||
{t('auto.components.OrcaSignInProgress.copyLink', 'Copy sign-in link')}
|
||||
</Button>
|
||||
<span aria-hidden>·</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
size="xs"
|
||||
onClick={() => void window.api.orcaProfiles.cancelSignIn().catch(() => {})}
|
||||
>
|
||||
<Button type="button" variant="link" size="xs" onClick={cancelSignIn}>
|
||||
{t('auto.components.OrcaSignInProgress.cancel', 'Cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
)}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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). */
|
||||
|
||||
@@ -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'
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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([
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
)}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
})
|
||||
+13
@@ -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,
|
||||
|
||||
@@ -124,7 +124,7 @@ export function EnvironmentForm({
|
||||
<DropdownMenuLabel variant="hint">
|
||||
{t(
|
||||
'cloudEnvironment.form.importHint',
|
||||
'Reads Conductor and dev container setup from a local project.'
|
||||
'Reads Conductor and Dev Container setup from a local project.'
|
||||
)}
|
||||
</DropdownMenuLabel>
|
||||
{importProjects.map((project) => (
|
||||
|
||||
@@ -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':
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -59,7 +59,8 @@ export function NewWorkspaceComposerAgentSection({
|
||||
<div className="min-w-0 space-y-1" data-contextual-tour-target="workspace-creation-agent">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<label className="text-xs font-medium text-muted-foreground">
|
||||
{t('components.newWorkspace.agentOptional', 'Agent (optional)')}
|
||||
{/* Optional is implied by the Blank terminal default (PC-9). */}
|
||||
{t('components.newWorkspace.agentLabel', 'Agent')}
|
||||
</label>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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<T extends { cli?: boolean }>(
|
||||
selection: T,
|
||||
orcaCloud: boolean
|
||||
): T {
|
||||
return orcaCloud && selection.cli ? { ...selection, cli: false } : selection
|
||||
}
|
||||
@@ -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). */
|
||||
|
||||
@@ -130,6 +130,11 @@ function BrowserWaiting({ flow }: { flow: CloudSetupFlow }): React.JSX.Element {
|
||||
{t('cloudSetupPage.waitingBrowser', 'Waiting for your browser…')}
|
||||
</span>
|
||||
<span className="ms-auto flex items-center gap-2">
|
||||
{flow.signingIn ? (
|
||||
<Button type="button" variant="ghost" size="sm" onClick={flow.cancelSignIn}>
|
||||
{t('cloudSetupPage.cancelSignIn', 'Cancel')}
|
||||
</Button>
|
||||
) : null}
|
||||
{flow.copyLink ? (
|
||||
<Button type="button" variant="ghost" size="sm" onClick={flow.copyLink}>
|
||||
<Copy aria-hidden />
|
||||
@@ -159,12 +164,22 @@ function StepActions({ flow }: { flow: CloudSetupFlow }): React.JSX.Element | nu
|
||||
flow.action === 'choose-plan' ||
|
||||
flow.action === 'fix-billing' ||
|
||||
flow.action === 'github-install'
|
||||
if (flow.inBrowser && inBrowserAction && !flow.error) {
|
||||
if (flow.signingIn || (flow.inBrowser && inBrowserAction && !flow.error)) {
|
||||
return <BrowserWaiting flow={flow} />
|
||||
}
|
||||
const continueLabel = t('cloudSetupPage.continueInBrowser', 'Continue in browser')
|
||||
switch (flow.action) {
|
||||
case 'sign-in':
|
||||
return flow.signInDidNotFinish ? (
|
||||
<div className="flex flex-col items-start gap-3">
|
||||
<p role="status" className="text-sm text-muted-foreground">
|
||||
{t('cloudSetupPage.signIn.didNotFinish', 'Sign-in didn’t finish. Try again.')}
|
||||
</p>
|
||||
{browser(continueLabel, flow.continueInBrowser)}
|
||||
</div>
|
||||
) : (
|
||||
browser(continueLabel, flow.continueInBrowser)
|
||||
)
|
||||
case 'choose-plan':
|
||||
return browser(continueLabel, flow.continueInBrowser)
|
||||
case 'fix-billing':
|
||||
@@ -269,9 +284,16 @@ export function CloudSetupPage({
|
||||
setViewing(previous.id)
|
||||
return
|
||||
}
|
||||
// Leaving setup cancels a sign-in this page started (it must not finish behind the user).
|
||||
flow.abandon()
|
||||
onBackToComposer()
|
||||
}
|
||||
|
||||
const exit = (): void => {
|
||||
flow.abandon()
|
||||
onExit()
|
||||
}
|
||||
|
||||
// Each new step moves focus to its heading so screen readers hear the change once.
|
||||
const stepKey = `${viewing ?? shown.current?.id ?? 'done'}:${shown.action}`
|
||||
React.useEffect(() => {
|
||||
@@ -311,7 +333,7 @@ export function CloudSetupPage({
|
||||
size="icon-sm"
|
||||
aria-label={t('cloudSetupPage.exit', 'Exit setup')}
|
||||
title={t('cloudSetupPage.exit', 'Exit setup')}
|
||||
onClick={onExit}
|
||||
onClick={exit}
|
||||
>
|
||||
<X aria-hidden />
|
||||
</Button>
|
||||
|
||||
@@ -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<typeof parseCloudSetupError>
|
||||
@@ -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,
|
||||
|
||||
@@ -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<HTMLElement | null>, 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.
|
||||
|
||||
@@ -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(<CloudAsleepFilesPanel workspaceId="ws" archived />)
|
||||
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(<CloudAsleepFilesPanel workspaceId="ws" archived />)
|
||||
await waitFor(() =>
|
||||
expect(container.textContent).toContain(
|
||||
'Files aren’t available while the workspace is archived.'
|
||||
)
|
||||
)
|
||||
expect(container.querySelector('button')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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 ? (
|
||||
<span className="inline-flex items-center gap-1.5 text-muted-foreground" role="status">
|
||||
<Loader2 className="size-3 motion-safe:animate-spin" aria-hidden="true" />
|
||||
{t('orcaCloudWorkspace.files.waking', 'Waking… the files show when it’s up.')}
|
||||
@@ -63,14 +69,24 @@ export function CloudAsleepFilesPanel({
|
||||
>
|
||||
{git ? (
|
||||
<>
|
||||
<SavedChanges git={git} at={snapshot?.capturedAt ?? null} now={now} />
|
||||
<SavedChanges
|
||||
git={git}
|
||||
at={snapshot?.capturedAt ?? null}
|
||||
now={now}
|
||||
archived={archived}
|
||||
/>
|
||||
<RecentCommits git={git} now={now} />
|
||||
<div className="flex flex-col items-start gap-2 border-t border-border/60 pt-3 text-muted-foreground">
|
||||
<p>
|
||||
{t(
|
||||
'orcaCloudWorkspace.files.wakeForAll',
|
||||
'Wake the workspace to browse all its files.'
|
||||
)}
|
||||
{archived
|
||||
? t(
|
||||
'orcaCloudWorkspace.files.unarchiveForAll',
|
||||
'Unarchive the workspace to browse all its files.'
|
||||
)
|
||||
: t(
|
||||
'orcaCloudWorkspace.files.wakeForAll',
|
||||
'Wake the workspace to browse all its files.'
|
||||
)}
|
||||
</p>
|
||||
{wake}
|
||||
</div>
|
||||
@@ -78,10 +94,15 @@ export function CloudAsleepFilesPanel({
|
||||
) : (
|
||||
<div className="flex flex-col items-start gap-2 text-muted-foreground">
|
||||
<p>
|
||||
{t(
|
||||
'orcaCloudWorkspace.files.asleep',
|
||||
'Files aren’t available while the workspace is asleep.'
|
||||
)}
|
||||
{archived
|
||||
? t(
|
||||
'orcaCloudWorkspace.files.archived',
|
||||
'Files aren’t available while the workspace is archived.'
|
||||
)
|
||||
: t(
|
||||
'orcaCloudWorkspace.files.asleep',
|
||||
'Files aren’t available while the workspace is asleep.'
|
||||
)}
|
||||
</p>
|
||||
{wake}
|
||||
</div>
|
||||
@@ -95,11 +116,13 @@ type Git = NonNullable<CloudOfflineSnapshot['git']>
|
||||
function SavedChanges({
|
||||
git,
|
||||
at,
|
||||
now
|
||||
now,
|
||||
archived
|
||||
}: {
|
||||
git: Git
|
||||
at: number | null
|
||||
now: number
|
||||
archived: boolean
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
@@ -107,7 +130,18 @@ function SavedChanges({
|
||||
if (git.changes.length === 0 && git.changeCount === 0) {
|
||||
return (
|
||||
<p className="text-muted-foreground">
|
||||
{time
|
||||
{archived
|
||||
? time
|
||||
? t(
|
||||
'orcaCloudWorkspace.files.noChangesAtArchive',
|
||||
'No files had changed when this workspace was archived · {{time}}',
|
||||
{ time }
|
||||
)
|
||||
: t(
|
||||
'orcaCloudWorkspace.files.noChangesAtArchiveNoTime',
|
||||
'No files had changed when this workspace was archived'
|
||||
)
|
||||
: time
|
||||
? t(
|
||||
'orcaCloudWorkspace.files.noChangesAtSleep',
|
||||
'No files had changed when this workspace went to sleep · {{time}}',
|
||||
@@ -127,7 +161,18 @@ function SavedChanges({
|
||||
aria-label={t('orcaCloudWorkspace.files.changedTitle', 'Changed files')}
|
||||
>
|
||||
<h3 className="font-medium text-foreground">
|
||||
{time
|
||||
{archived
|
||||
? time
|
||||
? t(
|
||||
'orcaCloudWorkspace.files.changedAtArchive',
|
||||
'Changed files when this workspace was archived · {{time}}',
|
||||
{ time }
|
||||
)
|
||||
: t(
|
||||
'orcaCloudWorkspace.files.changedAtArchiveNoTime',
|
||||
'Changed files when this workspace was archived'
|
||||
)
|
||||
: time
|
||||
? t(
|
||||
'orcaCloudWorkspace.files.changedAtSleep',
|
||||
'Changed files when this workspace went to sleep · {{time}}',
|
||||
|
||||
@@ -3,9 +3,14 @@ import { useCloudWorkspaceView } from '../use-cloud-workspace-view'
|
||||
|
||||
/**
|
||||
* The active workspace when it is an Orca Cloud workspace whose files can't be read right now:
|
||||
* asleep, waking (opening one wakes it), or failed to wake. `waking` says which.
|
||||
* asleep, waking (opening one wakes it), failed to wake, or archived. `waking` and `archived` say
|
||||
* which (an archived one is suspended too, but its copy must say archived, not asleep: DS-h).
|
||||
*/
|
||||
export function useAsleepCloudWorkspace(): { id: string; waking: boolean } | null {
|
||||
export function useAsleepCloudWorkspace(): {
|
||||
id: string
|
||||
waking: boolean
|
||||
archived: boolean
|
||||
} | null {
|
||||
const activeWorktreeId = useAppStore((state) => state.activeWorktreeId)
|
||||
const view = useCloudWorkspaceView(activeWorktreeId ?? '')
|
||||
// The local VM record flips as soon as this computer puts it to sleep; the control plane's status
|
||||
@@ -20,9 +25,12 @@ export function useAsleepCloudWorkspace(): { id: string; waking: boolean } | nul
|
||||
return null
|
||||
}
|
||||
if (view.state === 'waking' || view.state === 'starting') {
|
||||
return { id: activeWorktreeId, waking: true }
|
||||
return { id: activeWorktreeId, waking: true, archived: false }
|
||||
}
|
||||
if (view.state === 'archived') {
|
||||
return { id: activeWorktreeId, waking: false, archived: true }
|
||||
}
|
||||
return view.state === 'sleeping' || view.state === 'wakeFailed' || vmSuspended
|
||||
? { id: activeWorktreeId, waking: false }
|
||||
? { id: activeWorktreeId, waking: false, archived: false }
|
||||
: null
|
||||
}
|
||||
|
||||
@@ -73,4 +73,18 @@ describe('terminal error toast on an Orca Cloud workspace that sleeps', () => {
|
||||
const unrelated = render(toast('ws', 'spawn failed: ENOENT'))
|
||||
expect(unrelated.container.querySelector('[data-terminal-error-toast]')).not.toBeNull()
|
||||
})
|
||||
|
||||
// Glossary lint allowlists these two "VM" match patterns because they are never rendered. If
|
||||
// that ever changes, this fails before the banned word reaches a cloud user.
|
||||
it('never renders the legacy "VM" sleep errors it matches (glossary allowlist)', () => {
|
||||
seed('sleeping')
|
||||
for (const error of [
|
||||
"This workspace's VM is asleep",
|
||||
"This workspace's VM could not wake up"
|
||||
]) {
|
||||
const { container, unmount } = render(toast('ws', error))
|
||||
expect(container.textContent).not.toMatch(/\bVM\b/)
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
// JA-33: sign-out names what matters, cloud workspaces.
|
||||
import { defineFixture } from '../../component-fixtures/component-fixture'
|
||||
import { OrcaProfileSignOutConfirmDialog } from './OrcaProfileSignOutConfirmDialog'
|
||||
|
||||
export const open = defineFixture({
|
||||
width: 520,
|
||||
render: () => (
|
||||
<OrcaProfileSignOutConfirmDialog
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
onConfirm={() => {}}
|
||||
signingOut={false}
|
||||
/>
|
||||
)
|
||||
})
|
||||
@@ -31,8 +31,8 @@ export function OrcaProfileSignOutConfirmDialog({
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t(
|
||||
'auto.components.orca.profiles.signout.confirm.description',
|
||||
"Artifacts and Orca Relay will be unavailable until you sign in again. Your local projects and worktrees won't be affected."
|
||||
'auto.components.orca.profiles.signout.confirm.description2',
|
||||
"You'll lose access to your cloud workspaces until you sign in again. Local workspaces aren't affected."
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
+7
-1
@@ -137,7 +137,13 @@ export function FileExplorerFilesTreePane({
|
||||
// An asleep Orca Cloud workspace has no tree to read: its saved changes and Wake, not an error.
|
||||
const asleepCloud = useAsleepCloudWorkspace()
|
||||
if (asleepCloud) {
|
||||
return <CloudAsleepFilesPanel workspaceId={asleepCloud.id} waking={asleepCloud.waking} />
|
||||
return (
|
||||
<CloudAsleepFilesPanel
|
||||
workspaceId={asleepCloud.id}
|
||||
waking={asleepCloud.waking}
|
||||
archived={asleepCloud.archived}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
+32
-3
@@ -1,13 +1,27 @@
|
||||
import { defineFixture } from '../../../../component-fixtures/component-fixture'
|
||||
import type { OrcaProfileAuthStatus } from '../../../../../../shared/orca-profiles'
|
||||
import type {
|
||||
OrcaCloudSignInEnd,
|
||||
OrcaCloudSignInProgress,
|
||||
OrcaProfileAuthStatus
|
||||
} from '../../../../../../shared/orca-profiles'
|
||||
import { OrcaAccountSettingsPane } from './OrcaAccountSettingsPane'
|
||||
|
||||
const width = 760
|
||||
|
||||
function pane(status: OrcaProfileAuthStatus) {
|
||||
function pane(
|
||||
status: OrcaProfileAuthStatus,
|
||||
signIn: {
|
||||
progress?: OrcaCloudSignInProgress | null
|
||||
end?: OrcaCloudSignInEnd | null
|
||||
} = {}
|
||||
) {
|
||||
return defineFixture({
|
||||
width,
|
||||
store: { orcaProfileAuthStatus: status },
|
||||
store: {
|
||||
orcaProfileAuthStatus: status,
|
||||
orcaProfileSignInProgress: signIn.progress ?? null,
|
||||
orcaProfileSignInEnd: signIn.end ?? null
|
||||
},
|
||||
// The pane re-reads auth status on mount; answer with the same state so the frame holds it.
|
||||
setup: () => {
|
||||
Object.assign(window.api.orcaProfiles, { authStatus: () => Promise.resolve(status) })
|
||||
@@ -31,3 +45,18 @@ export const reconnectRequired = pane({
|
||||
state: 'reconnect-required',
|
||||
persistence: 'encrypted'
|
||||
})
|
||||
|
||||
const signedOutStatus: OrcaProfileAuthStatus = {
|
||||
activeProfileId: 'default',
|
||||
configured: true,
|
||||
state: 'local',
|
||||
persistence: 'none'
|
||||
}
|
||||
|
||||
/** Waiting on the browser: the primary stays live as "Reopen browser"; the line offers Cancel. */
|
||||
export const signInPending = pane(signedOutStatus, {
|
||||
progress: { link: 'https://auth.example/v1/desktop/auth/authorize?state=preview' }
|
||||
})
|
||||
|
||||
/** The browser never came back: a calm inline note, and Sign in to Orca again. */
|
||||
export const signInTimedOut = pane(signedOutStatus, { end: 'timed-out' })
|
||||
|
||||
@@ -99,7 +99,7 @@ function mcpPage(workspaces: OrcaCloudMcpWorkspace[] | null | 'failed'): React.J
|
||||
<Page
|
||||
id="cloud-mcp"
|
||||
title="MCP servers"
|
||||
description="MCP servers from Claude Code and Codex on this computer, synced to your cloud workspaces."
|
||||
description="MCP servers from Claude and Codex on this computer, synced to your cloud workspaces."
|
||||
>
|
||||
<OrcaCloudMcpServersView
|
||||
workspaces={workspaces}
|
||||
|
||||
@@ -18,6 +18,7 @@ import { CloudSecretsSection } from '../cloud-secrets/CloudSecretsSection'
|
||||
import { SettingsGroup } from '../section-layout/SettingsGroup'
|
||||
import { CloudPredictiveWakeSetting } from './CloudPredictiveWakeSetting'
|
||||
import { OrcaCloudMcpServersPane } from './OrcaCloudMcpServersPane'
|
||||
import { OrcaCloudSkillsPane } from './cloud-skills/OrcaCloudSkillsPane'
|
||||
|
||||
type OrcaCloudAccount = {
|
||||
orgId: string | null
|
||||
@@ -178,3 +179,7 @@ export function OrcaCloudEnvironmentsPane(): React.JSX.Element {
|
||||
export function OrcaCloudMcpPane(): React.JSX.Element {
|
||||
return <OrcaCloudAccountGate>{() => <OrcaCloudMcpServersPane />}</OrcaCloudAccountGate>
|
||||
}
|
||||
|
||||
export function OrcaCloudSkillsSyncPane(): React.JSX.Element {
|
||||
return <OrcaCloudAccountGate>{() => <OrcaCloudSkillsPane />}</OrcaCloudAccountGate>
|
||||
}
|
||||
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
import { useId } from 'react'
|
||||
import { Check, ChevronDown, CircleDashed, Minus, RefreshCw } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { InlineError } from '@/components/ui/inline-error'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { useNow } from '@/hooks/use-now'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type {
|
||||
AgentConfigSyncRow,
|
||||
AgentConfigSyncStatus
|
||||
} from '../../../../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import { formatRelative } from '../../../cloud-workspaces/cloud-workspace-format'
|
||||
import {
|
||||
cloudSkillsDisplayName,
|
||||
cloudSkillsErrorRetryable,
|
||||
cloudSkillsErrorText,
|
||||
cloudSkillsKindLabel,
|
||||
cloudSkillsRowIncluded,
|
||||
cloudSkillsRowNote,
|
||||
cloudSkillsRowStateLabel,
|
||||
cloudSkillsRowToggleable,
|
||||
cloudSkillsGroupRows,
|
||||
type CloudSkillsEntry,
|
||||
cloudSkillsSummary
|
||||
} from './cloud-skills-sync-copy'
|
||||
|
||||
export type CloudSkillsSyncPanelProps = {
|
||||
status: AgentConfigSyncStatus
|
||||
excluded: ReadonlySet<string>
|
||||
/** Off: nothing syncs on its own, and the panel says Sync now is a one-time copy. */
|
||||
autoSync: boolean
|
||||
/** For "synced 2 minutes ago"; fixtures pin it. */
|
||||
now?: number
|
||||
expanded: boolean
|
||||
onToggleExpanded: () => void
|
||||
onSyncNow: () => void
|
||||
onToggleItem: (key: string, included: boolean) => void
|
||||
}
|
||||
|
||||
function RowIcon({
|
||||
row,
|
||||
included
|
||||
}: {
|
||||
row: AgentConfigSyncRow
|
||||
included: boolean
|
||||
}): React.JSX.Element {
|
||||
if (row.state === 'synced') {
|
||||
return <Check aria-hidden className="size-3.5 shrink-0 text-foreground" />
|
||||
}
|
||||
if (row.state === 'pending' && included) {
|
||||
return <CircleDashed aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
}
|
||||
return <Minus aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
}
|
||||
|
||||
function ItemRow({
|
||||
row,
|
||||
included,
|
||||
disabled,
|
||||
isCopy = false,
|
||||
onToggle
|
||||
}: {
|
||||
row: AgentConfigSyncRow
|
||||
included: boolean
|
||||
disabled: boolean
|
||||
/** A copy for the other agent: indented under its original, whose switch it follows. */
|
||||
isCopy?: boolean
|
||||
onToggle: (included: boolean) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const note = cloudSkillsRowNote(row, t)
|
||||
const name = cloudSkillsDisplayName(row)
|
||||
const kind = cloudSkillsKindLabel(row, t)
|
||||
return (
|
||||
<li className={cn('flex items-center gap-2.5 py-1.5', isCopy && 'pl-6')}>
|
||||
<RowIcon row={row} included={included} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-baseline gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
'truncate font-medium',
|
||||
row.state === 'synced' ? 'text-foreground' : 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{name}
|
||||
</span>
|
||||
<span className="sr-only">{cloudSkillsRowStateLabel(row, included, t)}</span>
|
||||
<span className="shrink-0 text-2xs text-muted-foreground">{kind}</span>
|
||||
</div>
|
||||
{note ? <p className="line-clamp-2 text-2xs text-muted-foreground">{note}</p> : null}
|
||||
</div>
|
||||
{!isCopy && cloudSkillsRowToggleable(row) ? (
|
||||
<Switch
|
||||
checked={included}
|
||||
// aria-disabled, not disabled: the switch just pressed keeps focus while its sync runs.
|
||||
aria-disabled={disabled || undefined}
|
||||
title={t('cloudSkillsSync.appliesEverywhere', 'Applies to every cloud workspace')}
|
||||
onCheckedChange={(next) => {
|
||||
if (!disabled) {
|
||||
onToggle(next)
|
||||
}
|
||||
}}
|
||||
aria-label={t(
|
||||
'cloudSkillsSync.toggleItem',
|
||||
'Sync {{name}} ({{kind}}) to cloud workspaces',
|
||||
{
|
||||
name,
|
||||
kind
|
||||
}
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function Group({
|
||||
title,
|
||||
entries,
|
||||
excluded,
|
||||
disabled,
|
||||
onToggleItem
|
||||
}: {
|
||||
title: string
|
||||
entries: CloudSkillsEntry[]
|
||||
excluded: ReadonlySet<string>
|
||||
disabled: boolean
|
||||
onToggleItem: (key: string, included: boolean) => void
|
||||
}): React.JSX.Element | null {
|
||||
const headingId = useId()
|
||||
if (entries.length === 0) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<section aria-labelledby={headingId}>
|
||||
<h4 id={headingId} className="pt-1 text-2xs font-medium text-muted-foreground">
|
||||
{title} · {entries.reduce((sum, entry) => sum + 1 + entry.copies.length, 0)}
|
||||
</h4>
|
||||
<ul>
|
||||
{entries.flatMap(({ row, copies }) => [
|
||||
<ItemRow
|
||||
key={row.key}
|
||||
row={row}
|
||||
included={cloudSkillsRowIncluded(row, excluded)}
|
||||
disabled={disabled}
|
||||
onToggle={(included) => onToggleItem(row.key, included)}
|
||||
/>,
|
||||
...copies.map((copy) => (
|
||||
<ItemRow
|
||||
key={copy.key}
|
||||
row={copy}
|
||||
included={cloudSkillsRowIncluded(copy, excluded)}
|
||||
disabled={disabled}
|
||||
isCopy
|
||||
onToggle={() => {}}
|
||||
/>
|
||||
))
|
||||
])}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
export function CloudSkillsSyncSkeleton(): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
return (
|
||||
<div
|
||||
className="mt-2 flex min-h-6 items-center gap-1.5 border-t border-border/60 pt-2 text-xs"
|
||||
aria-busy
|
||||
>
|
||||
<span className="font-medium text-foreground">
|
||||
{t('cloudSkillsSync.title', 'Skills & commands')}
|
||||
</span>
|
||||
<span className="sr-only">
|
||||
{t('cloudSkillsSync.loading', 'Loading skills and commands…')}
|
||||
</span>
|
||||
<Skeleton className="h-3 w-28" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** "Skills & commands: N synced" for one Orca Cloud workspace, with a per-item opt-out. */
|
||||
export function CloudSkillsSyncPanel({
|
||||
status,
|
||||
excluded,
|
||||
autoSync,
|
||||
now: pinnedNow,
|
||||
expanded,
|
||||
onToggleExpanded,
|
||||
onSyncNow,
|
||||
onToggleItem
|
||||
}: CloudSkillsSyncPanelProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
// A minute tick keeps "synced 2 minutes ago" honest while Settings stays open.
|
||||
const tick = useNow(60_000, pinnedNow === undefined)
|
||||
const now = pinnedNow ?? tick
|
||||
const listId = useId()
|
||||
const error = cloudSkillsErrorText(status.error, t)
|
||||
const summary = cloudSkillsSummary(status, t)
|
||||
const lastSynced =
|
||||
status.lastSyncedAt === null
|
||||
? null
|
||||
: t('cloudSkillsSync.syncedAgo', 'synced {{time}}', {
|
||||
time: formatRelative(status.lastSyncedAt, now, t)
|
||||
})
|
||||
const groups = cloudSkillsGroupRows(status.rows)
|
||||
const hasRows = status.rows.length > 0
|
||||
const title = (
|
||||
<>
|
||||
<span className="font-medium text-foreground">
|
||||
{t('cloudSkillsSync.title', 'Skills & commands')}
|
||||
</span>
|
||||
<span className="truncate text-muted-foreground">
|
||||
{summary}
|
||||
{lastSynced && !status.running ? ` · ${lastSynced}` : null}
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
return (
|
||||
<div className="mt-2 border-t border-border/60 pt-2 text-xs">
|
||||
<div className="flex min-h-6 items-center gap-2">
|
||||
{hasRows ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="inlineChip"
|
||||
className="-ml-1.5 min-w-0"
|
||||
aria-expanded={expanded}
|
||||
aria-controls={listId}
|
||||
onClick={onToggleExpanded}
|
||||
>
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
{title}
|
||||
<ChevronDown
|
||||
aria-hidden
|
||||
className={cn(
|
||||
'size-3 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none',
|
||||
expanded && 'rotate-180'
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
</Button>
|
||||
) : (
|
||||
<div className="flex min-w-0 items-center gap-1.5">{title}</div>
|
||||
)}
|
||||
<span className="sr-only" role="status">
|
||||
{status.running
|
||||
? t('cloudSkillsSync.syncing', 'Syncing skills and commands…')
|
||||
: error
|
||||
? null
|
||||
: summary}
|
||||
</span>
|
||||
<span className="flex-1" />
|
||||
{hasRows && status.error !== 'host-outdated' && !cloudSkillsErrorRetryable(status.error) ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
onClick={status.running ? undefined : onSyncNow}
|
||||
aria-disabled={status.running || undefined}
|
||||
aria-busy={status.running || undefined}
|
||||
>
|
||||
{status.running ? <LoadingSpinner className="size-3" /> : <RefreshCw />}
|
||||
{status.running
|
||||
? t('cloudSkillsSync.syncingShort', 'Syncing…')
|
||||
: t('cloudSkillsSync.syncNow', 'Sync now')}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{error ? (
|
||||
<InlineError
|
||||
className="mt-1.5"
|
||||
density="compact"
|
||||
tone={cloudSkillsErrorRetryable(status.error) ? 'error' : 'neutral'}
|
||||
title={error}
|
||||
{...(cloudSkillsErrorRetryable(status.error)
|
||||
? {
|
||||
retryLabel: t('cloudSkillsSync.syncAgain', 'Sync again'),
|
||||
onRetry: onSyncNow,
|
||||
retrying: status.running
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
) : null}
|
||||
{!autoSync && hasRows ? (
|
||||
<p className="mt-0.5 text-2xs text-muted-foreground">
|
||||
{t('cloudSkillsSync.manualOnly', 'Not synced automatically. Sync now copies them once.')}
|
||||
</p>
|
||||
) : null}
|
||||
<div id={listId} hidden={!expanded || !hasRows} className="mt-1.5 space-y-2">
|
||||
<Group
|
||||
title={t('cloudSkillsSync.group.synced', 'Synced')}
|
||||
entries={groups.synced}
|
||||
excluded={excluded}
|
||||
disabled={status.running}
|
||||
onToggleItem={onToggleItem}
|
||||
/>
|
||||
<Group
|
||||
title={t('cloudSkillsSync.group.pending', 'Not synced yet')}
|
||||
entries={groups.pending}
|
||||
excluded={excluded}
|
||||
disabled={status.running}
|
||||
onToggleItem={onToggleItem}
|
||||
/>
|
||||
<Group
|
||||
title={t('cloudSkillsSync.group.notSynced', 'Not synced')}
|
||||
entries={groups.notSynced}
|
||||
excluded={excluded}
|
||||
disabled={status.running}
|
||||
onToggleItem={onToggleItem}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
import type {
|
||||
AgentConfigSyncRow,
|
||||
AgentConfigSyncStatus,
|
||||
CloudAgentConfigSyncPreferences
|
||||
} from '../../../../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import { defineFixture } from '../../../../component-fixtures/component-fixture'
|
||||
import { SettingsSection } from '../../section-layout/SettingsSection'
|
||||
import type { OrcaCloudMcpWorkspace } from '../OrcaCloudMcpServersPane'
|
||||
import { CloudSkillsSyncPanel, CloudSkillsSyncSkeleton } from './CloudSkillsSyncPanel'
|
||||
import { CloudSkillsSyncSettingsView, OrcaCloudSkillsWorkspacesView } from './OrcaCloudSkillsPane'
|
||||
|
||||
const noop = (): void => {}
|
||||
|
||||
function row(
|
||||
kind: AgentConfigSyncRow['kind'],
|
||||
name: string,
|
||||
patch: Partial<AgentConfigSyncRow> = {}
|
||||
): AgentConfigSyncRow {
|
||||
const scope = patch.scope ?? 'user'
|
||||
return {
|
||||
key: `${scope}:${kind}:${name}`,
|
||||
scope,
|
||||
kind,
|
||||
name,
|
||||
bytes: 2048,
|
||||
fileCount: 1,
|
||||
withheldFiles: 0,
|
||||
included: true,
|
||||
state: 'synced',
|
||||
outcome: 'added',
|
||||
...patch
|
||||
}
|
||||
}
|
||||
|
||||
const ROWS: AgentConfigSyncRow[] = [
|
||||
row('claude-skill', 'deploy-preview', { fileCount: 3 }),
|
||||
row('claude-skill', 'release-notes', { withheldFiles: 1 }),
|
||||
row('claude-command', 'review'),
|
||||
row('claude-command', 'frontend/component', { outcome: 'unchanged' }),
|
||||
row('agents-skill', 'playwright-cli'),
|
||||
row('codex-prompt', 'fix-ci', { outcome: 'unchanged' }),
|
||||
row('agents-skill', 'deploy-preview', { convertedFrom: 'user:claude-skill:deploy-preview' }),
|
||||
row('claude-skill', 'local-notes', { scope: 'project' }),
|
||||
row('claude-skill', 'scratch', {
|
||||
state: 'skipped',
|
||||
outcome: undefined,
|
||||
skipReason: 'turned-off'
|
||||
}),
|
||||
row('claude-skill', 'design-system', {
|
||||
scope: 'project',
|
||||
state: 'skipped',
|
||||
outcome: undefined,
|
||||
skipReason: 'in-repo'
|
||||
}),
|
||||
row('claude-skill', 'vendor-keys', {
|
||||
state: 'skipped',
|
||||
outcome: undefined,
|
||||
skipReason: 'secret'
|
||||
}),
|
||||
row('claude-skill', 'datasets', {
|
||||
state: 'skipped',
|
||||
outcome: undefined,
|
||||
skipReason: 'too-large'
|
||||
}),
|
||||
row('claude-command', 'ship', { state: 'skipped', outcome: 'kept-host' })
|
||||
]
|
||||
|
||||
const STATUS: AgentConfigSyncStatus = {
|
||||
environmentId: 'env-1',
|
||||
running: false,
|
||||
lastSyncedAt: Date.UTC(2026, 10, 10, 16, 42),
|
||||
error: null,
|
||||
rows: ROWS
|
||||
}
|
||||
const EXCLUDED = new Set(['user:claude-skill:scratch'])
|
||||
|
||||
const ON: CloudAgentConfigSyncPreferences = {
|
||||
autoSync: true,
|
||||
shareAcrossAgents: true,
|
||||
excluded: []
|
||||
}
|
||||
const OFF: CloudAgentConfigSyncPreferences = {
|
||||
autoSync: false,
|
||||
shareAcrossAgents: false,
|
||||
excluded: []
|
||||
}
|
||||
|
||||
const ONE: OrcaCloudMcpWorkspace[] = [
|
||||
{ runtimeId: 'rt-1', name: 'acme/web · fix-login', environmentId: 'env-1' }
|
||||
]
|
||||
|
||||
function page(
|
||||
preferences: CloudAgentConfigSyncPreferences,
|
||||
workspaces: OrcaCloudMcpWorkspace[] | null | 'failed',
|
||||
status: AgentConfigSyncStatus = STATUS,
|
||||
expanded = true
|
||||
): React.JSX.Element {
|
||||
return (
|
||||
<div className="bg-background px-8 py-6">
|
||||
<SettingsSection
|
||||
id="cloud-skills"
|
||||
title="Skills & commands"
|
||||
description="Skills and slash commands from Claude and Codex on this computer, synced to your cloud workspaces."
|
||||
forceVisible
|
||||
bodyClassName="rounded-none border-0 bg-transparent p-0 shadow-none"
|
||||
>
|
||||
<div className="space-y-5">
|
||||
<CloudSkillsSyncSettingsView preferences={preferences} onChange={noop} />
|
||||
<OrcaCloudSkillsWorkspacesView
|
||||
workspaces={workspaces}
|
||||
onRetry={noop}
|
||||
renderSync={(workspace) => (
|
||||
<CloudSkillsSyncPanel
|
||||
status={{ ...status, environmentId: workspace.environmentId }}
|
||||
excluded={EXCLUDED}
|
||||
autoSync={preferences.autoSync}
|
||||
now={Date.UTC(2026, 10, 10, 16, 44)}
|
||||
expanded={expanded}
|
||||
onToggleExpanded={noop}
|
||||
onSyncNow={noop}
|
||||
onToggleItem={noop}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const synced = defineFixture({ width: 784, render: () => page(ON, ONE) })
|
||||
export const collapsed = defineFixture({ width: 784, render: () => page(ON, ONE, STATUS, false) })
|
||||
export const offNotSynced = defineFixture({
|
||||
width: 784,
|
||||
render: () =>
|
||||
page(
|
||||
OFF,
|
||||
ONE,
|
||||
{
|
||||
...STATUS,
|
||||
lastSyncedAt: null,
|
||||
rows: ROWS.filter((entry) => !entry.convertedFrom).map((entry) =>
|
||||
entry.state === 'synced' ? { ...entry, state: 'pending', outcome: undefined } : entry
|
||||
)
|
||||
},
|
||||
true
|
||||
)
|
||||
})
|
||||
export const syncing = defineFixture({
|
||||
width: 784,
|
||||
render: () => page(ON, ONE, { ...STATUS, running: true }, false)
|
||||
})
|
||||
export const hostOutdated = defineFixture({
|
||||
width: 784,
|
||||
render: () =>
|
||||
page(
|
||||
ON,
|
||||
ONE,
|
||||
{
|
||||
...STATUS,
|
||||
lastSyncedAt: null,
|
||||
error: 'host-outdated',
|
||||
rows: ROWS.map((entry) =>
|
||||
entry.state === 'synced' ? { ...entry, state: 'pending', outcome: undefined } : entry
|
||||
)
|
||||
},
|
||||
false
|
||||
)
|
||||
})
|
||||
export const hostUnreachable = defineFixture({
|
||||
width: 784,
|
||||
render: () => page(ON, ONE, { ...STATUS, error: 'host-unreachable' }, false)
|
||||
})
|
||||
export const noneFound = defineFixture({
|
||||
width: 784,
|
||||
render: () => page(ON, ONE, { ...STATUS, rows: [], lastSyncedAt: null }, false)
|
||||
})
|
||||
export const noneRunning = defineFixture({ width: 784, render: () => page(OFF, []) })
|
||||
export const loadingWorkspaces = defineFixture({ width: 784, render: () => page(ON, null) })
|
||||
export const loadFailed = defineFixture({ width: 784, render: () => page(ON, 'failed') })
|
||||
export const panelLoading = defineFixture({
|
||||
width: 640,
|
||||
render: () => (
|
||||
<div className="bg-background p-6">
|
||||
<CloudSkillsSyncSkeleton />
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,263 @@
|
||||
import { useCallback, useEffect, useId, useMemo, useState } from 'react'
|
||||
import { BookOpenText } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { InlineError } from '@/components/ui/inline-error'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
setCloudAgentConfigItemIncluded,
|
||||
setCloudAgentConfigSyncPreferences,
|
||||
syncCloudAgentConfigNow,
|
||||
useCloudAgentConfigSyncPreferences,
|
||||
useCloudAgentConfigSyncStatus
|
||||
} from '@/lib/cloud-agent-config-sync/cloud-agent-config-sync-client'
|
||||
import { useAppStore } from '@/store'
|
||||
import type { CloudAgentConfigSyncPreferences } from '../../../../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
import { CloudApiEmptyState } from '../../cloud-api/cloud-api-parts'
|
||||
import { SettingsGroup } from '../../section-layout/SettingsGroup'
|
||||
import {
|
||||
runningOrcaCloudMcpWorkspaces,
|
||||
type OrcaCloudMcpWorkspace
|
||||
} from '../OrcaCloudMcpServersPane'
|
||||
import { CloudSkillsSyncPanel, CloudSkillsSyncSkeleton } from './CloudSkillsSyncPanel'
|
||||
|
||||
function SwitchRow({
|
||||
title,
|
||||
description,
|
||||
checked,
|
||||
disabled = false,
|
||||
onChange
|
||||
}: {
|
||||
title: string
|
||||
description: string
|
||||
checked: boolean
|
||||
disabled?: boolean
|
||||
onChange: (next: boolean) => void
|
||||
}): React.JSX.Element {
|
||||
const labelId = useId()
|
||||
const hintId = useId()
|
||||
return (
|
||||
<div data-settings-row="" className="flex items-start justify-between gap-4 py-4">
|
||||
<div className={cn('min-w-0 shrink space-y-0.5', disabled && 'opacity-60')}>
|
||||
<Label id={labelId}>{title}</Label>
|
||||
<p id={hintId} className="text-xs text-muted-foreground">
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
aria-labelledby={labelId}
|
||||
aria-describedby={hintId}
|
||||
onCheckedChange={onChange}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function CloudSkillsSyncSettingsView({
|
||||
preferences,
|
||||
onChange
|
||||
}: {
|
||||
preferences: CloudAgentConfigSyncPreferences
|
||||
onChange: (next: Partial<Omit<CloudAgentConfigSyncPreferences, 'excluded'>>) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
return (
|
||||
<SettingsGroup>
|
||||
<SwitchRow
|
||||
title={t('cloudSkillsSync.autoSync', 'Sync when a workspace starts or wakes')}
|
||||
description={t(
|
||||
'cloudSkillsSync.autoSyncHint',
|
||||
'Copies your Claude and Codex skills and slash commands into each cloud workspace. Anything that looks like a key stays on this computer, and nothing made in the sandbox is overwritten.'
|
||||
)}
|
||||
checked={preferences.autoSync}
|
||||
onChange={(autoSync) => onChange({ autoSync })}
|
||||
/>
|
||||
<SwitchRow
|
||||
title={t('cloudSkillsSync.shareAcrossAgents', 'Share between Claude and Codex')}
|
||||
description={t(
|
||||
'cloudSkillsSync.shareAcrossAgentsHint',
|
||||
'In cloud workspaces, Codex also gets your Claude skills and commands, and Claude gets your Codex skills and prompts. An agent keeps its own if it has one with that name.'
|
||||
)}
|
||||
checked={preferences.shareAcrossAgents}
|
||||
// Nothing to share without sync.
|
||||
disabled={!preferences.autoSync}
|
||||
onChange={(shareAcrossAgents) => onChange({ shareAcrossAgents })}
|
||||
/>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
|
||||
function CloudSkillsSyncSection({
|
||||
environmentId,
|
||||
excluded,
|
||||
autoSync,
|
||||
defaultExpanded
|
||||
}: {
|
||||
environmentId: string
|
||||
excluded: ReadonlySet<string>
|
||||
autoSync: boolean
|
||||
defaultExpanded: boolean
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const status = useCloudAgentConfigSyncStatus(environmentId)
|
||||
const [expanded, setExpanded] = useState(defaultExpanded)
|
||||
if (status === undefined) {
|
||||
return <CloudSkillsSyncSkeleton />
|
||||
}
|
||||
if (!status) {
|
||||
return null
|
||||
}
|
||||
const syncNow = (): void => {
|
||||
void syncCloudAgentConfigNow(environmentId).catch(() =>
|
||||
toast.error(t('cloudSkillsSync.startFailed', 'Couldn’t start the sync.'))
|
||||
)
|
||||
}
|
||||
return (
|
||||
<CloudSkillsSyncPanel
|
||||
status={status}
|
||||
excluded={excluded}
|
||||
autoSync={autoSync}
|
||||
expanded={expanded}
|
||||
onToggleExpanded={() => setExpanded((value) => !value)}
|
||||
onSyncNow={syncNow}
|
||||
onToggleItem={(key, included) => {
|
||||
// Main re-syncs every workspace that already synced; a first sync is still the user's call.
|
||||
void setCloudAgentConfigItemIncluded(key, included).catch(() =>
|
||||
toast.error(t('cloudSkillsSync.saveFailed', 'Couldn’t save the change.'))
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export function OrcaCloudSkillsWorkspacesView({
|
||||
workspaces,
|
||||
renderSync,
|
||||
onRetry
|
||||
}: {
|
||||
workspaces: OrcaCloudMcpWorkspace[] | null | 'failed'
|
||||
renderSync: (workspace: OrcaCloudMcpWorkspace, onlyOne: boolean) => React.ReactNode
|
||||
onRetry: () => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
if (workspaces === 'failed') {
|
||||
return (
|
||||
<InlineError
|
||||
title={t('settings.orcaCloud.mcp.loadFailed', 'Couldn’t list your cloud workspaces')}
|
||||
retryLabel={t('cloudEnvironment.retry', 'Try again')}
|
||||
onRetry={onRetry}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (workspaces === null) {
|
||||
return (
|
||||
<div aria-busy>
|
||||
<span className="sr-only">
|
||||
{t('cloudSkillsSync.loading', 'Loading skills and commands…')}
|
||||
</span>
|
||||
<Skeleton className="h-20 w-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (workspaces.length === 0) {
|
||||
return (
|
||||
<SettingsGroup>
|
||||
<CloudApiEmptyState
|
||||
icon={BookOpenText}
|
||||
title={t('settings.orcaCloud.mcp.emptyTitle', 'No cloud workspace is running')}
|
||||
description={t(
|
||||
'cloudSkillsSync.emptyBody',
|
||||
'Skills and commands sync to a cloud workspace while it runs. Start or wake one to see what it gets.'
|
||||
)}
|
||||
/>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{workspaces.map((workspace) => {
|
||||
const name = workspace.name ?? t('settings.orcaCloud.mcp.unnamed', 'Cloud workspace')
|
||||
return (
|
||||
<SettingsGroup key={workspace.runtimeId}>
|
||||
<section
|
||||
className="py-3"
|
||||
aria-label={t('cloudSkillsSync.workspaceLabel', 'Skills and commands in {{name}}', {
|
||||
name
|
||||
})}
|
||||
>
|
||||
<p className="truncate text-sm font-medium">{name}</p>
|
||||
{renderSync(workspace, workspaces.length === 1)}
|
||||
</section>
|
||||
</SettingsGroup>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Settings › Orca Cloud › Skills & commands. */
|
||||
export function OrcaCloudSkillsPane(): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const preferences = useCloudAgentConfigSyncPreferences()
|
||||
const [workspaces, setWorkspaces] = useState<OrcaCloudMcpWorkspace[] | null | 'failed'>(null)
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
const lifecycle = useAppStore((s) => s.ephemeralVmRuntimesByWorkspaceId)
|
||||
useEffect(() => {
|
||||
const listRuntimes = window.api.ephemeralVm?.listRuntimes
|
||||
if (!listRuntimes) {
|
||||
setWorkspaces([])
|
||||
return
|
||||
}
|
||||
let disposed = false
|
||||
void listRuntimes()
|
||||
.then((records) => !disposed && setWorkspaces(runningOrcaCloudMcpWorkspaces(records)))
|
||||
.catch(() => !disposed && setWorkspaces('failed'))
|
||||
return () => {
|
||||
disposed = true
|
||||
}
|
||||
}, [lifecycle, attempt])
|
||||
const retry = useCallback(() => {
|
||||
setWorkspaces(null)
|
||||
setAttempt((value) => value + 1)
|
||||
}, [])
|
||||
const excluded = useMemo(() => new Set(preferences?.excluded ?? []), [preferences])
|
||||
if (preferences === undefined) {
|
||||
return <Skeleton className="h-28 w-full" />
|
||||
}
|
||||
if (preferences === null) {
|
||||
return (
|
||||
<InlineError
|
||||
title={t('cloudSkillsSync.unavailable', 'Skill sync isn’t available in this build.')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<CloudSkillsSyncSettingsView
|
||||
preferences={preferences}
|
||||
onChange={(next) =>
|
||||
void setCloudAgentConfigSyncPreferences(next).catch(() =>
|
||||
toast.error(t('cloudSkillsSync.saveFailed', 'Couldn’t save the change.'))
|
||||
)
|
||||
}
|
||||
/>
|
||||
<OrcaCloudSkillsWorkspacesView
|
||||
workspaces={workspaces}
|
||||
onRetry={retry}
|
||||
renderSync={(workspace, onlyOne) => (
|
||||
<CloudSkillsSyncSection
|
||||
environmentId={workspace.environmentId}
|
||||
excluded={excluded}
|
||||
autoSync={preferences.autoSync}
|
||||
defaultExpanded={onlyOne}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
import {
|
||||
agentOfKind,
|
||||
isSkillKind,
|
||||
type AgentConfigSyncRow,
|
||||
type AgentConfigSyncStatus
|
||||
} from '../../../../../../shared/agent-config-sync/agent-config-sync-contract'
|
||||
|
||||
// Glossary: the agent is "Claude" in UI copy, never "Claude Code".
|
||||
export const AGENT_LABEL = { claude: 'Claude', codex: 'Codex' } as const
|
||||
|
||||
/** What the user types: `/frontend:review` for a namespaced Claude command, `/prompts:x` in Codex. */
|
||||
export function cloudSkillsDisplayName(row: Pick<AgentConfigSyncRow, 'kind' | 'name'>): string {
|
||||
if (row.kind === 'claude-command') {
|
||||
return `/${row.name.split('/').join(':')}`
|
||||
}
|
||||
if (row.kind === 'codex-prompt') {
|
||||
return `/prompts:${row.name}`
|
||||
}
|
||||
return row.name
|
||||
}
|
||||
|
||||
export function cloudSkillsKindLabel(row: AgentConfigSyncRow, t: Translate = translate): string {
|
||||
const agent = AGENT_LABEL[agentOfKind(row.kind)]
|
||||
const kind = isSkillKind(row.kind)
|
||||
? t('cloudSkillsSync.kind.skill', '{{agent}} skill', { agent })
|
||||
: row.kind === 'codex-prompt'
|
||||
? t('cloudSkillsSync.kind.prompt', 'Codex prompt')
|
||||
: t('cloudSkillsSync.kind.command', '{{agent}} command', { agent })
|
||||
return row.scope === 'project'
|
||||
? t('cloudSkillsSync.kind.project', '{{kind}}, this project', { kind })
|
||||
: kind
|
||||
}
|
||||
|
||||
/** Rows the user's switches apply to: a copy for the other agent follows its original. */
|
||||
export function cloudSkillsRowIncluded(
|
||||
row: AgentConfigSyncRow,
|
||||
excluded: ReadonlySet<string>
|
||||
): boolean {
|
||||
return !excluded.has(row.convertedFrom ?? row.key)
|
||||
}
|
||||
|
||||
export function cloudSkillsCounts(status: AgentConfigSyncStatus): {
|
||||
synced: number
|
||||
skipped: number
|
||||
} {
|
||||
const synced = status.rows.filter((row) => row.state === 'synced').length
|
||||
return { synced, skipped: status.rows.length - synced }
|
||||
}
|
||||
|
||||
export function cloudSkillsSummary(
|
||||
status: AgentConfigSyncStatus,
|
||||
t: Translate = translate
|
||||
): string {
|
||||
if (status.rows.length === 0) {
|
||||
return t('cloudSkillsSync.summary.none', 'None found in Claude or Codex on this computer')
|
||||
}
|
||||
if (status.lastSyncedAt === null) {
|
||||
return t('cloudSkillsSync.summary.notSynced', '{{count}} found, not synced yet', {
|
||||
count: status.rows.length,
|
||||
defaultValue_one: '{{count}} found, not synced yet'
|
||||
})
|
||||
}
|
||||
const counts = cloudSkillsCounts(status)
|
||||
const synced = t('cloudSkillsSync.summary.synced', '{{count}} synced', {
|
||||
count: counts.synced,
|
||||
defaultValue_one: '{{count}} synced'
|
||||
})
|
||||
if (counts.skipped === 0) {
|
||||
return synced
|
||||
}
|
||||
const skipped = t('cloudSkillsSync.summary.skipped', '{{count}} not synced', {
|
||||
count: counts.skipped,
|
||||
defaultValue_one: '{{count}} not synced'
|
||||
})
|
||||
return t('cloudSkillsSync.summary.pair', '{{synced}}, {{skipped}}', { synced, skipped })
|
||||
}
|
||||
|
||||
export function cloudSkillsErrorRetryable(error: AgentConfigSyncStatus['error']): boolean {
|
||||
return error === 'host-unreachable' || error === 'failed'
|
||||
}
|
||||
|
||||
export function cloudSkillsErrorText(
|
||||
error: AgentConfigSyncStatus['error'],
|
||||
t: Translate = translate
|
||||
): string | null {
|
||||
const copy: Record<NonNullable<AgentConfigSyncStatus['error']>, string> = {
|
||||
'host-outdated': t(
|
||||
'cloudSkillsSync.error.hostOutdated',
|
||||
'This workspace was created before skills sync. Create a new workspace to use it.'
|
||||
),
|
||||
'host-unreachable': t(
|
||||
'cloudSkillsSync.error.hostUnreachable',
|
||||
'Couldn’t reach the sandbox. Skills already there still work.'
|
||||
),
|
||||
failed: t(
|
||||
'cloudSkillsSync.error.failed',
|
||||
'The last sync didn’t finish. Skills already in the sandbox still work.'
|
||||
)
|
||||
}
|
||||
return error ? copy[error] : null
|
||||
}
|
||||
|
||||
/** Why an item is not in the sandbox, or a caveat for one that is. */
|
||||
export function cloudSkillsRowNote(
|
||||
row: AgentConfigSyncRow,
|
||||
t: Translate = translate
|
||||
): string | null {
|
||||
if (row.state === 'synced' && row.withheldFiles > 0) {
|
||||
return t(
|
||||
'cloudSkillsSync.row.withheld',
|
||||
'Synced without {{count}} files that look like keys or credentials',
|
||||
{
|
||||
count: row.withheldFiles,
|
||||
defaultValue_one: 'Synced without 1 file that looks like a key or credential'
|
||||
}
|
||||
)
|
||||
}
|
||||
if (row.state !== 'skipped') {
|
||||
return row.convertedFrom
|
||||
? t('cloudSkillsSync.row.converted', 'Copied from {{agent}} so both agents have it', {
|
||||
agent: AGENT_LABEL[agentOfKind(row.kind) === 'claude' ? 'codex' : 'claude']
|
||||
})
|
||||
: null
|
||||
}
|
||||
const key = row.outcome ?? row.skipReason
|
||||
switch (key) {
|
||||
case 'turned-off':
|
||||
return t('cloudSkillsSync.row.turnedOff', 'Turned off')
|
||||
case 'in-repo':
|
||||
return t('cloudSkillsSync.row.inRepo', 'Committed to the repo, so the sandbox already has it')
|
||||
case 'too-large':
|
||||
return t('cloudSkillsSync.row.tooLarge', 'Too large to sync (256 KB a file, 512 KB a skill)')
|
||||
case 'over-limit':
|
||||
return t('cloudSkillsSync.row.overLimit', 'Over the 8 MB a workspace can receive')
|
||||
case 'secret':
|
||||
return t(
|
||||
'cloudSkillsSync.row.secret',
|
||||
'Looks like it contains a key or token, so it stays on this computer'
|
||||
)
|
||||
case 'invalid':
|
||||
return t('cloudSkillsSync.row.invalid', 'Its name or files can’t be copied')
|
||||
case 'kept-host':
|
||||
return t(
|
||||
'cloudSkillsSync.row.keptHost',
|
||||
'The sandbox has its own {{name}}, so it’s left alone',
|
||||
{ name: cloudSkillsDisplayName(row) }
|
||||
)
|
||||
case 'no-project':
|
||||
return t('cloudSkillsSync.row.noProject', 'The sandbox has no project checkout for it')
|
||||
case 'failed':
|
||||
return t('cloudSkillsSync.row.failed', 'Couldn’t write it in the sandbox')
|
||||
case 'added':
|
||||
case 'updated':
|
||||
case 'unchanged':
|
||||
case 'needed':
|
||||
case undefined:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const FIXED_SKIPS: ReadonlySet<string> = new Set([
|
||||
'in-repo',
|
||||
'too-large',
|
||||
'secret',
|
||||
'invalid',
|
||||
'kept-host',
|
||||
'no-project'
|
||||
])
|
||||
|
||||
/** A copy follows its original's switch; fixed skips can't be changed from here. */
|
||||
export function cloudSkillsRowToggleable(row: AgentConfigSyncRow): boolean {
|
||||
if (row.convertedFrom) {
|
||||
return false
|
||||
}
|
||||
const key = row.outcome ?? row.skipReason
|
||||
return !key || !FIXED_SKIPS.has(key)
|
||||
}
|
||||
|
||||
export type CloudSkillsEntry = { row: AgentConfigSyncRow; copies: AgentConfigSyncRow[] }
|
||||
export type CloudSkillsGroups = {
|
||||
synced: CloudSkillsEntry[]
|
||||
pending: CloudSkillsEntry[]
|
||||
notSynced: CloudSkillsEntry[]
|
||||
}
|
||||
|
||||
const byName = (a: AgentConfigSyncRow, b: AgentConfigSyncRow): number =>
|
||||
cloudSkillsDisplayName(a).localeCompare(cloudSkillsDisplayName(b)) || a.key.localeCompare(b.key)
|
||||
|
||||
/** Synced, ready (never synced yet) and not synced; each copy for the other agent sits under its original. */
|
||||
export function cloudSkillsGroupRows(rows: readonly AgentConfigSyncRow[]): CloudSkillsGroups {
|
||||
const originals = new Set(rows.filter((row) => !row.convertedFrom).map((row) => row.key))
|
||||
const copies = new Map<string, AgentConfigSyncRow[]>()
|
||||
for (const row of rows) {
|
||||
if (row.convertedFrom && originals.has(row.convertedFrom)) {
|
||||
copies.set(row.convertedFrom, [...(copies.get(row.convertedFrom) ?? []), row])
|
||||
}
|
||||
}
|
||||
const groups: CloudSkillsGroups = { synced: [], pending: [], notSynced: [] }
|
||||
for (const row of [...rows].sort(byName)) {
|
||||
if (row.convertedFrom && originals.has(row.convertedFrom)) {
|
||||
continue
|
||||
}
|
||||
const entry = { row, copies: (copies.get(row.key) ?? []).sort(byName) }
|
||||
const group =
|
||||
row.state === 'synced'
|
||||
? groups.synced
|
||||
: row.state === 'pending'
|
||||
? groups.pending
|
||||
: groups.notSynced
|
||||
group.push(entry)
|
||||
}
|
||||
// Ones a switch can turn back on come before skips nothing here can fix.
|
||||
groups.notSynced.sort(
|
||||
(a, b) =>
|
||||
Number(!cloudSkillsRowToggleable(a.row)) - Number(!cloudSkillsRowToggleable(b.row)) ||
|
||||
byName(a.row, b.row)
|
||||
)
|
||||
return groups
|
||||
}
|
||||
|
||||
export function cloudSkillsRowStateLabel(
|
||||
row: AgentConfigSyncRow,
|
||||
included: boolean,
|
||||
t: Translate = translate
|
||||
): string {
|
||||
if (row.state === 'synced') {
|
||||
return t('cloudSkillsSync.state.synced', 'Synced')
|
||||
}
|
||||
return row.state === 'pending' && included
|
||||
? t('cloudSkillsSync.state.pending', 'Not synced yet')
|
||||
: t('cloudSkillsSync.state.skipped', 'Not synced')
|
||||
}
|
||||
@@ -81,3 +81,20 @@ export const getOrcaCloudMcpSearchEntries = createLocalizedCatalog(() => [
|
||||
]
|
||||
}
|
||||
])
|
||||
|
||||
export const getOrcaCloudSkillsSearchEntries = createLocalizedCatalog(() => [
|
||||
{
|
||||
title: translate('cloudSkillsSync.title', 'Skills & commands'),
|
||||
description: translate(
|
||||
'settings.orcaCloud.skills.searchDescription',
|
||||
'Sync Claude and Codex skills and slash commands from this computer to your cloud workspaces.'
|
||||
),
|
||||
keywords: [
|
||||
...translateSearchKeyword('settings.orcaCloud.skills.keywordSkills', 'skills'),
|
||||
...translateSearchKeyword('settings.orcaCloud.skills.keywordCommands', 'slash commands'),
|
||||
...translateSearchKeyword('settings.orcaCloud.skills.keywordPrompts', 'prompts'),
|
||||
...translateSearchKeyword('settings.orcaCloud.mcp.keywordSync', 'sync'),
|
||||
...translateSearchKeyword('settings.orcaCloud.mcp.keywordCloud', 'cloud')
|
||||
]
|
||||
}
|
||||
])
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
OrcaCloudEnvironmentsPane,
|
||||
OrcaCloudMcpPane,
|
||||
OrcaCloudSecretsPane,
|
||||
OrcaCloudSkillsSyncPane,
|
||||
OrcaCloudTeamPane
|
||||
} from '../orca-cloud/OrcaCloudSettingsPanes'
|
||||
import { SettingsSection } from '../section-layout/SettingsSection'
|
||||
@@ -26,6 +27,7 @@ export function renderOrcaCloudSettingsSections(
|
||||
{ id: 'cloud-billing', pane: <OrcaCloudBillingPane /> },
|
||||
{ id: 'cloud-team', pane: <OrcaCloudTeamPane /> },
|
||||
{ id: 'cloud-secrets', pane: <OrcaCloudSecretsPane /> },
|
||||
{ id: 'cloud-skills', pane: <OrcaCloudSkillsSyncPane /> },
|
||||
{ id: 'cloud-environments', pane: <OrcaCloudEnvironmentsPane /> },
|
||||
{ id: 'cloud-mcp', pane: <OrcaCloudMcpPane /> }
|
||||
]
|
||||
|
||||
+2
-1
@@ -22,7 +22,8 @@ import {
|
||||
mcpSyncTimeLabel
|
||||
} from './cloud-mcp-sync-copy'
|
||||
|
||||
const AGENT_LABEL = { claude: 'Claude Code', codex: 'Codex' } as const
|
||||
// Glossary: the catalog name is "Claude", never "Claude Code".
|
||||
const AGENT_LABEL = { claude: 'Claude', codex: 'Codex' } as const
|
||||
|
||||
export type CloudMcpSyncPanelProps = {
|
||||
status: McpSyncStatus
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ export function mcpSyncSummary(status: McpSyncStatus, t: Translate = translate):
|
||||
if (status.rows.length === 0) {
|
||||
return t(
|
||||
'cloudMcpSync.summary.none',
|
||||
'None found in Claude Code or Codex on this computer. Servers you add there show up here.'
|
||||
'None found in Claude or Codex on this computer. Servers you add there show up here.'
|
||||
)
|
||||
}
|
||||
if (status.error === 'host-outdated' && status.lastSyncedAt === null) {
|
||||
|
||||
@@ -71,7 +71,7 @@ export function SidebarAccountMenu(): React.JSX.Element {
|
||||
const mountedRef = useMountedRef()
|
||||
|
||||
const identity = getAccountMenuIdentity(authStatus)
|
||||
// The team is named once, on the switcher below; the header carries the plan's hours instead.
|
||||
// The plan's hours are the team's, so they sit on the team row below, not under your name (JA-32).
|
||||
const billingResult = useBillingState().result
|
||||
const usage = accountMenuUsageLines(billingResult, t, locale)
|
||||
const visibleItems = selectVisibleAccountMenuItems(registeredItems, authStatus)
|
||||
@@ -187,14 +187,6 @@ export function SidebarAccountMenu(): React.JSX.Element {
|
||||
{identity.email}
|
||||
</span>
|
||||
) : null}
|
||||
{usage ? (
|
||||
<span className="truncate text-xs text-muted-foreground tabular-nums">
|
||||
{usage.hoursLeft}
|
||||
</span>
|
||||
) : null}
|
||||
{usage?.warning ? (
|
||||
<span className="text-xs text-foreground text-pretty">{usage.warning}</span>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
@@ -216,7 +208,7 @@ export function SidebarAccountMenu(): React.JSX.Element {
|
||||
{identity.signedIn ? <AccountMenuTrialRow result={billingResult} /> : null}
|
||||
</>
|
||||
) : null}
|
||||
<SidebarTeamSubmenu authStatus={authStatus} />
|
||||
<SidebarTeamSubmenu authStatus={authStatus} usage={usage} />
|
||||
{extensionItems.length > 0 ? (
|
||||
<>
|
||||
{extensionItems.map((item) => {
|
||||
|
||||
@@ -23,9 +23,12 @@ const PERSONAL_VALUE = '__personal__'
|
||||
* which re-scopes billing, seats and the Team page.
|
||||
*/
|
||||
export function SidebarTeamSubmenu({
|
||||
authStatus
|
||||
authStatus,
|
||||
usage = null
|
||||
}: {
|
||||
authStatus: OrcaProfileAuthStatus | null
|
||||
/** The active plan's hours (and its usage alert), shown on the team row because they're the team's. */
|
||||
usage?: { hoursLeft: string; warning: string | null } | null
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const pendingOrgId = usePendingTeamSwitch()
|
||||
@@ -68,8 +71,18 @@ export function SidebarTeamSubmenu({
|
||||
}
|
||||
>
|
||||
{activeName ? <ChevronsUpDown className="size-3.5" /> : <User className="size-3.5" />}
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{activeName ?? t('auto.components.sidebar.teamSwitcher.personal', 'Personal account')}
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate">
|
||||
{activeName ?? t('auto.components.sidebar.teamSwitcher.personal', 'Personal account')}
|
||||
</span>
|
||||
{usage ? (
|
||||
<span className="truncate text-xs text-muted-foreground tabular-nums">
|
||||
{usage.hoursLeft}
|
||||
</span>
|
||||
) : null}
|
||||
{usage?.warning ? (
|
||||
<span className="text-xs text-foreground text-pretty">{usage.warning}</span>
|
||||
) : null}
|
||||
</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent className="w-60">
|
||||
|
||||
@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => {
|
||||
activeWorktreeId: null,
|
||||
setActiveWorktree: vi.fn(),
|
||||
shutdownWorktreeBrowsers: vi.fn(),
|
||||
browserTabsByWorktree: {},
|
||||
browserPagesByWorkspace: {},
|
||||
shutdownWorktreeTerminals: vi.fn<AppState['shutdownWorktreeTerminals']>(),
|
||||
tabsByWorktree,
|
||||
ptyIdsByTabId,
|
||||
@@ -18,9 +20,14 @@ const mocks = vi.hoisted(() => {
|
||||
detectedWorktreesByRepo: {}
|
||||
},
|
||||
persist: vi.fn(async () => {}),
|
||||
payload: vi.fn(() => ({}))
|
||||
payload: vi.fn(() => ({})),
|
||||
evictGuests: vi.fn()
|
||||
}
|
||||
})
|
||||
vi.mock('@/store/slices/browser/cleanup/browser-webview-cleanup', () => ({
|
||||
destroyWorktreeBrowserGuests: (_tabs: unknown, _pages: unknown, worktreeId: string) =>
|
||||
mocks.evictGuests(worktreeId)
|
||||
}))
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: { getState: () => mocks.state, subscribe: () => () => {} }
|
||||
}))
|
||||
@@ -203,7 +210,9 @@ describe('project move renderer completion', () => {
|
||||
records: []
|
||||
})
|
||||
await f.persist()
|
||||
expect(mocks.state.shutdownWorktreeBrowsers).toHaveBeenCalledWith('wt')
|
||||
// Sleep keeps the tabs (NEW-01); only their pages are dropped.
|
||||
expect(mocks.state.shutdownWorktreeBrowsers).not.toHaveBeenCalled()
|
||||
expect(mocks.evictGuests).toHaveBeenCalledWith('wt')
|
||||
expect(f.responses.at(-1)).toMatchObject({
|
||||
phase: 'error',
|
||||
error: 'project_move_pause_sleep_superseded'
|
||||
|
||||
+6
-1
@@ -1,3 +1,4 @@
|
||||
import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import { useRepoById } from '@/store/repos/use-repository-catalog'
|
||||
@@ -107,7 +108,11 @@ export function useWorktreeContextMenuModel({
|
||||
selectMenuScopedMap(menuOpen, s.ptyIdsByTabId, EMPTY_PTY_IDS_BY_TAB_ID)
|
||||
)
|
||||
const browserTabsByWorktree = useAppStore((s) =>
|
||||
selectMenuScopedMap(menuOpen, s.browserTabsByWorktree, EMPTY_BROWSER_TABS_BY_WORKTREE)
|
||||
selectMenuScopedMap(
|
||||
menuOpen,
|
||||
selectAwakeBrowserTabsByWorktree(s),
|
||||
EMPTY_BROWSER_TABS_BY_WORKTREE
|
||||
)
|
||||
)
|
||||
const unifiedTabsByWorktree = useAppStore((s) =>
|
||||
selectMenuScopedMap(menuOpen, s.unifiedTabsByWorktree, EMPTY_UNIFIED_TABS_BY_WORKTREE)
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { BrowserWorkspace } from '../../../../../../shared/browser-workspace-types'
|
||||
|
||||
type State = {
|
||||
activeWorktreeId: string | null
|
||||
browserTabsByWorktree: Record<string, BrowserWorkspace[]>
|
||||
asleepBrowserWorktreeIds: Record<string, number>
|
||||
browserPagesByWorkspace: Record<string, never[]>
|
||||
activeBrowserTabIdByWorktree: Record<string, string>
|
||||
}
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const listeners = new Set<(state: State) => void>()
|
||||
const initial: State = {
|
||||
activeWorktreeId: null,
|
||||
browserTabsByWorktree: {},
|
||||
asleepBrowserWorktreeIds: {},
|
||||
browserPagesByWorkspace: {},
|
||||
activeBrowserTabIdByWorktree: {}
|
||||
}
|
||||
const store = {
|
||||
state: initial,
|
||||
getState: (): State => store.state,
|
||||
setState: (change: (state: State) => Partial<State>): void => {
|
||||
store.state = { ...store.state, ...change(store.state) }
|
||||
for (const listener of listeners) {
|
||||
listener(store.state)
|
||||
}
|
||||
},
|
||||
subscribe: (listener: (state: State) => void): (() => void) => {
|
||||
listeners.add(listener)
|
||||
return () => listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
const evicted: string[] = []
|
||||
return { store, evicted }
|
||||
})
|
||||
vi.mock('@/store', () => ({ useAppStore: mocks.store }))
|
||||
vi.mock('@/store/slices/browser/cleanup/browser-webview-cleanup', () => ({
|
||||
destroyWorktreeBrowserGuests: (_tabs: unknown, _pages: unknown, worktreeId: string) =>
|
||||
mocks.evicted.push(worktreeId)
|
||||
}))
|
||||
|
||||
const { sleepWorktreeBrowserTabs, installBrowserTabWakeOnOpen, selectAwakeBrowserTabsByWorktree } =
|
||||
await import('./browser-tab-sleep')
|
||||
const { isInactiveWorkspace } = await import('@/lib/worktree-activity-state')
|
||||
|
||||
const tab = (id: string): BrowserWorkspace => ({
|
||||
id,
|
||||
worktreeId: 'wt',
|
||||
url: `http://localhost:3000/${id}`,
|
||||
title: id,
|
||||
loading: false,
|
||||
faviconUrl: null,
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
loadError: null,
|
||||
createdAt: 1
|
||||
})
|
||||
|
||||
const state = (): State => mocks.store.getState()
|
||||
const inactive = (): boolean =>
|
||||
isInactiveWorkspace('wt', {}, {}, selectAwakeBrowserTabsByWorktree(state()), new Set())
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.evicted.length = 0
|
||||
mocks.store.state = {
|
||||
activeWorktreeId: null,
|
||||
browserTabsByWorktree: { wt: [tab('a'), tab('b'), tab('c')] },
|
||||
asleepBrowserWorktreeIds: {},
|
||||
browserPagesByWorkspace: {},
|
||||
activeBrowserTabIdByWorktree: { wt: 'b' }
|
||||
}
|
||||
})
|
||||
|
||||
describe('sleep keeps browser tabs in place (NEW-01)', () => {
|
||||
it('keeps every tab, in order, with the same active tab; drops only their pages', () => {
|
||||
const before = state().browserTabsByWorktree
|
||||
sleepWorktreeBrowserTabs('wt', 42)
|
||||
expect(mocks.evicted).toEqual(['wt'])
|
||||
// The layout itself is untouched: same object, same order, same active tab.
|
||||
expect(state().browserTabsByWorktree).toBe(before)
|
||||
expect(state().browserTabsByWorktree.wt.map((t) => t.id)).toEqual(['a', 'b', 'c'])
|
||||
expect(state().activeBrowserTabIdByWorktree.wt).toBe('b')
|
||||
})
|
||||
|
||||
it('asleep tabs are not activity, so the workspace still reads as asleep', () => {
|
||||
expect(inactive()).toBe(false)
|
||||
sleepWorktreeBrowserTabs('wt', 42)
|
||||
expect(inactive()).toBe(true)
|
||||
})
|
||||
|
||||
it('opening the workspace again wakes its tabs', () => {
|
||||
const stop = installBrowserTabWakeOnOpen()
|
||||
sleepWorktreeBrowserTabs('wt', 42)
|
||||
mocks.store.setState(() => ({ activeWorktreeId: 'wt' }))
|
||||
expect(state().asleepBrowserWorktreeIds).toEqual({})
|
||||
expect(inactive()).toBe(false)
|
||||
expect(state().browserTabsByWorktree.wt.map((t) => t.id)).toEqual(['a', 'b', 'c'])
|
||||
stop()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,103 @@
|
||||
// Sleep never changes a workspace's tab layout (NEW-01). Its browser tabs stay where they are, in
|
||||
// the same order with the same active tab; only their pages are dropped to free memory, and the
|
||||
// workspace's tabs are marked asleep so they no longer count as activity (an asleep workspace still
|
||||
// reads as asleep and hides with "Hide sleeping"). Opening the workspace again wakes them: each
|
||||
// page reloads in place when it is shown. A remote desktop tab's own chrome reconnects it after a
|
||||
// wake. The mark lives outside the layout (asleepBrowserWorktreeIds), so sleep writes no layout.
|
||||
import { useAppStore } from '@/store'
|
||||
import { destroyWorktreeBrowserGuests } from '@/store/slices/browser/cleanup/browser-webview-cleanup'
|
||||
import type { BrowserWorkspace } from '../../../../../../shared/browser-workspace-types'
|
||||
|
||||
type BrowserTabsByWorktree = Record<string, BrowserWorkspace[]>
|
||||
|
||||
let cache: {
|
||||
tabs: BrowserTabsByWorktree
|
||||
asleep: Record<string, number>
|
||||
awake: BrowserTabsByWorktree
|
||||
} | null = null
|
||||
|
||||
/**
|
||||
* The browser tabs that count as activity: every workspace's, minus those Sleep put to rest.
|
||||
* Same object back while neither input changes, so store selectors stay stable.
|
||||
*/
|
||||
export function selectAwakeBrowserTabsByWorktree(state: {
|
||||
browserTabsByWorktree: BrowserTabsByWorktree
|
||||
asleepBrowserWorktreeIds?: Record<string, number>
|
||||
}): BrowserTabsByWorktree {
|
||||
const tabs = state.browserTabsByWorktree
|
||||
const asleep = state.asleepBrowserWorktreeIds
|
||||
if (!asleep || Object.keys(asleep).length === 0) {
|
||||
return tabs
|
||||
}
|
||||
if (cache && cache.tabs === tabs && cache.asleep === asleep) {
|
||||
return cache.awake
|
||||
}
|
||||
const awake: BrowserTabsByWorktree = {}
|
||||
for (const [worktreeId, worktreeTabs] of Object.entries(tabs)) {
|
||||
if (!asleep[worktreeId]) {
|
||||
awake[worktreeId] = worktreeTabs
|
||||
}
|
||||
}
|
||||
cache = { tabs, asleep, awake }
|
||||
return awake
|
||||
}
|
||||
|
||||
// Pages a host ran (an Orca Cloud VM's browser) are gone after the VM sleeps. When such a page is
|
||||
// reported missing after the wake, its tab opens a new page at the same URL instead of closing.
|
||||
const reopenAfterSleep = new Set<string>()
|
||||
|
||||
/** True once per slept page: the pane recreates the host page instead of closing the tab. */
|
||||
export function consumeReopenAfterSleep(browserPageId: string): boolean {
|
||||
return reopenAfterSleep.delete(browserPageId)
|
||||
}
|
||||
|
||||
/** Sleep: drop the pages, keep the tabs, mark the workspace's tabs asleep. */
|
||||
export function sleepWorktreeBrowserTabs(worktreeId: string, now: number = Date.now()): void {
|
||||
const state = useAppStore.getState()
|
||||
for (const tab of state.browserTabsByWorktree[worktreeId] ?? []) {
|
||||
reopenAfterSleep.add(tab.id)
|
||||
for (const page of state.browserPagesByWorkspace[tab.id] ?? []) {
|
||||
reopenAfterSleep.add(page.id)
|
||||
}
|
||||
}
|
||||
destroyWorktreeBrowserGuests(
|
||||
state.browserTabsByWorktree,
|
||||
state.browserPagesByWorkspace,
|
||||
worktreeId
|
||||
)
|
||||
if ((state.browserTabsByWorktree[worktreeId] ?? []).length === 0) {
|
||||
return
|
||||
}
|
||||
useAppStore.setState((s) => ({
|
||||
asleepBrowserWorktreeIds: { ...s.asleepBrowserWorktreeIds, [worktreeId]: now }
|
||||
}))
|
||||
}
|
||||
|
||||
/** The workspace is open again: its tabs count as activity once more (pages reload when shown). */
|
||||
export function wakeWorktreeBrowserTabs(worktreeId: string): void {
|
||||
if (!useAppStore.getState().asleepBrowserWorktreeIds?.[worktreeId]) {
|
||||
return
|
||||
}
|
||||
useAppStore.setState((s) => {
|
||||
const next = { ...s.asleepBrowserWorktreeIds }
|
||||
delete next[worktreeId]
|
||||
return { asleepBrowserWorktreeIds: next }
|
||||
})
|
||||
}
|
||||
|
||||
/** Wakes a workspace's asleep tabs whenever it becomes the active one. */
|
||||
export function installBrowserTabWakeOnOpen(): () => void {
|
||||
let previous = useAppStore.getState().activeWorktreeId
|
||||
if (previous) {
|
||||
wakeWorktreeBrowserTabs(previous)
|
||||
}
|
||||
return useAppStore.subscribe((state) => {
|
||||
if (state.activeWorktreeId === previous) {
|
||||
return
|
||||
}
|
||||
previous = state.activeWorktreeId
|
||||
if (previous) {
|
||||
wakeWorktreeBrowserTabs(previous)
|
||||
}
|
||||
})
|
||||
}
|
||||
+3
-1
@@ -18,6 +18,8 @@ type SleepStateInput = {
|
||||
tabsByWorktree?: Record<string, readonly TabLike[]> | null
|
||||
ptyIdsByTabId?: Record<string, string[]> | null
|
||||
browserTabsByWorktree?: Record<string, readonly TabLike[]> | null
|
||||
/** Workspaces whose browser tabs Sleep put to rest: those tabs are not activity. */
|
||||
asleepBrowserWorktreeIds?: Record<string, number>
|
||||
unifiedTabsByWorktree?: Record<string, Tab[]> | null
|
||||
structuredChatSleptAtByPaneKey?: StructuredChatSleptAtByPaneKey
|
||||
}
|
||||
@@ -70,7 +72,7 @@ export function selectIsSleepingWorktree(state: SleepStateInput, worktreeId: str
|
||||
worktreeId,
|
||||
state.tabsByWorktree,
|
||||
state.ptyIdsByTabId,
|
||||
state.browserTabsByWorktree,
|
||||
state.asleepBrowserWorktreeIds?.[worktreeId] ? null : state.browserTabsByWorktree,
|
||||
selectWorktreeIdsWithLiveAgent(state),
|
||||
getWorktreeIdsWithStructuredChat(
|
||||
state.unifiedTabsByWorktree,
|
||||
|
||||
+6
-6
@@ -1,5 +1,5 @@
|
||||
import { useAppStore } from '@/store'
|
||||
import { noteRemoteDesktopBeforeSleep } from '@/lib/cloud-remote-desktop/desktop-sleep-reopen'
|
||||
import { sleepWorktreeBrowserTabs, wakeWorktreeBrowserTabs } from './browser-tab-sleep'
|
||||
import {
|
||||
captureWorkspaceSelection,
|
||||
restoreWorkspaceSelection,
|
||||
@@ -56,10 +56,6 @@ export function followWorkspaceSleep(
|
||||
const state = useAppStore.getState()
|
||||
const wasActive = state.activeWorktreeId === worktreeId
|
||||
const selectionBeforeSleep = wasActive ? captureWorkspaceSelection(state) : null
|
||||
if (!options.keepBrowserTabs) {
|
||||
// Before the selection clears: whether the desktop tab was in front decides how it comes back.
|
||||
noteRemoteDesktopBeforeSleep(worktreeId)
|
||||
}
|
||||
// Why first: clearing the active workspace unmounts its panes, whose exits must not stamp activity.
|
||||
markWorktreeSleepIntent(worktreeId)
|
||||
if (wasActive) {
|
||||
@@ -68,7 +64,9 @@ export function followWorkspaceSleep(
|
||||
restoreSidebarPosition()
|
||||
}
|
||||
if (!options.keepBrowserTabs) {
|
||||
state.shutdownWorktreeBrowsers(worktreeId)
|
||||
// Sleep never changes the tab layout (NEW-01): the tabs, their order and the active one stay;
|
||||
// only their pages are dropped, and each reloads in place when shown after the wake.
|
||||
sleepWorktreeBrowserTabs(worktreeId)
|
||||
}
|
||||
let settle!: (stop: HostTerminalStop) => void
|
||||
const hostStop = new Promise<HostTerminalStop>((resolve) => (settle = resolve))
|
||||
@@ -105,6 +103,8 @@ export function followWorkspaceSleep(
|
||||
// A failed sleep leaves the workspace awake and retryable; one the user reopened is theirs.
|
||||
if (!notice.slept || state.activeWorktreeId === worktreeId) {
|
||||
clearWorktreeSleepIntent(worktreeId)
|
||||
// Still awake: its tabs count as activity again.
|
||||
wakeWorktreeBrowserTabs(worktreeId)
|
||||
}
|
||||
if (!notice.slept && entry?.selectionBeforeSleep && state.activeWorktreeId === null) {
|
||||
restoreWorkspaceSelection(state, entry.selectionBeforeSleep)
|
||||
|
||||
+2
-1
@@ -1,3 +1,4 @@
|
||||
import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import { getAgentStatusEpochNow } from '@/lib/agent-status/evidence/agent-status-epoch-clock'
|
||||
@@ -52,7 +53,7 @@ export function useVisibleWorkspaceKanbanWorktreeIds({
|
||||
const tabsByWorktree = useAppStore((s) => (!showSleepingWorkspaces ? s.tabsByWorktree : null))
|
||||
const ptyIdsByTabId = useAppStore((s) => (!showSleepingWorkspaces ? s.ptyIdsByTabId : null))
|
||||
const browserTabsByWorktree = useAppStore((s) =>
|
||||
!showSleepingWorkspaces ? s.browserTabsByWorktree : null
|
||||
!showSleepingWorkspaces ? selectAwakeBrowserTabsByWorktree(s) : null
|
||||
)
|
||||
const worktreeIdsWithStructuredChat = useAppStore((s) =>
|
||||
getStructuredChatWorktreeIds(
|
||||
|
||||
+6
-1
@@ -62,7 +62,12 @@ export function selectWorktreeActivityPtyIds(
|
||||
|
||||
export function useWorktreeActivityStatus(worktreeId: string): WorktreeStatus {
|
||||
const tabs = useAppStore((s) => s.tabsByWorktree[worktreeId] ?? EMPTY_TABS)
|
||||
const browserTabs = useAppStore((s) => s.browserTabsByWorktree[worktreeId] ?? EMPTY_BROWSER_TABS)
|
||||
// Tabs Sleep put to rest stay in the layout but are not activity (NEW-01).
|
||||
const browserTabs = useAppStore((s) =>
|
||||
s.asleepBrowserWorktreeIds?.[worktreeId]
|
||||
? EMPTY_BROWSER_TABS
|
||||
: (s.browserTabsByWorktree[worktreeId] ?? EMPTY_BROWSER_TABS)
|
||||
)
|
||||
const hasStructuredChat = useAppStore((s) =>
|
||||
hasAwakeStructuredChat(s.unifiedTabsByWorktree[worktreeId], s.structuredChatSleptAtByPaneKey)
|
||||
)
|
||||
|
||||
+3
-1
@@ -35,7 +35,9 @@ export function selectWorktreeActivityStatuses(
|
||||
worktreeId,
|
||||
resolveWorktreeStatus({
|
||||
tabs: statusInputs.tabsByWorktree[worktreeId] ?? EMPTY_TABS,
|
||||
browserTabs: statusInputs.browserTabsByWorktree[worktreeId] ?? EMPTY_BROWSER_TABS,
|
||||
browserTabs: statusInputs.asleepBrowserWorktreeIds?.[worktreeId]
|
||||
? EMPTY_BROWSER_TABS
|
||||
: (statusInputs.browserTabsByWorktree[worktreeId] ?? EMPTY_BROWSER_TABS),
|
||||
hasStructuredChat: hasAwakeStructuredChat(
|
||||
statusInputs.unifiedTabsByWorktree[worktreeId],
|
||||
statusInputs.structuredChatSleptAtByPaneKey
|
||||
|
||||
@@ -19,6 +19,8 @@ export type VisibleWorktreeOptions = {
|
||||
tabsByWorktree: Record<string, Pick<TerminalTab, 'id'>[]> | null
|
||||
ptyIdsByTabId: Record<string, string[]> | null
|
||||
browserTabsByWorktree?: Record<string, { id: string }[]> | null
|
||||
/** Workspaces whose browser tabs Sleep put to rest: those tabs are not activity (NEW-01). */
|
||||
asleepBrowserWorktreeIds?: Record<string, number>
|
||||
worktreeIdsWithLiveAgent: ReadonlySet<string>
|
||||
worktreeIdsWithStructuredChat?: ReadonlySet<string>
|
||||
hideDefaultBranchWorkspace: boolean
|
||||
|
||||
+2
-1
@@ -23,6 +23,7 @@ export type DesktopWorkspaceRowFactInputs = {
|
||||
tabsByWorktree: Record<string, Pick<TerminalTab, 'id'>[]> | null
|
||||
ptyIdsByTabId: Record<string, string[]> | null
|
||||
browserTabsByWorktree?: Record<string, { id: string }[]> | null
|
||||
asleepBrowserWorktreeIds?: Record<string, number>
|
||||
worktreeIdsWithLiveAgent: ReadonlySet<string>
|
||||
worktreeIdsWithStructuredChat?: ReadonlySet<string>
|
||||
/** Rows in a PTY-rebind grace window; read as unverifiable, never as asleep (#15996). */
|
||||
@@ -54,7 +55,7 @@ export function buildDesktopWorkspaceRowFactReader(
|
||||
worktree.id,
|
||||
inputs.tabsByWorktree,
|
||||
inputs.ptyIdsByTabId,
|
||||
inputs.browserTabsByWorktree,
|
||||
inputs.asleepBrowserWorktreeIds?.[worktree.id] ? null : inputs.browserTabsByWorktree,
|
||||
inputs.worktreeIdsWithLiveAgent,
|
||||
inputs.worktreeIdsWithStructuredChat
|
||||
)
|
||||
|
||||
+4
-1
@@ -1,3 +1,4 @@
|
||||
import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep'
|
||||
import type { AppState } from '@/store/types'
|
||||
import type { Worktree } from '../../../../../../shared/worktree/types'
|
||||
import { isSleepingSweepExempt } from '../../../../../../shared/workspace-view/workspace-row-filters'
|
||||
@@ -15,7 +16,9 @@ export function createSleepingSweepHiddenCheck(
|
||||
exemptWorktreeIds?: ReadonlySet<string>
|
||||
): (worktree: Worktree) => boolean {
|
||||
const tabsByWorktree = getVisibleWorktreeTerminalActivityTabs(state.tabsByWorktree)
|
||||
const browserTabsByWorktree = getVisibleWorktreeBrowserActivityTabs(state.browserTabsByWorktree)
|
||||
const browserTabsByWorktree = getVisibleWorktreeBrowserActivityTabs(
|
||||
selectAwakeBrowserTabsByWorktree(state)
|
||||
)
|
||||
const liveAgentWorktrees = getWorktreeIdsWithLiveAgent(
|
||||
state.agentStatusByPaneKey,
|
||||
tabsByWorktree,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep'
|
||||
import { selectSidebarLineageParentIdentities } from '@/store/slices/worktrees/metadata/cross-store-lineage-parents'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { shallow } from 'zustand/shallow'
|
||||
@@ -93,7 +94,9 @@ export function useVisibleSidebarWorktrees(args: {
|
||||
)
|
||||
const ptyIdsByTabId = useAppStore((s) => (needsActivityMaps ? s.ptyIdsByTabId : null))
|
||||
const browserTabsByWorktree = useAppStore((s) =>
|
||||
!showSleepingWorkspaces ? getVisibleWorktreeBrowserActivityTabs(s.browserTabsByWorktree) : null
|
||||
!showSleepingWorkspaces
|
||||
? getVisibleWorktreeBrowserActivityTabs(selectAwakeBrowserTabsByWorktree(s))
|
||||
: null
|
||||
)
|
||||
const worktreeIdsWithStructuredChat = useAppStore((s) =>
|
||||
getStructuredChatWorktreeIds(
|
||||
|
||||
+1
@@ -21,6 +21,7 @@ export function buildVisibleWorktreeOptionsFromState(
|
||||
tabsByWorktree: state.tabsByWorktree,
|
||||
ptyIdsByTabId: state.ptyIdsByTabId,
|
||||
browserTabsByWorktree: state.browserTabsByWorktree,
|
||||
asleepBrowserWorktreeIds: state.asleepBrowserWorktreeIds,
|
||||
worktreeIdsWithLiveAgent: getWorktreeIdsWithLiveAgent(
|
||||
state.agentStatusByPaneKey,
|
||||
state.tabsByWorktree,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// NS-03: failed usage reads show a quiet "--" (reason on hover), never a permanent warning.
|
||||
import { defineFixture } from '../../component-fixtures/component-fixture'
|
||||
import type { ProviderRateLimits } from '../../../../shared/rate-limit-types'
|
||||
import { ProviderSegment } from './StatusBar'
|
||||
|
||||
function errorProvider(
|
||||
provider: ProviderRateLimits['provider'],
|
||||
failureKind: string
|
||||
): ProviderRateLimits {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: minimal error-state fixture data.
|
||||
return {
|
||||
provider,
|
||||
session: null,
|
||||
weekly: null,
|
||||
updatedAt: 0,
|
||||
error: 'usage read failed',
|
||||
status: 'error',
|
||||
usageMetadata: { failureKind }
|
||||
} as unknown as ProviderRateLimits
|
||||
}
|
||||
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: minimal placeholder fixture data.
|
||||
const notConfiguredOnCloud = {
|
||||
provider: 'codex',
|
||||
session: null,
|
||||
weekly: null,
|
||||
updatedAt: 0,
|
||||
error: 'Not configured on Orca Cloud',
|
||||
status: 'error',
|
||||
usageMetadata: {
|
||||
ownerNotSetUp: { kind: 'not-configured', ownerLabel: 'Orca Cloud', signInSavedHereOnly: false }
|
||||
}
|
||||
} as unknown as ProviderRateLimits
|
||||
|
||||
export const calmErrors = defineFixture({
|
||||
width: 360,
|
||||
render: () => (
|
||||
<div className="flex h-6 items-center gap-4 border-t border-border px-3 text-xs">
|
||||
<ProviderSegment p={errorProvider('cursor', 'stale-token')} compact={false} display="used" />
|
||||
<ProviderSegment p={errorProvider('gemini', 'unknown')} compact={false} display="used" />
|
||||
<ProviderSegment p={notConfiguredOnCloud} compact={false} display="used" />
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -1,7 +1,6 @@
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import React from 'react'
|
||||
import type {
|
||||
OwnerNotSetUpPlaceholder,
|
||||
ProviderRateLimits,
|
||||
RateLimitWindow
|
||||
} from '../../../../shared/rate-limit-types'
|
||||
@@ -21,7 +20,6 @@ import {
|
||||
getProviderUsageStatusLabel
|
||||
} from './tooltip'
|
||||
import { getProviderDisplayName } from '../../../../shared/usage-provider-windows'
|
||||
import { getOwnerNotSetUpLabelParts } from './owner-not-set-up-copy'
|
||||
import { isClaudeUsageWaitingForClaude } from './usage-error-copy'
|
||||
import { getTightestUsageSection, getUsageHeadlineSection } from './UsageRosterPanel'
|
||||
import { formatBareUsagePercentage, formatUsagePercentageLabel } from './usage-percentage-label'
|
||||
@@ -91,27 +89,6 @@ export function ProviderLetterBadge({ p }: { p: ProviderRateLimits }): React.JSX
|
||||
)
|
||||
}
|
||||
|
||||
// Why only the host name truncates: the phrase around it must stay readable in every locale.
|
||||
function OwnerNotSetUpLabel({
|
||||
placeholder
|
||||
}: {
|
||||
placeholder: OwnerNotSetUpPlaceholder
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const { before, host, after } = getOwnerNotSetUpLabelParts(placeholder, t)
|
||||
return (
|
||||
<span className="text-[11px] font-medium">
|
||||
{before}
|
||||
{host ? (
|
||||
<span data-owner-host className="inline-block max-w-28 truncate align-bottom">
|
||||
{host}
|
||||
</span>
|
||||
) : null}
|
||||
{after}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export type UsageTone = 'urgent' | 'warning' | 'normal'
|
||||
|
||||
/** Urgency by consumption, matching the usage bar colors, whatever % display the user chose. */
|
||||
@@ -288,24 +265,31 @@ export function ProviderSegment({
|
||||
}
|
||||
|
||||
if (p.usageMetadata?.ownerNotSetUp) {
|
||||
// Why calm: "Not configured on Orca Cloud" sat in the bar for good in every cloud workspace
|
||||
// (JA-07/NS-03). Same quiet "--" as a failed read; the reason stays on hover and in the card.
|
||||
const reason = getProviderUsageErrorMessage(p, t)
|
||||
return (
|
||||
<span
|
||||
className="inline-flex items-center gap-1 text-muted-foreground"
|
||||
title={getProviderUsageErrorMessage(p, t)}
|
||||
className="inline-flex items-center gap-1 text-muted-foreground/60"
|
||||
title={reason}
|
||||
aria-label={reason}
|
||||
>
|
||||
<ProviderIcon provider={provider} />
|
||||
{/* Why "--" when compact: an icon alone would read as a healthy chip. */}
|
||||
{compact ? '--' : <OwnerNotSetUpLabel placeholder={p.usageMetadata.ownerNotSetUp} />}
|
||||
<ProviderIcon provider={provider} /> --
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// Why calm: a failed usage read isn't the user's emergency, and a warning that never clears turns
|
||||
// into permanent noise ("Refresh failed", "⚠ Sign-in expired"). The bar shows a quiet "--"; the
|
||||
// reason and its fix stay one hover away in the usage card.
|
||||
if (p.status === 'error' && !tightest) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-muted-foreground">
|
||||
<ProviderIcon provider={provider} />
|
||||
{!calm && <AlertTriangle size={11} className="text-muted-foreground/80" />}
|
||||
{!compact && <span className="text-[11px] font-medium">{statusLabel}</span>}
|
||||
<span
|
||||
className="inline-flex items-center gap-1 text-muted-foreground/60"
|
||||
title={statusLabel}
|
||||
aria-label={statusLabel}
|
||||
>
|
||||
<ProviderIcon provider={provider} /> --
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -318,7 +302,10 @@ export function ProviderSegment({
|
||||
mode === 'verbose' && groupedBuckets.length > 0 && groupedBuckets.length === sections.length
|
||||
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<span
|
||||
className={cn('inline-flex items-center gap-1.5', isStale && 'opacity-60')}
|
||||
title={isStale ? statusLabel : undefined}
|
||||
>
|
||||
<ProviderIcon provider={provider} />
|
||||
{mode === 'verbose' && tightest && !compact ? (
|
||||
<MiniBar usedPct={clampUsedPercent(tightest.window.usedPercent)} display={display} />
|
||||
@@ -350,7 +337,6 @@ export function ProviderSegment({
|
||||
<span className="tabular-nums">{formatCompactExtraUsage(p.extraUsage, t)}</span>
|
||||
</>
|
||||
) : null}
|
||||
{isStale && <AlertTriangle size={11} className="text-muted-foreground/80" />}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -25,30 +25,6 @@ export function getOwnerNotSetUpLabel(
|
||||
return translateOwnerNotSetUpLabel(placeholder, placeholder.ownerLabel, t)
|
||||
}
|
||||
|
||||
// Why a sentinel, not Trans markup: a host name containing "<" would parse as markup.
|
||||
const HOST_SLOT = '\u0000'
|
||||
|
||||
/** The label split around the host name, so only the name truncates wherever the locale puts it. */
|
||||
export function getOwnerNotSetUpLabelParts(
|
||||
placeholder: OwnerNotSetUpPlaceholder,
|
||||
t?: Translate
|
||||
): {
|
||||
before: string
|
||||
host: string
|
||||
after: string
|
||||
} {
|
||||
const template = translateOwnerNotSetUpLabel(placeholder, HOST_SLOT, t)
|
||||
const slot = template.indexOf(HOST_SLOT)
|
||||
if (slot === -1) {
|
||||
return { before: getOwnerNotSetUpLabel(placeholder, t), host: '', after: '' }
|
||||
}
|
||||
return {
|
||||
before: template.slice(0, slot),
|
||||
host: placeholder.ownerLabel,
|
||||
after: template.slice(slot + HOST_SLOT.length)
|
||||
}
|
||||
}
|
||||
|
||||
export function getOwnerNotSetUpNote(
|
||||
placeholder: OwnerNotSetUpPlaceholder,
|
||||
t: Translate = translate
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { ProviderRateLimits } from '../../../../shared/rate-limit-types'
|
||||
|
||||
vi.mock('@/i18n/i18n', () => ({
|
||||
i18n: { language: 'en' },
|
||||
translate: (_key: string, fallback: string, values?: Record<string, string>) => {
|
||||
let result = fallback
|
||||
for (const [key, value] of Object.entries(values ?? {})) {
|
||||
result = result.replace(`{{${key}}}`, value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/components/agent/icons/AgentIcon', () => ({
|
||||
AgentIcon: () => null
|
||||
}))
|
||||
|
||||
vi.mock('../../store', () => ({
|
||||
useAppStore: (selector: (state: { usagePercentageDisplay: 'used' | 'remaining' }) => unknown) =>
|
||||
selector({ usagePercentageDisplay: 'used' })
|
||||
}))
|
||||
|
||||
|
||||
// NS-03 (Neil): "Refresh failed" and "⚠ Sign-in expired" sat in the status bar for good. A failed
|
||||
// usage read now shows a quiet "--" with the reason as its label; the usage card explains it.
|
||||
describe('ProviderSegment calm error', () => {
|
||||
it.each([
|
||||
['cursor', 'stale-token', 'Sign-in expired'],
|
||||
['gemini', 'unknown', 'Refresh failed'],
|
||||
// design-squad P3: "⚠ Usage unavailable" twice (Claude + Codex) in a cloud workspace.
|
||||
['claude', 'usage-unavailable', 'Usage unavailable']
|
||||
] as const)('%s %s renders "--", no warning icon, label kept for a11y', async (provider, kind, label) => {
|
||||
const { ProviderSegment } = await import('./StatusBar')
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: minimal error-state fixture.
|
||||
const p = {
|
||||
provider,
|
||||
session: null,
|
||||
weekly: null,
|
||||
updatedAt: 0,
|
||||
error: 'boom',
|
||||
status: 'error',
|
||||
usageMetadata: { failureKind: kind }
|
||||
} as unknown as ProviderRateLimits
|
||||
const html = renderToStaticMarkup(
|
||||
<ProviderSegment p={p} compact={false} display="used" mode="verbose" />
|
||||
)
|
||||
expect(html).toContain('--')
|
||||
expect(html).toContain(`aria-label="${label}"`)
|
||||
expect(html).not.toContain(`>${label}<`)
|
||||
expect(html).not.toContain('lucide-triangle-alert')
|
||||
})
|
||||
|
||||
it('owner not set up (e.g. "Not configured on Orca Cloud") is the same quiet "--"', async () => {
|
||||
const { ProviderSegment } = await import('./StatusBar')
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: minimal placeholder fixture.
|
||||
const p = {
|
||||
provider: 'codex',
|
||||
session: null,
|
||||
weekly: null,
|
||||
updatedAt: 0,
|
||||
error: 'Not configured on Orca Cloud',
|
||||
status: 'error',
|
||||
usageMetadata: {
|
||||
ownerNotSetUp: { kind: 'not-configured', ownerLabel: 'Orca Cloud', signInSavedHereOnly: false }
|
||||
}
|
||||
} as unknown as ProviderRateLimits
|
||||
const html = renderToStaticMarkup(
|
||||
<ProviderSegment p={p} compact={false} display="used" mode="verbose" />
|
||||
)
|
||||
expect(html).toContain('--')
|
||||
expect(html).toContain('Not configured on Orca Cloud')
|
||||
expect(html).not.toContain('>Not configured on')
|
||||
})
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user