Merge pull request #276 from nwparker/cloud/agents-a5-followups

A5 follow-ups: offline last-known state, retry missed syncs, remove-prompt fixture, dev e2e
This commit is contained in:
Neil
2026-11-10 07:43:54 -08:00
committed by GitHub
14 changed files with 680 additions and 127 deletions
@@ -6,7 +6,7 @@ import type { CloudSecretsClient } from '../cloud-secrets/cloud-secrets-client'
import { getOrcaCloudAvailability } from '../hosted-sandbox/hosted-sandbox-install'
import { getOrcaProfileIndexGeneration } from '../orca-profiles/profile-index-generation'
import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store'
import type { AgentApiKeyCloudConnection } from './agent-api-key-cloud-sync'
import type { AgentApiKeyCloudLink } from './agent-api-key-cloud-sync'
let client: CloudSecretsClient | null = null
let recorder: ((agent: TuiAgent, envName: string) => Promise<void>) | null = null
@@ -26,15 +26,27 @@ export function setAgentApiKeyCloudClient(next: CloudSecretsClient | null): void
client = next
}
/** The signed-in Orca account with Orca Cloud, or null: signed out, no capability, or offline. */
export async function agentApiKeyCloudConnection(): Promise<AgentApiKeyCloudConnection | null> {
/**
* Where this desktop stands with the Orca account. Signed in but `unavailable` means the session
* couldn't be refreshed (offline), not a sign-out: the account is still the profile's.
*/
export async function agentApiKeyCloudLink(): Promise<AgentApiKeyCloudLink> {
const current = client
const generation = getOrcaProfileIndexGeneration()
if (!current || (await getOrcaCloudAvailability()) !== 'offered') {
return null
if (!current) {
return { kind: 'signed-out' }
}
const availability = await getOrcaCloudAvailability()
const accountId = ensureActiveOrcaProfile(app.getPath('userData')).profile.cloud?.userId
// Every sign-in, sign-out and account or team switch rewrites the profile index.
const isCurrent = (): boolean => getOrcaProfileIndexGeneration() === generation
return accountId && isCurrent() ? { accountId, client: current, isCurrent } : null
if (!accountId || !isCurrent()) {
return { kind: 'signed-out' }
}
if (availability === 'offered') {
return { kind: 'connected', connection: { accountId, client: current, isCurrent } }
}
return availability === 'unavailable'
? { kind: 'unreachable', accountId }
: { kind: 'signed-out' }
}
@@ -0,0 +1,152 @@
// The A5 sync ledger: per Orca account, which variables this computer wrote (and from which vault
// key) plus saves still waiting to reach the account. Names, ids and timestamps only; never values.
import { readFile } from 'node:fs/promises'
import { writeSecureFile } from '../../shared/secure-storage/secure-file'
import type { AgentApiKeySummary } from '../../shared/agent-api-keys/agent-api-key-catalog'
export type LedgerEntry = {
/** The vault key whose value was written. */
keyId: string
/** That key's `updatedAt` when it was written, so a later edit that failed to sync isn't "synced". */
keyUpdatedAt: number
syncedAt: number
}
export type LedgerFile = {
version: 1
/** accountId → variable → what this computer wrote there. */
accounts: Record<string, Record<string, LedgerEntry>>
/**
* accountId → key id → that key's `updatedAt`: saves made while signed in to this account that
* haven't reached it yet. Retried on reconnect and at start; nothing else is ever uploaded unasked.
*/
pending?: Record<string, Record<string, number>>
}
const MAX_LEDGER_BYTES = 256 * 1024
function isEntry(value: unknown): value is LedgerEntry {
return (
typeof value === 'object' &&
value !== null &&
'keyId' in value &&
'keyUpdatedAt' in value &&
'syncedAt' in value &&
typeof value.keyId === 'string' &&
typeof value.keyUpdatedAt === 'number' &&
typeof value.syncedAt === 'number'
)
}
export function parseLedger(text: string): LedgerFile {
const ledger: LedgerFile = { version: 1, accounts: {} }
if (text.length > MAX_LEDGER_BYTES) {
return ledger
}
let parsed: unknown
try {
parsed = JSON.parse(text)
} catch {
return ledger
}
if (
typeof parsed !== 'object' ||
parsed === null ||
!('version' in parsed) ||
parsed.version !== 1 ||
!('accounts' in parsed) ||
typeof parsed.accounts !== 'object' ||
parsed.accounts === null
) {
return ledger
}
for (const [accountId, names] of Object.entries(parsed.accounts)) {
if (typeof names !== 'object' || names === null) {
continue
}
const kept: Record<string, LedgerEntry> = {}
for (const [name, entry] of Object.entries(names)) {
if (isEntry(entry)) {
kept[name] = entry
}
}
ledger.accounts[accountId] = kept
}
if ('pending' in parsed && typeof parsed.pending === 'object' && parsed.pending !== null) {
const pending: Record<string, Record<string, number>> = {}
for (const [accountId, keys] of Object.entries(parsed.pending)) {
if (typeof keys !== 'object' || keys === null) {
continue
}
pending[accountId] = Object.fromEntries(
Object.entries(keys).filter(
(entry): entry is [string, number] => typeof entry[1] === 'number'
)
)
}
ledger.pending = pending
}
return ledger
}
export function pendingOf(
keys: readonly AgentApiKeySummary[],
pending: Record<string, number>
): { pending?: string[] } {
const ids = keys.filter((key) => pending[key.id] === key.updatedAt).map((key) => key.id)
return ids.length > 0 ? { pending: ids } : {}
}
/** The variables `keyId` wrote to the account (more than one after a rename). */
export function namesWrittenBy(names: Record<string, LedgerEntry>, keyId: string): string[] {
return Object.entries(names)
.filter(([, entry]) => entry.keyId === keyId)
.map(([name]) => name)
}
/** The ledger file, cached: the sync is its only writer. Written 0600. */
export class CloudKeyLedger {
private cached: LedgerFile | null = null
constructor(private readonly path: string) {}
async read(): Promise<LedgerFile> {
if (this.cached) {
return this.cached
}
let text = ''
try {
text = await readFile(this.path, 'utf8')
} catch {
// Missing or unreadable: nothing was synced from here that we can prove, so remove nothing.
}
return (this.cached = parseLedger(text))
}
private write(next: LedgerFile): void {
writeSecureFile(this.path, JSON.stringify(next, null, 2))
this.cached = next
}
async setNames(accountId: string, names: Record<string, LedgerEntry>): Promise<void> {
const ledger = await this.read()
this.write({ ...ledger, accounts: { ...ledger.accounts, [accountId]: names } })
}
/** Marks (a version of) a key as waiting for the account, or clears it. True when one was added. */
async setPending(accountId: string, keyId: string, updatedAt: number | null): Promise<boolean> {
const ledger = await this.read()
const current = ledger.pending?.[accountId] ?? {}
if ((current[keyId] ?? null) === updatedAt) {
return false
}
const { [keyId]: _old, ...rest } = current
const keys = updatedAt === null ? rest : { ...rest, [keyId]: updatedAt }
this.write({ ...ledger, pending: { ...ledger.pending, [accountId]: keys } })
return updatedAt !== null
}
hasPending(): boolean {
return Object.values(this.cached?.pending ?? {}).some((keys) => Object.keys(keys).length > 0)
}
}
@@ -0,0 +1,81 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createAgentApiKeyCloudRetry } from './agent-api-key-cloud-retry'
type Link = 'connected' | 'unreachable' | 'signed-out' | null
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
function fakeCloud() {
const cloud: {
lastLink: Link
pending: boolean
hasPending: () => boolean
flushPending: ReturnType<typeof vi.fn<() => Promise<boolean>>>
} = {
lastLink: null,
pending: false,
hasPending: () => cloud.pending,
flushPending: vi.fn(async () => false)
}
return cloud
}
describe('createAgentApiKeyCloudRetry', () => {
it('runs only when kicked, backs off while Orca is unreachable, and stops once it is back', async () => {
const cloud = fakeCloud()
const notify = vi.fn()
const retry = createAgentApiKeyCloudRetry({
cloud,
serial: (run) => run(),
notify,
firstDelayMs: 10,
maxDelayMs: 40
})
await vi.advanceTimersByTimeAsync(1000)
expect(cloud.flushPending).not.toHaveBeenCalled()
cloud.lastLink = 'unreachable'
retry.kick()
await vi.advanceTimersByTimeAsync(10)
expect(cloud.flushPending).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(19)
expect(cloud.flushPending).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(cloud.flushPending).toHaveBeenCalledTimes(2)
cloud.flushPending.mockImplementationOnce(async () => {
cloud.lastLink = 'connected'
return true
})
await vi.advanceTimersByTimeAsync(40)
expect(cloud.flushPending).toHaveBeenCalledTimes(3)
expect(notify).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(10_000)
expect(cloud.flushPending).toHaveBeenCalledTimes(3)
retry.stop()
})
it('a soon kick (wake, start) resets the backoff', async () => {
const cloud = fakeCloud()
cloud.pending = true
const retry = createAgentApiKeyCloudRetry({
cloud,
serial: (run) => run(),
notify: () => {},
firstDelayMs: 10,
maxDelayMs: 1000
})
retry.kick()
await vi.advanceTimersByTimeAsync(10 + 20 + 40)
expect(cloud.flushPending).toHaveBeenCalledTimes(3)
retry.kick({ soon: true })
await vi.advanceTimersByTimeAsync(10)
expect(cloud.flushPending).toHaveBeenCalledTimes(4)
retry.stop()
})
})
@@ -0,0 +1,77 @@
// Saves made while signed in that didn't reach the Orca account (offline, a failed request) are
// retried at start, on wake, and with backoff while Orca is unreachable or a save is pending. The
// timer stops as soon as there is nothing to wait for; the sync kicks it again when there is.
import type { AgentApiKeyCloudSync } from './agent-api-key-cloud-sync'
const FIRST_DELAY_MS = 15_000
const MAX_DELAY_MS = 15 * 60_000
export type AgentApiKeyCloudRetry = {
/** Something is waiting (a pending save, Orca unreachable) or the network may be back. */
kick: (options?: { soon?: boolean }) => void
stop: () => void
}
export function createAgentApiKeyCloudRetry({
cloud,
serial,
notify,
firstDelayMs = FIRST_DELAY_MS,
maxDelayMs = MAX_DELAY_MS
}: {
cloud: Pick<AgentApiKeyCloudSync, 'flushPending' | 'hasPending' | 'lastLink'>
serial: <T>(run: () => Promise<T>) => Promise<T>
/** Tells open windows to re-read the keys' state. */
notify: () => void
firstDelayMs?: number
maxDelayMs?: number
}): AgentApiKeyCloudRetry {
let timer: ReturnType<typeof setTimeout> | null = null
let delay = firstDelayMs
let stopped = false
const waiting = (): boolean => cloud.lastLink === 'unreachable' || cloud.hasPending()
const run = async (): Promise<void> => {
timer = null
try {
const before = cloud.lastLink
const changed = await serial(() => cloud.flushPending())
if (changed || cloud.lastLink !== before) {
notify()
}
} catch {
// Treated like any other miss: back off and try again.
}
if (waiting()) {
delay = Math.min(delay * 2, maxDelayMs)
schedule()
} else {
delay = firstDelayMs
}
}
const schedule = (): void => {
if (stopped || timer) {
return
}
timer = setTimeout(() => void run(), delay)
timer.unref?.()
}
return {
kick: ({ soon = false } = {}) => {
if (soon) {
delay = firstDelayMs
if (timer) {
clearTimeout(timer)
timer = null
}
}
schedule()
},
stop: () => {
stopped = true
if (timer) {
clearTimeout(timer)
}
}
}
}
@@ -41,9 +41,15 @@ function setup(accountId: string | null = 'user-a', vault: AgentApiKeySummary[]
return { accountId: id, client, isCurrent: () => generation === at }
}
let current: AgentApiKeyCloudConnection | null = accountId ? connect(accountId) : null
let offline = false
const sync = new AgentApiKeyCloudSync({
ledgerPath: join(root, 'ledger.json'),
connection: async () => current,
link: async () =>
!current
? { kind: 'signed-out' }
: offline
? { kind: 'unreachable', accountId: current.accountId }
: { kind: 'connected', connection: current },
valueOf: async () => VALUE,
listKeys: async () => vault,
now: () => 100
@@ -54,6 +60,9 @@ function setup(accountId: string | null = 'user-a', vault: AgentApiKeySummary[]
signInAs: (id: string | null) => {
generation++
current = id ? connect(id) : null
},
setOffline: (next: boolean) => {
offline = next
}
}
}
@@ -106,7 +115,12 @@ describe('AgentApiKeyCloudSync', () => {
expect(outcome).toEqual({ kind: 'failed', error: 'unavailable', keyId: 'k1' })
expect(JSON.stringify(outcome)).not.toContain(VALUE)
expect(JSON.stringify(warn.mock.calls)).not.toContain(VALUE)
expect(await sync.state([key()])).toEqual({ signedIn: true, synced: [], managed: [] })
expect(await sync.state([key()])).toEqual({
signedIn: true,
synced: [],
managed: [],
pending: ['k1']
})
warn.mockRestore()
})
@@ -116,7 +130,12 @@ describe('AgentApiKeyCloudSync', () => {
client.put.mockRejectedValueOnce(new EnvironmentProviderError('timeout', 'slow'))
const edited = key({ updatedAt: 2, hint: 'zzzz' })
await sync.push(edited)
expect(await sync.state([edited])).toEqual({ signedIn: true, synced: [], managed: ['k1'] })
expect(await sync.state([edited])).toEqual({
signedIn: true,
synced: [],
managed: ['k1'],
pending: ['k1']
})
})
it('keeps one ledger per Orca account', async () => {
@@ -257,4 +276,65 @@ describe('AgentApiKeyCloudSync', () => {
}
)
})
it('shows the last-known state while Orca is unreachable, and nothing for an account never connected here', async () => {
const { sync, setOffline } = setup()
setOffline(true)
expect(await sync.state([key()])).toEqual({ signedIn: false, synced: [], managed: [] })
setOffline(false)
await sync.push(key())
setOffline(true)
expect(await sync.state([key()])).toEqual({
signedIn: true,
unreachable: true,
synced: ['k1'],
managed: ['k1']
})
const ledger = await readFile(join(root, 'ledger.json'), 'utf8')
expect(ledger).not.toContain(VALUE)
})
it('queues a save made while offline and sends it when Orca is back, once', async () => {
const edited = key({ updatedAt: 2 })
const { client, sync, setOffline } = setup('user-a', [edited])
await sync.push(key())
setOffline(true)
expect(await sync.push(edited)).toEqual({ kind: 'failed', error: 'unavailable', keyId: 'k1' })
expect(await sync.state([edited])).toMatchObject({ unreachable: true, pending: ['k1'] })
expect(sync.hasPending()).toBe(true)
expect(await sync.flushPending()).toBe(false)
setOffline(false)
expect(await sync.flushPending()).toBe(true)
expect(client.put).toHaveBeenCalledTimes(2)
expect(await sync.state([edited])).toEqual({ signedIn: true, synced: ['k1'], managed: ['k1'] })
expect(await sync.flushPending()).toBe(false)
expect(client.put).toHaveBeenCalledTimes(2)
})
it('retries a failed request, but drops keys edited or removed since and non-transient failures', async () => {
const other = key({ id: 'k2', envName: 'OPENAI_API_KEY' })
const vault = [key(), other]
const { client, sync } = setup('user-a', vault)
vi.spyOn(console, 'warn').mockImplementation(() => {})
client.put.mockRejectedValueOnce(new EnvironmentProviderError('timeout', 'slow'))
client.put.mockRejectedValueOnce(new EnvironmentProviderError('timeout', 'slow'))
await sync.push(key())
await sync.push(other)
expect(await sync.state(vault)).toMatchObject({ pending: ['k1', 'k2'] })
// k1 was edited since its failed save: the user's newer save decides, not the retry.
vault[0] = key({ updatedAt: 9 })
expect(await sync.flushPending()).toBe(true)
expect(client.put).toHaveBeenCalledTimes(3)
expect(client.put).toHaveBeenLastCalledWith({ scope: 'personal' }, 'OPENAI_API_KEY', VALUE)
expect(sync.hasPending()).toBe(false)
vi.mocked(console.warn).mockRestore()
})
it('never queues keys saved while signed out', async () => {
const { client, sync, signInAs } = setup(null, [key()])
await sync.push(key())
signInAs('user-a')
expect(await sync.flushPending()).toBe(false)
expect(client.put).not.toHaveBeenCalled()
})
})
@@ -2,8 +2,6 @@
// secret of the same variable. Cloud secrets are write-only, so this is one way (desktop → account),
// and a key removed here leaves the account copy alone unless this computer wrote it and the user
// confirms. The ledger records which variables this computer wrote, per account; it holds no values.
import { readFile } from 'node:fs/promises'
import { writeSecureFile } from '../../shared/secure-storage/secure-file'
import type { AgentApiKeySummary } from '../../shared/agent-api-keys/agent-api-key-catalog'
import {
agentApiKeyCloudEligible,
@@ -16,6 +14,13 @@ import {
cloudSecretsFailureCode,
type CloudSecretsClient
} from '../cloud-secrets/cloud-secrets-client'
import {
CloudKeyLedger,
namesWrittenBy,
pendingOf,
type LedgerEntry,
type LedgerFile
} from './agent-api-key-cloud-ledger'
/** The signed-in account that can hold personal Cloud secrets, or null (signed out, no Cloud). */
export type AgentApiKeyCloudConnection = {
@@ -25,137 +30,116 @@ export type AgentApiKeyCloudConnection = {
isCurrent: () => boolean
}
type LedgerEntry = {
/** The vault key whose value was written. */
keyId: string
/** That key's `updatedAt` when it was written, so a later edit that failed to sync isn't "synced". */
keyUpdatedAt: number
syncedAt: number
}
/**
* Where the desktop stands with the Orca account. `unreachable`: signed in, but Orca can't be
* reached now (offline, or the session refresh failed); rows keep their last-known state.
*/
export type AgentApiKeyCloudLink =
| { kind: 'connected'; connection: AgentApiKeyCloudConnection }
| { kind: 'unreachable'; accountId: string }
| { kind: 'signed-out' }
type LedgerFile = {
version: 1
/** accountId → variable → what this computer wrote there. */
accounts: Record<string, Record<string, LedgerEntry>>
}
/** Failures worth retrying on their own; anything else needs the user. */
const TRANSIENT: ReadonlySet<CloudSecretsErrorCode> = new Set([
'unavailable',
'timeout',
'unknown',
'unauthorized'
])
const MAX_LEDGER_BYTES = 256 * 1024
const PERSONAL = { scope: 'personal' } as const
function isEntry(value: unknown): value is LedgerEntry {
return (
typeof value === 'object' &&
value !== null &&
'keyId' in value &&
'keyUpdatedAt' in value &&
'syncedAt' in value &&
typeof value.keyId === 'string' &&
typeof value.keyUpdatedAt === 'number' &&
typeof value.syncedAt === 'number'
)
}
function parseLedger(text: string): LedgerFile {
const ledger: LedgerFile = { version: 1, accounts: {} }
if (text.length > MAX_LEDGER_BYTES) {
return ledger
}
let parsed: unknown
try {
parsed = JSON.parse(text)
} catch {
return ledger
}
if (
typeof parsed !== 'object' ||
parsed === null ||
!('version' in parsed) ||
parsed.version !== 1 ||
!('accounts' in parsed) ||
typeof parsed.accounts !== 'object' ||
parsed.accounts === null
) {
return ledger
}
for (const [accountId, names] of Object.entries(parsed.accounts)) {
if (typeof names !== 'object' || names === null) {
continue
}
const kept: Record<string, LedgerEntry> = {}
for (const [name, entry] of Object.entries(names)) {
if (isEntry(entry)) {
kept[name] = entry
}
}
ledger.accounts[accountId] = kept
}
return ledger
}
export type AgentApiKeyCloudSyncOptions = {
ledgerPath: string
/** Null when signed out of Orca or Orca Cloud isn't offered: keys then stay on this computer. */
connection: () => Promise<AgentApiKeyCloudConnection | null>
/** Signed out (or no Orca Cloud): keys stay on this computer. */
link: () => Promise<AgentApiKeyCloudLink>
/** Unseals one vault key for a single write. */
valueOf: (keyId: string) => Promise<string | null>
/** The vault's keys now, to tell whether another key owns a variable's account copy. */
listKeys: () => Promise<AgentApiKeySummary[]>
/** Called when something now waits on Orca (it's unreachable, or a save is pending). */
onWaiting?: () => void
now?: () => number
}
/** The variables `keyId` wrote to the account (more than one after a rename). */
function namesWrittenBy(names: Record<string, LedgerEntry>, keyId: string): string[] {
return Object.entries(names)
.filter(([, entry]) => entry.keyId === keyId)
.map(([name]) => name)
}
export class AgentApiKeyCloudSync {
private cached: LedgerFile | null = null
private readonly book: CloudKeyLedger
constructor(private readonly options: AgentApiKeyCloudSyncOptions) {}
constructor(private readonly options: AgentApiKeyCloudSyncOptions) {
this.book = new CloudKeyLedger(options.ledgerPath)
}
private now(): number {
return this.options.now?.() ?? Date.now()
}
private async ledger(): Promise<LedgerFile> {
if (this.cached) {
return this.cached
}
let text = ''
try {
text = await readFile(this.options.ledgerPath, 'utf8')
} catch {
// Missing or unreadable: nothing was synced from here that we can prove, so remove nothing.
}
return (this.cached = parseLedger(text))
private ledger(): Promise<LedgerFile> {
return this.book.read()
}
private async setNames(accountId: string, names: Record<string, LedgerEntry>): Promise<void> {
const ledger = await this.ledger()
const next: LedgerFile = { ...ledger, accounts: { ...ledger.accounts, [accountId]: names } }
writeSecureFile(this.options.ledgerPath, JSON.stringify(next, null, 2))
this.cached = next
private setNames(accountId: string, names: Record<string, LedgerEntry>): Promise<void> {
return this.book.setNames(accountId, names)
}
private async setPending(
accountId: string,
keyId: string,
updatedAt: number | null
): Promise<void> {
if (await this.book.setPending(accountId, keyId, updatedAt)) {
this.options.onWaiting?.()
}
}
/** The last link seen, so the reconnect check costs nothing while there's nothing to wait for. */
lastLink: AgentApiKeyCloudLink['kind'] | null = null
private async link(): Promise<AgentApiKeyCloudLink> {
let link: AgentApiKeyCloudLink
try {
link = await this.options.link()
} catch {
link = { kind: 'signed-out' }
}
this.lastLink = link.kind
if (link.kind === 'unreachable') {
this.options.onWaiting?.()
}
return link
}
private async connection(): Promise<AgentApiKeyCloudConnection | null> {
try {
return await this.options.connection()
} catch {
return null
}
const link = await this.link()
return link.kind === 'connected' ? link.connection : null
}
/** Saves waiting to reach the account, for any account (cheap: the ledger is cached). */
hasPending(): boolean {
return this.book.hasPending()
}
async state(keys: readonly AgentApiKeySummary[]): Promise<AgentApiKeysCloudState> {
const connection = await this.connection()
if (!connection) {
const link = await this.link()
if (link.kind === 'signed-out') {
return { signedIn: false, synced: [], managed: [] }
}
const names = (await this.ledger()).accounts[connection.accountId] ?? {}
const accountId = link.kind === 'connected' ? link.connection.accountId : link.accountId
const ledger = await this.ledger()
if (link.kind === 'unreachable' && !ledger.accounts[accountId]) {
// Never connected from here: nothing known to show, so this reads as signed out.
return { signedIn: false, synced: [], managed: [] }
}
if (link.kind === 'connected' && !ledger.accounts[accountId]) {
// Remember the account was connected, so a later offline spell shows its last-known state.
await this.setNames(accountId, {})
}
const names = (await this.ledger()).accounts[accountId] ?? {}
const pending = (await this.ledger()).pending?.[accountId] ?? {}
const managed = keys.filter((key) => namesWrittenBy(names, key.id).length > 0)
return {
signedIn: true,
...(link.kind === 'unreachable' ? { unreachable: true } : {}),
...pendingOf(keys, pending),
managed: managed.map((key) => key.id),
synced: managed
.filter((key) => {
@@ -180,8 +164,8 @@ export class AgentApiKeyCloudSync {
key: AgentApiKeySummary,
{ replace = false }: { replace?: boolean } = {}
): Promise<AgentApiKeyCloudOutcome> {
const connection = await this.connection()
if (!connection || key.hostScope.kind !== 'all') {
const link = await this.link()
if (link.kind === 'signed-out' || key.hostScope.kind !== 'all') {
return { kind: 'skipped' }
}
const failed = (error: CloudSecretsErrorCode): AgentApiKeyCloudOutcome => ({
@@ -192,6 +176,22 @@ export class AgentApiKeyCloudSync {
if (!agentApiKeyCloudEligible(key)) {
return failed('not_swappable')
}
if (link.kind === 'unreachable') {
// Saved while signed in: it goes to the account as soon as Orca is reachable again.
if ((await this.ledger()).accounts[link.accountId]) {
await this.setPending(link.accountId, key.id, key.updatedAt)
}
return failed('unavailable')
}
const { connection } = link
const retryLater = async (error: CloudSecretsErrorCode): Promise<AgentApiKeyCloudOutcome> => {
await this.setPending(
connection.accountId,
key.id,
TRANSIENT.has(error) ? key.updatedAt : null
)
return failed(error)
}
const owner = (await this.ledger()).accounts[connection.accountId]?.[key.envName]?.keyId
if (
!replace &&
@@ -199,7 +199,7 @@ export class AgentApiKeyCloudSync {
owner !== key.id &&
(await this.options.listKeys()).some((other) => other.id === owner)
) {
return failed('desktop_key_conflict')
return retryLater('desktop_key_conflict')
}
const value = await this.options.valueOf(key.id)
if (!value) {
@@ -212,7 +212,7 @@ export class AgentApiKeyCloudSync {
try {
await connection.client.put(PERSONAL, key.envName, value)
} catch (error) {
return failed(logged('save', cloudSecretsFailureCode(error)))
return retryLater(logged('save', cloudSecretsFailureCode(error)))
}
// A sign-in or account switch mid-write: the token may have been another account's, so this
// computer can't claim the variable (and must never later delete it on that claim).
@@ -222,9 +222,38 @@ export class AgentApiKeyCloudSync {
const names = { ...(await this.ledger()).accounts[connection.accountId] }
names[key.envName] = { keyId: key.id, keyUpdatedAt: key.updatedAt, syncedAt: this.now() }
await this.setNames(connection.accountId, names)
await this.setPending(connection.accountId, key.id, null)
return { kind: 'synced' }
}
/**
* Retries saves the user made while signed in that haven't reached the account. Only those keys,
* only at the version that was saved: a key edited, rescoped or removed since is dropped.
* Returns whether anything changed.
*/
async flushPending(): Promise<boolean> {
const connection = await this.connection()
const pending = connection ? (await this.ledger()).pending?.[connection.accountId] : undefined
if (!connection || !pending || Object.keys(pending).length === 0) {
return false
}
const keys = await this.options.listKeys()
let changed = false
for (const [keyId, updatedAt] of Object.entries(pending)) {
const key = keys.find((entry) => entry.id === keyId)
if (!key || key.updatedAt !== updatedAt || !agentApiKeyCloudEligible(key)) {
await this.setPending(connection.accountId, keyId, null)
continue
}
const outcome = await this.push(key)
changed ||= outcome.kind === 'synced'
if (outcome.kind === 'failed' && TRANSIENT.has(outcome.error)) {
break // Still unreachable: try again on the next check.
}
}
return changed
}
/** Records a write of `key` made elsewhere (the cloud workspace setup's "Save to your Orca account"). */
async record(key: AgentApiKeySummary): Promise<void> {
const connection = await this.connection()
@@ -288,6 +317,7 @@ export class AgentApiKeyCloudSync {
Object.entries(names).filter(([, entry]) => entry.keyId !== key.id)
)
await this.setNames(connection.accountId, rest)
await this.setPending(connection.accountId, key.id, null)
}
}
}
+30 -6
View File
@@ -1,4 +1,4 @@
import { ipcMain } from 'electron'
import { BrowserWindow, ipcMain, powerMonitor } from 'electron'
import { join } from 'node:path'
import {
selectAgentApiKeys,
@@ -9,10 +9,11 @@ import { AgentApiKeyStore } from './agent-api-key-store'
import { mutate, stateOf } from './agent-api-key-state'
import { installAgentApiKeyLaunchEnvResolver } from './agent-api-key-launch-env'
import { AgentApiKeyCloudSync } from './agent-api-key-cloud-sync'
import { agentApiKeyCloudLink, setAgentApiKeyCloudRecorder } from './agent-api-key-cloud-connection'
import {
agentApiKeyCloudConnection,
setAgentApiKeyCloudRecorder
} from './agent-api-key-cloud-connection'
createAgentApiKeyCloudRetry,
type AgentApiKeyCloudRetry
} from './agent-api-key-cloud-retry'
import { registerAgentApiKeyCloudHandlers, removeRequestOf } from './agent-api-key-cloud-ipc'
/** A host id no host-scoped key names, as in desktopKeyValueForCloud. */
@@ -20,14 +21,18 @@ const ANY_CLOUD_HOST = toRuntimeExecutionHostId('orca-cloud')
const CHANNELS = ['agentApiKeys:list', 'agentApiKeys:save', 'agentApiKeys:remove'] as const
let retry: AgentApiKeyCloudRetry | null = null
let wakeHooked = false
/** Values only ever travel renderer → main here; nothing returns them. */
export function registerAgentApiKeyHandlers(userDataPath: string): AgentApiKeyStore {
const store = new AgentApiKeyStore(join(userDataPath, 'agent-api-keys.json'))
const cloud = new AgentApiKeyCloudSync({
ledgerPath: join(userDataPath, 'agent-api-keys-cloud-ledger.json'),
connection: agentApiKeyCloudConnection,
link: agentApiKeyCloudLink,
valueOf: (id) => store.valueOf(id),
listKeys: () => store.list()
listKeys: () => store.list(),
onWaiting: () => retry?.kick()
})
// Saves, removals and imports touch the vault and the ledger; one at a time keeps them in step.
let queue: Promise<unknown> = Promise.resolve()
@@ -74,5 +79,24 @@ export function registerAgentApiKeyHandlers(userDataPath: string): AgentApiKeySt
})
)
registerAgentApiKeyCloudHandlers({ store, cloud, serial })
retry?.stop()
retry = createAgentApiKeyCloudRetry({
cloud,
serial,
notify: () => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send('agentApiKeys:changed')
}
}
}
})
// At start (a save from last session may be waiting) and after sleep, when the network returns.
retry.kick({ soon: true })
if (!wakeHooked) {
wakeHooked = true
powerMonitor.on('resume', () => retry?.kick({ soon: true }))
powerMonitor.on('unlock-screen', () => retry?.kick({ soon: true }))
}
return store
}
+7
View File
@@ -21,6 +21,8 @@ export type AgentApiKeysApi = {
/** Keys this computer already uses: names, sources and last fours only. */
scanThisComputer?: () => Promise<AgentApiKeysScanResult>
importFromThisComputer?: (names: string[]) => Promise<AgentApiKeysImportResult>
/** Main re-synced or reconnected: re-read `list`. Returns the unsubscribe. */
onChanged?: (listener: () => void) => () => void
}
export const agentApiKeysApi: AgentApiKeysApi = {
@@ -29,6 +31,11 @@ export const agentApiKeysApi: AgentApiKeysApi = {
remove: (request) => ipcRenderer.invoke('agentApiKeys:remove', request),
saveToAccount: (id) => ipcRenderer.invoke('agentApiKeys:saveToAccount', id),
scanThisComputer: () => ipcRenderer.invoke('agentApiKeys:scanThisComputer'),
onChanged: (listener) => {
const handler = (): void => listener()
ipcRenderer.on('agentApiKeys:changed', handler)
return () => ipcRenderer.removeListener('agentApiKeys:changed', handler)
},
importFromThisComputer: (names) =>
ipcRenderer.invoke('agentApiKeys:importFromThisComputer', names)
}
@@ -12,6 +12,7 @@ export function AgentApiKeyCloudLine({
envName,
state,
canSave,
offline = false,
failure,
onSaveToAccount
}: {
@@ -19,6 +20,8 @@ export function AgentApiKeyCloudLine({
state: AgentApiKeyCloudRowState
/** Every host and a variable the proxy swaps. */
canSave: boolean
/** Orca can't be reached: show the last-known state, without actions that would fail. */
offline?: boolean
failure: CloudSecretsErrorCode | undefined
onSaveToAccount: () => Promise<CloudSecretsErrorCode | null>
}): React.JSX.Element | null {
@@ -36,7 +39,7 @@ export function AgentApiKeyCloudLine({
setSaving(false)
}
// A failed account write replaces the status line: one line says what happened and offers retry.
if (failure && canSave && (state === 'local' || state === 'stale')) {
if (failure && canSave && !offline && (state === 'local' || state === 'stale')) {
const transport = failure === 'unavailable' || failure === 'timeout' || failure === 'unknown'
return (
<div className="pl-[22px]">
@@ -91,7 +94,7 @@ export function AgentApiKeyCloudLine({
)
: t('agentApiKeys.cloud.local', 'Only on this computer')}
</span>
{canSave && (state === 'local' || state === 'stale') ? (
{canSave && !offline && (state === 'local' || state === 'stale') ? (
<Button
type="button"
variant="outline"
@@ -168,12 +171,40 @@ export type AgentApiKeysNoticeState = { kind: 'kept' } | { kind: 'imported'; cou
/** One line above the list: the last removal or import, or what failed. */
export function AgentApiKeysNotice({
failure,
notice
notice,
unreachable = false
}: {
failure: string | null
notice: AgentApiKeysNoticeState
/** Signed in, but Orca can't be reached: the rows show the last-known state. */
unreachable?: boolean
}): React.JSX.Element | null {
const t = useTranslate()
const offline = unreachable ? (
<InlineError
tone="neutral"
density="compact"
title={t('agentApiKeys.cloud.unreachable', 'Can’t reach your Orca account right now')}
detail={t(
'agentApiKeys.cloud.unreachableDetail',
'Showing the last known state. Keys you save now go to your Orca account when Orca is back.'
)}
/>
) : null
const message = noticeMessage(failure, notice, t)
return offline || message ? (
<div className="space-y-2">
{offline}
{message}
</div>
) : null
}
function noticeMessage(
failure: string | null,
notice: AgentApiKeysNoticeState,
t: ReturnType<typeof useTranslate>
): React.JSX.Element | null {
if (failure) {
return <InlineError density="compact" title={failure} />
}
@@ -255,3 +255,28 @@ export const cloudStaleFailed = defineFixture({
/>
)
})
/** Removing a key this computer saved to the Orca account asks about that copy. */
export const removePrompt = defineFixture({
width: 720,
render: () => (
<AgentApiKeysPane model={model(SIGNED_IN)} hosts={HOSTS} initiallyRemoving="synced" />
)
})
/** Signed in, but Orca can't be reached: last-known state, no account actions. */
export const cloudUnreachable = defineFixture({
width: 720,
render: () => (
<AgentApiKeysPane
model={model(
{
...SIGNED_IN,
cloud: { signedIn: true, unreachable: true, synced: ['synced'], managed: ['synced'] }
},
{ cloudFailures: { local: 'unavailable' } }
)}
hosts={HOSTS}
/>
)
})
@@ -71,7 +71,8 @@ function KeyLine({
cloudFailure,
onEdit,
onRemove,
onSaveToAccount
onSaveToAccount,
initiallyConfirming = false
}: {
apiKey: AgentApiKeySummary
hosts: readonly AgentApiKeyHostChoice[]
@@ -81,9 +82,10 @@ function KeyLine({
onEdit: () => void
onRemove: (fromAccount: boolean) => Promise<void>
onSaveToAccount: () => Promise<CloudSecretsErrorCode | null>
initiallyConfirming?: boolean
}): React.JSX.Element {
const t = useTranslate()
const [confirming, setConfirming] = useState(false)
const [confirming, setConfirming] = useState(initiallyConfirming)
const asksAboutAccount = agentApiKeyRemoveAsksAboutAccount(apiKey, cloud)
return (
<li className="group space-y-1 rounded-md px-2 py-1.5 hover:bg-accent/40">
@@ -153,6 +155,7 @@ function KeyLine({
<AgentApiKeyCloudLine
envName={apiKey.envName}
state={agentApiKeyCloudRowState(apiKey, cloud)}
offline={cloud?.unreachable === true}
canSave={agentApiKeyCloudEligible(apiKey)}
failure={cloudFailure}
onSaveToAccount={onSaveToAccount}
@@ -166,7 +169,8 @@ export function AgentApiKeysPane({
model,
hosts,
initiallyEditing = null,
initialImport = null
initialImport = null,
initiallyRemoving = null
}: {
model: AgentApiKeysModel
hosts: readonly AgentApiKeyHostChoice[]
@@ -174,6 +178,8 @@ export function AgentApiKeysPane({
initiallyEditing?: Editing
/** Fixtures: open "Import from this Mac" in a given state. */
initialImport?: ImportScanState | null
/** Fixtures: a key whose remove prompt starts open. */
initiallyRemoving?: string | null
}): React.JSX.Element {
const t = useTranslate()
const [editing, setEditing] = useState<Editing>(initiallyEditing)
@@ -245,7 +251,11 @@ export function AgentApiKeysPane({
</div>
) : null}
<AgentApiKeysNotice failure={failure} notice={notice} />
<AgentApiKeysNotice
failure={failure}
notice={notice}
unreachable={model.state?.cloud?.unreachable === true}
/>
<SettingsGroup bodyClassName="px-0">
{agents.map((agent) => {
@@ -301,6 +311,7 @@ export function AgentApiKeysPane({
<KeyLine
key={apiKey.id}
apiKey={apiKey}
initiallyConfirming={initiallyRemoving === apiKey.id}
hosts={hosts}
canEdit={canEdit}
cloud={cloud}
@@ -56,8 +56,25 @@ export function useAgentApiKeys(api: AgentApiKeysApi | undefined): AgentApiKeysM
}
}
)
// Main retried a save or Orca became reachable again: show the fresh state.
const unsubscribe = api.onChanged?.(() => {
void api.list().then(
(next) => {
if (!cancelled) {
setState(next)
setCloudFailures((current) =>
Object.fromEntries(
Object.entries(current).filter(([id]) => !next.cloud?.synced.includes(id))
)
)
}
},
() => undefined
)
})
return () => {
cancelled = true
unsubscribe?.()
}
}, [api])
+3 -1
View File
@@ -27508,7 +27508,9 @@
"retry": "Try again",
"staleCopy": "Your Orca account has an older copy. Cloud workspaces still use it.",
"updateLabel": "Update {{name}} in your Orca account",
"update": "Update your Orca account"
"update": "Update your Orca account",
"unreachable": "Can’t reach your Orca account right now",
"unreachableDetail": "Showing the last known state. Keys you save now go to your Orca account when Orca is back."
},
"remove": {
"confirmLabel": "Remove {{name}}",
@@ -9,6 +9,10 @@ import type { AgentApiKeySummary, AgentApiKeysState } from './agent-api-key-cata
export type AgentApiKeysCloudState = {
/** Signed in to an Orca account that has Orca Cloud; otherwise keys stay on this computer only. */
signedIn: boolean
/** Signed in, but Orca can't be reached now: `synced`/`managed` are the last-known state. */
unreachable?: boolean
/** Keys saved while signed in that haven't reached the account yet; Orca retries them. */
pending?: string[]
/** Keys whose current value this computer saved to the Orca account. */
synced: string[]
/**