Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
feat(byoa): upgrade paired computer engines from their cards (#342)
Strelizia8bb309a27cf8
diff --git a/server/src/__integration__/computer-control-stream.test.ts b/server/src/__integration__/computer-control-stream.test.tsindex 81a0f9b..a8980c4 100644--- a/server/src/__integration__/computer-control-stream.test.ts+++ b/server/src/__integration__/computer-control-stream.test.ts@@ -7,8 +7,10 @@ import type { Response } from 'express'import {attachComputerControlStream,deliverEngineDetect,+ deliverEngineUpdate,} from '../agents/computer/control-bus.js'import { parseComputerControlEvent } from '../agents/computer/control-event.js'+import { getEngineUpdate, reportEngineUpdate, startEngineUpdate } from '../agents/computer/engine-update.js'import { teardownAll } from './_helpers.js'function makeFakeSseResponse(): Response & {@@ -30,8 +32,9 @@ function makeFakeSseResponse(): Response & {return fake}-function engineDetectFrame(writes: string[]): string | null {- const block = writes.join('').split('\n\n').find((value) => value.startsWith('event: engine.detect\n'))+/** The `data:` line of the first `event: <kind>` block written to the stream. */+function controlFrame(writes: string[], kind: string): string | null {+ const block = writes.join('').split('\n\n').find((value) => value.startsWith(`event: ${kind}\n`))const data = block?.split('\n').find((line) => line.startsWith('data: '))?.slice(6)return data ?? null}@@ -48,12 +51,54 @@ test('[integration] engine refresh publishes through Redis to the device SSE strassert.ok((await deliverEngineDetect(computerId)) >= 1)await new Promise((resolve) => setTimeout(resolve, 50))- const raw = engineDetectFrame(response.written)+ const raw = controlFrame(response.written, 'engine.detect')assert.ok(raw, 'the daemon stream should receive an engine.detect frame')assert.equal(parseComputerControlEvent(raw)?.kind, 'engine.detect')response.triggerClose()})+test('[integration] an engine update reaches the daemon with only the engine id', async () => {+ const computerId = `computer-${randomUUID()}`+ const response = makeFakeSseResponse()+ await attachComputerControlStream(computerId, response)++ const requestId = randomUUID()+ assert.ok((await deliverEngineUpdate(computerId, 'codex', requestId)) >= 1)+ await new Promise((resolve) => setTimeout(resolve, 50))++ const raw = controlFrame(response.written, 'engine.update')+ assert.ok(raw, 'the daemon stream should receive an engine.update frame')+ const event = parseComputerControlEvent(raw)+ assert.equal(event?.kind, 'engine.update')+ // The command is the daemon's to pick: only the id travels.+ assert.deepEqual(Object.keys(event ?? {}).sort(), ['at', 'engine', 'id', 'kind'])+ assert.equal(event?.kind === 'engine.update' ? event.engine : null, 'codex')+ assert.equal(event?.id, requestId)+ response.triggerClose()+})++test('[integration] an update is claimed once, scoped to its computer, and released on completion', async () => {+ const computerId = `computer-${randomUUID()}`+ const job = await startEngineUpdate(computerId, 'company', 'codex')+ assert.ok(job)+ assert.equal(await startEngineUpdate(computerId, 'company', 'claude'), null)+ assert.equal(await reportEngineUpdate('other-computer', job.id, 'running'), false)+ const claims = await Promise.all([+ reportEngineUpdate(computerId, job.id, 'running'),+ reportEngineUpdate(computerId, job.id, 'running'),+ ])+ assert.equal(claims.filter(Boolean).length, 1)+ assert.equal((await getEngineUpdate(job.id))?.status, 'running')+ assert.equal(await reportEngineUpdate(computerId, job.id, 'succeeded'), true)+ assert.equal((await getEngineUpdate(job.id))?.status, 'succeeded')+ assert.equal(await reportEngineUpdate(computerId, job.id, 'running'), false)+ const next = await startEngineUpdate(computerId, 'company', 'claude')+ assert.ok(next)+ assert.equal(await reportEngineUpdate(computerId, next.id, 'failed', 'fixture failure'), true)+ assert.equal((await getEngineUpdate(next.id))?.error, 'fixture failure')+ assert.ok(await startEngineUpdate(computerId, 'company', 'codex'))+})+test('[integration] revoked device streams close before receiving a refresh', async () => {const computerId = `computer-${randomUUID()}`const response = makeFakeSseResponse()@@ -63,7 +108,7 @@ test('[integration] revoked device streams close before receiving a refresh', asawait new Promise((resolve) => setTimeout(resolve, 50))assert.equal(response.closed, true)- assert.equal(engineDetectFrame(response.written), null)+ assert.equal(controlFrame(response.written, 'engine.detect'), null)})test('[integration] a disconnected stream reports no immediate receiver', async () => {diff --git a/server/src/__integration__/ws-doc-authorization.test.ts b/server/src/__integration__/ws-doc-authorization.test.tsindex 1024e31..3b051a7 100644--- a/server/src/__integration__/ws-doc-authorization.test.ts+++ b/server/src/__integration__/ws-doc-authorization.test.ts@@ -197,6 +197,12 @@ async function waitForClosed(harness: SocketHarness, timeoutMs = 2_000): Promiseasync function closeAllSockets(): Promise<void> {await Promise.allSettled([...openSockets].map(closeSocket))+ // Client close does not await the server's presence/outbox transaction.+ const deadline = Date.now() + OBSERVER_QUERY_TIMEOUT_MS+ while (wss.clients.size > 0 || pool.waitingCount > 0 || pool.idleCount !== pool.totalCount) {+ assert.ok(Date.now() < deadline, 'timed out waiting for WebSocket disconnect cleanup')+ await delay(10)+ }}async function seedDocumentFixture(viewerCount: number): Promise<DocumentFixture> {@@ -306,13 +312,14 @@ beforeEach(async () => {await resetAllTables()})-afterEach(() => {+afterEach(async () => {// rooms.ts intentionally keeps empty rooms for a 60s reconnect grace// period. Tests own these document ids, so evicting them here cancels those// timers and keeps this focused integration file from holding the runner// open for a full grace window.for (const documentId of fixtureDocumentIds) evictDocumentRoom(documentId)fixtureDocumentIds.clear()+ await closeAllSockets()})after(async () => {@@ -362,6 +369,39 @@ test('a contended peer is detached without discarding a valid peer', async () =>}})+test('socket cleanup waits for the disconnect presence transaction', async () => {+ const fixture = await seedDocumentFixture(1)+ const socket = await openSocket(ACTOR_ID)+ const barrier = new Client({ connectionString: databaseUrl() })+ const observer = new Client({ connectionString: databaseUrl() })+ await barrier.connect()+ await observer.connect()+ let cleanup: Promise<void> | undefined+ try {+ await barrier.query('BEGIN')+ await barrier.query('LOCK TABLE realtime_outbox IN ACCESS EXCLUSIVE MODE')+ await closeSocket(socket)+ await waitForBlockedQuery(observer, '%INSERT INTO realtime_outbox%')+ cleanup = closeAllSockets()+ await assert.rejects(+ within(cleanup, 'blocked disconnect cleanup', 50),+ /timed out waiting for blocked disconnect cleanup/,+ )+ await barrier.query('COMMIT')+ await cleanup+ const { rows } = await pool.query<{ status: string }>(+ 'SELECT status FROM participants WHERE id = $1 AND company_id = $2',+ [ACTOR_ID, fixture.companyId],+ )+ assert.equal(rows[0]?.status, 'resting')+ } finally {+ await barrier.query('ROLLBACK').catch(() => {})+ await barrier.end()+ await observer.end()+ await cleanup+ }+})+test('legacy subscribers retry contention without a forced disconnect', async () => {const fixture = await seedDocumentFixture(2)const actor = await openDocSocket(fixture.users[0]!, fixture.documentId)diff --git a/server/src/__tests__/agents-computer-control.test.ts b/server/src/__tests__/agents-computer-control.test.tsindex ff78b4a..e29fdd8 100644--- a/server/src/__tests__/agents-computer-control.test.ts+++ b/server/src/__tests__/agents-computer-control.test.ts@@ -24,6 +24,17 @@ test('malformed and unknown control events are ignored', () => {assert.equal(parseComputerControlEvent(JSON.stringify({ kind: 'daemon.stop', id: 'x', at: Date.now() })), null)})+test('an engine update carries only an id, never a command', () => {+ const event = parseComputerControlEvent(JSON.stringify({ kind: 'engine.update', id: 'u1', at: 1, engine: 'codex' }))+ assert.deepEqual(event, { kind: 'engine.update', id: 'u1', at: 1, engine: 'codex' })+ // Anything that is not a plain engine id is refused: the daemon picks the+ // command itself, so a payload cannot smuggle one in.+ for (const engine of ['', 'codex; rm -rf /', '../x', 'CODE X']) {+ assert.equal(parseComputerControlEvent(JSON.stringify({ kind: 'engine.update', id: 'u1', at: 1, engine })), null)+ }+ assert.equal(parseComputerControlEvent(JSON.stringify({ kind: 'engine.update', id: 'u1', at: 1 })), null)+})+test('an immediate forced refresh arriving during a scan gets a forced follow-up', async () => {let releaseFirst!: () => voidconst firstGate = new Promise<void>((resolve) => { releaseFirst = resolve })diff --git a/server/src/__tests__/agents-computer-engine-version.test.ts b/server/src/__tests__/agents-computer-engine-version.test.tsindex 7f91a4f..2a9f34c 100644--- a/server/src/__tests__/agents-computer-engine-version.test.ts+++ b/server/src/__tests__/agents-computer-engine-version.test.ts@@ -19,9 +19,9 @@ process.env.CUMORA_RUNTIME_CLIENT = 'http'process.env.OPENAI_API_KEY ??= 'test-key'const {- parseCliVersion, isCliOutdated, isCliVersionAtLeast, inferUpdateCommand,+ parseCliVersion, isCliOutdated, isCliVersionAtLeast, inferUpdateCommand, updateArgv,parseCursorAbout, parseGrokCheck, ENGINE_VERSION_SPECS, versionCommandInvocation,- probeLocalEngineVersionWithRetry,+ probeLocalEngineVersionWithRetry, runEngineUpdate,} = await import('../agents/computer/cli-version.js')const { sanitizeDetectedEngines } = await import('../agents/computer/registry.js')@@ -104,14 +104,14 @@ test('inferUpdateCommand prefers the vendor updater, then brew, then npm', () =>)// gemini has no self-updater: brew only when it actually came from brew.assert.equal(- inferUpdateCommand(ENGINE_VERSION_SPECS.gemini, '/opt/homebrew/bin/gemini'),+ inferUpdateCommand(ENGINE_VERSION_SPECS.gemini, '/opt/homebrew/Cellar/gemini-cli/1.0.0/bin/gemini'),'brew upgrade gemini-cli',)assert.equal(inferUpdateCommand(ENGINE_VERSION_SPECS.gemini, '/usr/local/bin/gemini'),'npm install -g @google/gemini-cli@latest',)- // codex is npm-only.+ // A regular npm Codex install keeps using npm.assert.equal(inferUpdateCommand(ENGINE_VERSION_SPECS.codex, '/usr/local/bin/codex'),'npm install -g @openai/codex@latest',@@ -125,6 +125,43 @@ test('inferUpdateCommand prefers the vendor updater, then brew, then npm', () =>)})+test('updateArgv runs the CLI\'s own updater through its resolved path', () => {+ // Windows: a bare `claude` is a .cmd shim only cmd.exe can start.+ assert.deepEqual(updateArgv('claude update', 'C:\\bin\\claude.cmd'), ['C:\\bin\\claude.cmd', 'update'])+ // Package managers are already runnable by name.+ assert.deepEqual(+ updateArgv('npm install -g @openai/codex@latest', '/usr/local/bin/codex'),+ ['npm', 'install', '-g', '@openai/codex@latest'],+ )+ assert.deepEqual(updateArgv('brew upgrade gemini-cli', '/opt/homebrew/bin/gemini'), ['brew', 'upgrade', 'gemini-cli'])+})++test('Codex updates the installation that supplies its binary', () => {+ const spec = ENGINE_VERSION_SPECS.codex+ assert.equal(inferUpdateCommand(spec, '/opt/homebrew/Caskroom/codex/0.162.1/codex'), 'brew upgrade codex')+ assert.equal(inferUpdateCommand(spec, '/usr/local/Caskroom/codex/0.160.0/codex'), 'brew upgrade codex')+ assert.equal(inferUpdateCommand(spec, '/home/test/.codex/packages/standalone/current/bin/codex'), 'codex update')+ assert.equal(inferUpdateCommand(spec, 'C:\\Users\\test\\.codex\\packages\\standalone\\current\\bin\\codex.exe'), 'codex update')+ assert.equal(inferUpdateCommand(spec, '/usr/local/bin/codex'), 'npm install -g @openai/codex@latest')+})++test('Homebrew-installed Node does not make an npm Codex install belong to brew', () => {+ const spec = ENGINE_VERSION_SPECS.codex+ for (const path of [+ '/opt/homebrew/lib/node_modules/@openai/codex/bin/codex.js',+ '/opt/homebrew/Cellar/node@22/22.0.0/lib/node_modules/@openai/codex/bin/codex.js',+ '/home/linuxbrew/.linuxbrew/lib/node_modules/@openai/codex/bin/codex.js',+ ]) {+ assert.equal(inferUpdateCommand(spec, path), 'npm install -g @openai/codex@latest')+ }+})++test('an upgrade refuses an engine removed since the last scan', async () => {+ assert.deepEqual(await runEngineUpdate('codex', null), {+ ok: false, command: null, error: 'codex is no longer installed',+ })+})+test('parseCursorAbout / parseGrokCheck read their vendor formats', () => {assert.equal(parseCursorAbout('Version 1.0.0\nLatest 1.2.0\n'), '1.2.0')assert.equal(parseCursorAbout('Version 1.0.0\n'), null)diff --git a/server/src/agents/computer/cli-version.ts b/server/src/agents/computer/cli-version.tsindex 1fec615..42c92af 100644--- a/server/src/agents/computer/cli-version.ts+++ b/server/src/agents/computer/cli-version.ts@@ -74,6 +74,8 @@ export interface EngineVersionSpec {brew?: string/** The vendor's own updater, preferred over brew/npm when it exists. */selfUpdate?: string+ /** Restrict a vendor updater to binaries owned by its standalone installer. */+ selfUpdatePath?: RegExp/** CLIs that report upstream themselves instead of via the npm registry. */latestVia?: 'cursor-about' | 'grok-check'}@@ -96,6 +98,9 @@ export const ENGINE_VERSION_SPECS: Record<string, EngineVersionSpec> = {codex: {versionArgs: ['--version'],npm: '@openai/codex',+ brew: 'codex',+ selfUpdate: 'codex update',+ selfUpdatePath: /[/\\]\.codex[/\\]packages[/\\]standalone[/\\]/i,},grok: {versionArgs: ['--version'],@@ -251,27 +256,23 @@ function realpathOf(binPath: string): string {}}-export function isHomebrewInstall(binPath: string, real: string): boolean {- const hay = `${binPath}\n${real}`- return /(^|[/\\])(Homebrew|homebrew|linuxbrew|Cellar)([/\\]|$)/i.test(hay)- || binPath.startsWith('/opt/homebrew/')-}--function npmUpdateCommand(spec: EngineVersionSpec): string | null {- if (!spec.npm) return null- const flags = spec.npmFlags ? `${spec.npmFlags} ` : ''- return `npm install -g ${flags}${spec.npm}@latest`+export function isHomebrewInstall(real: string, formula: string): boolean {+ // npm under Homebrew's Node belongs to npm, not the Node formula's keg.+ return real.match(/(?:^|[/\\])(?:Cellar|Caskroom)[/\\]([^/\\]+)[/\\]/i)?.[1] === formula}/** Prefer the CLI's own updater when it has one (`pi update`, `claude update`):* that is the path vendors document, and it behaves the same on Windows. Fall* back to brew only when the binary actually came from brew, else npm. */export function inferUpdateCommand(spec: EngineVersionSpec, binPath: string | null): string | null {- if (spec.selfUpdate) return spec.selfUpdate- if (spec.brew && binPath && isHomebrewInstall(binPath, realpathOf(binPath))) {+ if (spec.selfUpdate && (!spec.selfUpdatePath || (binPath && spec.selfUpdatePath.test(realpathOf(binPath))))) {+ return spec.selfUpdate+ }+ if (spec.brew && binPath && isHomebrewInstall(realpathOf(binPath), spec.brew)) {return `brew upgrade ${spec.brew}`}- return npmUpdateCommand(spec)+ if (!spec.npm) return null+ return `npm install -g ${spec.npmFlags ? `${spec.npmFlags} ` : ''}${spec.npm}@latest`}export function parseCursorAbout(text: string): string | null {@@ -294,6 +295,8 @@ export interface CommandOutput {stderr: string/** stdout first — the order every combined-text caller wants. */combined: string+ /** Exit code, or null when it never ran or was killed on timeout. */+ code?: number | null}/** Run a command and return its output, or empty strings on any failure. Never@@ -303,19 +306,19 @@ export interface CommandOutput {* prints its version on stdout and its warnings on stderr, and merging them* let an `npm warn EBADENGINE … node: '>=20.19.0'` line stand in for an* engine's version at the secure floor. */-function spawnCommand(cmd: string, args: string[], timeoutMs: number): Promise<CommandOutput> {+function spawnCommand(cmd: string, args: string[], timeoutMs: number, forceShell = false): Promise<CommandOutput> {return new Promise((resolve) => {let settled = falselet child: ReturnType<typeof spawn>try {- const invocation = versionCommandInvocation(cmd, args)+ const invocation = versionCommandInvocation(cmd, args, process.platform, undefined, forceShell)child = spawn(invocation.command, invocation.args, {stdio: ['ignore', 'pipe', 'pipe'],windowsHide: true,windowsVerbatimArguments: invocation.windowsVerbatimArguments === true,})} catch {- resolve({ stdout: '', stderr: '', combined: '' })+ resolve({ stdout: '', stderr: '', combined: '', code: null })return}// Kept apart, then joined stdout-first. A CLI prints its version on stdout@@ -327,10 +330,11 @@ function spawnCommand(cmd: string, args: string[], timeoutMs: number): Promise<Clet stderr = ''child.stdout?.on('data', (buf: Buffer) => { stdout += buf.toString('utf8') })child.stderr?.on('data', (buf: Buffer) => { stderr += buf.toString('utf8') })- const captured = (): CommandOutput => ({+ const captured = (code: number | null): CommandOutput => ({stdout: stdout.trim(),stderr: stderr.trim(),combined: `${stdout}\n${stderr}`.trim(),+ code,})const finish = (value: CommandOutput) => {if (settled) return@@ -339,11 +343,13 @@ function spawnCommand(cmd: string, args: string[], timeoutMs: number): Promise<Cresolve(value)}const timer = setTimeout(() => {+ // shortcut: kills the direct child only, so a wedged npm.cmd can outlive+ // this on Windows; upgrade to a process-tree kill if that shows up.try { child.kill() } catch { /* already gone */ }- finish(captured())+ finish(captured(null))}, timeoutMs)- child.on('error', () => finish({ stdout: '', stderr: '', combined: '' }))- child.on('close', () => finish(captured()))+ child.on('error', () => finish({ stdout: '', stderr: '', combined: '', code: null }))+ child.on('close', (code) => finish(captured(code)))})}@@ -432,3 +438,47 @@ export async function probeLocalEngineVersionWithRetry(}return null}++/** A global npm install or a brew upgrade downloads and unpacks: minutes, not+ * seconds, on a slow link. */+const UPDATE_TIMEOUT_MS = 10 * 60 * 1000++/** The update as argv. The CLI's own updater is named after the CLI (`claude+ * update`), and on Windows a bare `claude` is a `.cmd` shim only cmd.exe can+ * start — so the resolved path takes its place. npm and brew stay as they are:+ * they are package managers, not the CLI. */+export function updateArgv(command: string, binPath: string | null): string[] {+ const argv = command.split(/\s+/)+ if (binPath && argv[0] !== 'npm' && argv[0] !== 'brew') argv[0] = binPath+ return argv+}++/** Run one engine's update on this machine and say whether it worked.+ *+ * The command is derived here from the same spec that produced the command the+ * app shows, and only the engine *id* ever crosses the wire — a request can+ * pick which known updater runs, never what it is.+ *+ * shortcut: the daemon's own PATH is thinner than a login shell's, so an npm+ * that lives under a version manager may not be the one found here; upgrade to+ * resolving npm/brew from the CLI's own folder if a mis-install shows up. */+export async function runEngineUpdate(+ id: string,+ binPath: string | null,+): Promise<{ ok: boolean; command: string | null; error?: string }> {+ if (!binPath) return { ok: false, command: null, error: `${id} is no longer installed` }+ const spec = ENGINE_VERSION_SPECS[id]+ const command = spec ? inferUpdateCommand(spec, binPath) : null+ if (!command) return { ok: false, command, error: `no update command is known for ${id}` }+ // The cached "latest" is 6 hours old by design; after an update it would make+ // the engine read as still behind until it expires.+ latestCache.delete(id)+ const [file, ...args] = updateArgv(command, binPath)+ if (!file) return { ok: false, command, error: `no update command is known for ${id}` }+ // Through ComSpec on Windows: `npm` is a .cmd shim there, and CreateProcess+ // cannot start one directly.+ const out = await spawnCommand(file, args, UPDATE_TIMEOUT_MS, true)+ if (out.code === 0) return { ok: true, command }+ const detail = out.combined.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).pop()+ return { ok: false, command, error: detail || `exit ${out.code ?? 'timeout'}` }+}diff --git a/server/src/agents/computer/control-bus.ts b/server/src/agents/computer/control-bus.tsindex ce399b8..bb5a600 100644--- a/server/src/agents/computer/control-bus.ts+++ b/server/src/agents/computer/control-bus.ts@@ -77,6 +77,19 @@ export async function deliverEngineDetect(computerId: string): Promise<number> {return redis.publish(CH_COMPUTER_CONTROL_PREFIX + computerId, JSON.stringify(event))}+/** Publish an immediate engine-update nudge. A zero return means no daemon+ * stream is connected — and unlike a refresh there is no persisted fallback,+ * so the update simply did not start and the caller must say so. */+export async function deliverEngineUpdate(computerId: string, engine: string, id = `engine.update-${randomUUID()}`): Promise<number> {+ const event: ComputerControlEvent = {+ kind: 'engine.update',+ id,+ at: Date.now(),+ engine,+ }+ return redis.publish(CH_COMPUTER_CONTROL_PREFIX + computerId, JSON.stringify(event))+}+/** Attach the authenticated daemon's long-lived SSE control stream. */export async function attachComputerControlStream(computerId: string,diff --git a/server/src/agents/computer/control-event.ts b/server/src/agents/computer/control-event.tsindex a6bea4e..ccfc62c 100644--- a/server/src/agents/computer/control-event.ts+++ b/server/src/agents/computer/control-event.ts@@ -1,22 +1,25 @@/** Wire protocol shared by the API server and the standalone Computer daemon. */-export interface ComputerControlEvent {- kind: 'engine.detect'- id: string- at: number-}+export type ComputerControlEvent =+ | { kind: 'engine.detect'; id: string; at: number }+ /** `engine` names what to update; the daemon derives the command itself. */+ | { kind: 'engine.update'; id: string; at: number; engine: string }++const ENGINE_ID = /^[a-z][a-z0-9-]{0,31}$/export function parseComputerControlEvent(raw: string): ComputerControlEvent | null {try {- const value = JSON.parse(raw) as Partial<ComputerControlEvent> | null- if (- !value- || value.kind !== 'engine.detect'- || typeof value.id !== 'string'- || value.id.length === 0- || typeof value.at !== 'number'- || !Number.isFinite(value.at)- ) return null- return value as ComputerControlEvent+ const value = JSON.parse(raw) as { kind?: unknown; id?: unknown; at?: unknown; engine?: unknown } | null+ if (!value) return null+ const { kind, id, at } = value+ if (typeof id !== 'string' || !id || typeof at !== 'number' || !Number.isFinite(at)) return null+ if (kind === 'engine.detect') return { kind, id, at }+ const { engine } = value+ // Only a plain engine id crosses the wire: the daemon picks the command, so+ // a payload can never smuggle one in.+ if (kind === 'engine.update' && typeof engine === 'string' && ENGINE_ID.test(engine)) {+ return { kind, id, at, engine }+ }+ return null} catch {return null}diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex 8b3ceec..e5bc3c6 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -41,6 +41,7 @@ import { parseSseStream, wakeStreamWasStable } from '../runtime/sse-parse.js'import { type ProviderProfile, providerProfileEnv, providerProfileFingerprint, providerProfileMetadata, readProviderProfiles, redactProviderSecret } from './provider-profiles.js'import { modelIdOrNull } from './model-id.js'import { parseComputerControlEvent } from './control-event.js'+import { runEngineUpdate } from './cli-version.js'import {mergeWakeBackgroundBriefs,parseWakeData,@@ -1235,10 +1236,9 @@ export const CUMORA_SHIM = `#!/usr/bin/env node})().catch((e) => { console.error('cumora:', (e && e.message) || e); process.exit(70) })`-/** Restricted Claude does not receive Bash at all. This fixed MCP bridge gives- * it one structured tool that invokes the unprivileged file-IPC shim without- * a shell. Local-body flags are rejected because the MCP process itself is not- * inside Claude's Bash sandbox; callers pass body text as an argv item instead. */+/** The fixed MCP bridge keeps Cumora actions outside the model's command+ * sandbox without exposing daemon credentials. Local-body flags are rejected+ * because MCP is not sandboxed; callers pass body text as an argv item instead. */export const CUMORA_MCP_SHIM = `#!/usr/bin/env node'use strict'var cp = require('child_process')@@ -3750,6 +3750,46 @@ async function doRun(serverOverride?: string): Promise<void> {}let shuttingDown = false+ // Serialize control events; the server refuses a second pending update.+ //+ // shortcut: an update is not deferred until agents are idle, so on Windows it+ // can lose to a CLI that is mid-turn (EPERM); the card then still reads+ // outdated and the daemon log says why. Upgrade to an idle wait if that shows+ // up in practice.+ let updating = Promise.resolve()+ const updateEngine = (id: string, requestId: string): Promise<void> => {+ if (!ENGINE_IDS.includes(id as EngineId)) return updating+ updating = updating.then(async () => {+ const report = (status: 'running' | 'succeeded' | 'failed', error?: string) =>+ api(cfg.serverUrl, `/api/computers/me/engine-updates/${encodeURIComponent(requestId)}`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${cfg.deviceToken}` },+ body: JSON.stringify({ status, error }),+ })+ // Claim before starting: another stream/process must not run this twice.+ try { await report('running') }+ catch (err) {+ console.warn(`[computer] ${id} update was not accepted:`, err instanceof Error ? err.message : err)+ return+ }+ let result: { ok: boolean; error?: string }+ try {+ const entry = (await snapshotDetectedEngines([id as EngineId]))[0]+ const updated = await runEngineUpdate(id, entry?.path ?? null)+ result = updated+ if (!updated.ok) console.warn(`[computer] ${id} update failed (${updated.command}): ${updated.error}`)+ else console.log(`[computer] ${id} updated: ${updated.command}`)+ } catch (err) {+ result = { ok: false, error: err instanceof Error ? err.message : String(err) }+ console.warn(`[computer] ${id} update failed:`, result.error)+ }+ await rescanEngines(true).catch(() => {})+ await report(result.ok ? 'succeeded' : 'failed', result.error)+ }).catch((err) => {+ console.warn(`[computer] ${id} update result could not be reported:`, err instanceof Error ? err.message : err)+ })+ return updating+ }const controlStreamAbort = new AbortController()const controlStreamLoop = async (): Promise<void> => {let backoff = 1000@@ -3771,9 +3811,9 @@ async function doRun(serverOverride?: string): Promise<void> {void heartbeat()continue}- if (event.event === 'engine.detect' && event.data && parseComputerControlEvent(event.data)) {- void rescanEngines(true)- }+ const signal = event.data ? parseComputerControlEvent(event.data) : null+ if (signal?.kind === 'engine.detect') void rescanEngines(true)+ else if (signal?.kind === 'engine.update') void updateEngine(signal.engine, signal.id)}if (!shuttingDown) console.warn(`[computer] control-stream closed by server · retry in ${backoff}ms`)} catch (error) {diff --git a/server/src/agents/computer/engine-update.ts b/server/src/agents/computer/engine-update.tsnew file mode 100644index 0000000..9d1b41b--- /dev/null+++ b/server/src/agents/computer/engine-update.ts@@ -0,0 +1,65 @@+import { randomUUID } from 'node:crypto'+import { redis } from '../../redis.js'+import { ENGINE_UPDATE_TTL_SECONDS, type EngineUpdate } from '../../../../shared/engine-update.js'++interface EngineUpdateRecord extends EngineUpdate {+ companyId: string+ computerId: string+}++const jobKey = (id: string) => `cumora:engine-update:job:${id}`+const activeKey = (computerId: string) => `cumora:engine-update:active:${computerId}`++/** Reserve the whole computer: its daemon serializes global package updates. */+export async function startEngineUpdate(computerId: string, companyId: string, engine: string): Promise<EngineUpdateRecord | null> {+ const job: EngineUpdateRecord = { id: randomUUID(), computerId, companyId, engine, status: 'queued' }+ const reserved = await redis.set(activeKey(computerId), job.id, 'EX', ENGINE_UPDATE_TTL_SECONDS, 'NX')+ if (!reserved) return null+ try {+ await redis.set(jobKey(job.id), JSON.stringify(job), 'EX', ENGINE_UPDATE_TTL_SECONDS)+ } catch (error) {+ await releaseEngineUpdate(job).catch(() => {})+ throw error+ }+ return job+}++export async function getEngineUpdate(id: string): Promise<EngineUpdateRecord | null> {+ const raw = await redis.get(jobKey(id))+ return raw ? JSON.parse(raw) as EngineUpdateRecord : null+}++async function releaseEngineUpdate(job: EngineUpdateRecord): Promise<void> {+ await redis.eval(+ "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0",+ 1, activeKey(job.computerId), job.id,+ )+}++/** Only the owning daemon may claim/finish this request. Claiming twice is refused. */+export async function reportEngineUpdate(+ computerId: string,+ id: string,+ status: 'running' | 'succeeded' | 'failed',+ error?: string,+): Promise<boolean> {+ const job = await getEngineUpdate(id)+ if (!job || job.computerId !== computerId) return false+ if (status !== 'running' && job.status === status) return true+ const expected = status === 'running' ? 'queued' : 'running'+ // An undelivered request can fail before a daemon claims it.+ if (job.status !== expected && !(status === 'failed' && job.status === 'queued')) return false+ const next = { ...job, status, ...(error ? { error: error.replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 1000) } : {}) }+ const saved = await redis.eval(+ `local raw = redis.call('GET', KEYS[1])+ if not raw or raw ~= ARGV[1] then return 0 end+ redis.call('SET', KEYS[1], ARGV[2], 'EX', ARGV[3])+ if ARGV[4] ~= 'running' and redis.call('GET', KEYS[2]) == ARGV[5] then+ redis.call('DEL', KEYS[2])+ end+ return 1`,+ 2, jobKey(id), activeKey(computerId),+ JSON.stringify(job), JSON.stringify(next), String(ENGINE_UPDATE_TTL_SECONDS), status, id,+ )+ return Boolean(saved)+}diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex f05fa84..c236410 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -1180,6 +1180,27 @@ export async function requestEngineDetect(args: {return Boolean(rowCount)}+/** Authorize an app-initiated engine update. The computer must be this+ * company's, and the engine must be one it already reported as outdated — the+ * card is the only place the button exists, and a daemon should never be told+ * to run an updater for an engine nobody saw behind.+ *+ * Nothing but the engine id travels: the daemon derives the command from its+ * own spec, so a request can pick which known updater runs, never what it is. */+export async function canUpdateEngine(args: {+ computerId: string+ companyId: string+ engine: string+}): Promise<boolean> {+ if (!PAIRABLE_ENGINES.has(args.engine)) return false+ const { rows } = await pool.query<{ detected_engines: DetectedEngine[] }>(+ `SELECT COALESCE(detected_engines, '[]'::jsonb) AS detected_engines FROM computers+ WHERE id = $1 AND company_id = $2 AND kind <> 'cloud' AND revoked_at IS NULL LIMIT 1`,+ [args.computerId, args.companyId],+ )+ return (rows[0]?.detected_engines ?? []).some((e) => e.id === args.engine && e.outdated === true)+}+/** Daemon reports a fresh PATH snapshot. Keeps the current default first when* that engine is still installed. */export async function reportDetectedEngines(args: {diff --git a/server/src/api/router.ts b/server/src/api/router.tsindex 89e2be5..0a5492a 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -53,10 +53,11 @@ import {resolveDevice, mintAgentRuntimeToken, listAgentsForComputer,listComputers, revokeComputer, assignAgentToComputer, heartbeatComputer,cloudComputerId, issueRepairCode, requestEngineDetect, reportDetectedEngines,- setComputerDefaultEngine, updateEngineDefaults, getEngineDefaults,+ setComputerDefaultEngine, updateEngineDefaults, getEngineDefaults, canUpdateEngine,rotateCompanyPairingCode, PAIRABLE_ENGINES, type EngineId,} from '../agents/computer/registry.js'-import { attachComputerControlStream, deliverEngineDetect } from '../agents/computer/control-bus.js'+import { attachComputerControlStream, deliverEngineDetect, deliverEngineUpdate } from '../agents/computer/control-bus.js'+import { getEngineUpdate, reportEngineUpdate, startEngineUpdate } from '../agents/computer/engine-update.js'import { companyTier } from '../tier.js'import { createShippingRouter } from './shipping-router.js'import {@@ -1343,6 +1344,53 @@ api.post('/computers/:id/detect', safe(async (req, res) => {res.json({ ok: true, delivered })}))+// Run one engine's own updater on the paired machine — the button beside the+// "update available" badge. The daemon executes it and reports the new version+// through the usual rescan; a separate operation result acknowledges completion.+api.post('/computers/:id/engine-update', safe(async (req, res) => {+ const { companyId } = await requireCompanyRole(req)+ const computerId = String(req.params.id)+ const engine = typeof req.body?.engine === 'string' ? req.body.engine : ''+ if (!(await canUpdateEngine({ computerId, companyId, engine }))) {+ throw new HttpError(400, 'this computer has no outdated engine by that name')+ }+ const update = await startEngineUpdate(computerId, companyId, engine)+ if (!update) throw new HttpError(409, 'an engine update is already running on this computer')+ let delivered = false+ try {+ delivered = (await deliverEngineUpdate(computerId, engine, update.id)) > 0+ } catch (error) {+ console.warn('[computers] immediate engine update signal failed:', error instanceof Error ? error.message : String(error))+ }+ if (!delivered) {+ await reportEngineUpdate(computerId, update.id, 'failed', 'the computer has no connected control stream')+ throw new HttpError(409, 'that computer did not answer — it is offline. Run the command there instead.')+ }+ res.json({ ok: true, updateId: update.id })+}))++api.get('/computers/:id/engine-updates/:updateId', safe(async (req, res) => {+ const { companyId } = await requireCompany(req)+ const update = await getEngineUpdate(String(req.params.updateId))+ if (!update || update.companyId !== companyId || update.computerId !== String(req.params.id)) {+ throw new HttpError(404, 'engine update not found or expired')+ }+ res.json({ id: update.id, engine: update.engine, status: update.status, error: update.error })+}))++api.post('/computers/me/engine-updates/:updateId', safe(async (req, res) => {+ const { computerId } = await requireDevice(req)+ const status = req.body?.status+ if (status !== 'running' && status !== 'succeeded' && status !== 'failed') {+ throw new HttpError(400, 'invalid engine update status')+ }+ const error = typeof req.body?.error === 'string' ? req.body.error : undefined+ if (!(await reportEngineUpdate(computerId, String(req.params.updateId), status, error))) {+ throw new HttpError(409, 'engine update is no longer pending for this computer')+ }+ res.json({ ok: true })+}))+api.post('/computers/:id/default-engine', safe(async (req, res) => {const { companyId } = await requireCompanyRole(req)const engine = typeof req.body?.engine === 'string' ? req.body.engine : ''diff --git a/shared/engine-update.ts b/shared/engine-update.tsnew file mode 100644index 0000000..966c8f2--- /dev/null+++ b/shared/engine-update.ts@@ -0,0 +1,9 @@+export interface EngineUpdate {+ id: string+ engine: string+ status: 'queued' | 'running' | 'succeeded' | 'failed'+ error?: string+}++// Covers the updater's ten-minute timeout and the final engine rescan.+export const ENGINE_UPDATE_TTL_SECONDS = 15 * 60diff --git a/src/api/client.ts b/src/api/client.tsindex 729518d..0a44845 100644--- a/src/api/client.ts+++ b/src/api/client.ts@@ -1,4 +1,5 @@import { getActiveCompanyId, getAuthToken, useAuth } from '@/stores/auth'+import type { EngineUpdate } from '../../shared/engine-update'import type {BoardCardComment, BoardCardLookup, BoardSnapshot, BoardSummary,CalendarDispatch, CalendarEvent, CalendarEventKind, CalendarEventStatus,@@ -1004,6 +1005,13 @@ export const api = {requestComputerEngineDetect: (id: string) =>http<{ ok: boolean }>(`/computers/${encodeURIComponent(id)}/detect`, { method: 'POST', body: '{}' }),+ /** Start one update; its operation id distinguishes completion from scans. */+ updateComputerEngine: (id: string, engine: string) =>+ http<{ ok: boolean; updateId: string }>(+ `/computers/${encodeURIComponent(id)}/engine-update`,+ { method: 'POST', body: JSON.stringify({ engine }) }),+ getComputerEngineUpdate: (id: string, updateId: string) =>+ http<EngineUpdate>(`/computers/${encodeURIComponent(id)}/engine-updates/${encodeURIComponent(updateId)}`),/** Read per-engine default model settings for a computer. */getEngineDefaults: (id: string) =>http<{ defaults: EngineDefaultsMap }>(diff --git a/src/desktop/MeView.tsx b/src/desktop/MeView.tsxindex c3ca423..0f00691 100644--- a/src/desktop/MeView.tsx+++ b/src/desktop/MeView.tsx@@ -16,6 +16,7 @@ import { cn } from '@/lib/utils'import { api, getPairingServerOrigin, getServerOrigin, type ApiProject, type ApiQuotaSnapshot, type ApiQuotaWindow } from '@/api/client'import { ENGINE_BIN, ENGINE_LABEL, RUNNABLE_ENGINES, RUNNABLE_ENGINE_IDS, engineLabel, type RunnableEngineId } from '@/lib/engines'import type { Computer, EngineId } from '@/types'+import { ENGINE_UPDATE_TTL_SECONDS } from '../../shared/engine-update'// The tab's identity is its `key`; the label is a message key resolved at// render. Before this they were the same string, which would have made@@ -864,6 +865,8 @@ function ComputersTab() {const [repairCopied, setRepairCopied] = useState(false)const [busyId, setBusyId] = useState<string | null>(null)const [copiedCli, setCopiedCli] = useState<string | null>(null)+ // `computerId:engine` whose update the daemon is running right now.+ const [updatingCli, setUpdatingCli] = useState<string | null>(null)// Engine model defaults editing: which computer+engine is being editedconst [editingModel, setEditingModel] = useState<{ computerId: string; engineId: string } | null>(null)const [modelInput, setModelInput] = useState('')@@ -1011,6 +1014,32 @@ function ComputersTab() {}}+ /** Only this request's result ends the wait; ordinary scans are unrelated. */+ async function updateEngine(computerId: string, engineId: string) {+ const key = `${computerId}:${engineId}`+ setErr(null)+ setUpdatingCli(key)+ try {+ const { updateId } = await api.updateComputerEngine(computerId, engineId)+ const deadline = Date.now() + ENGINE_UPDATE_TTL_SECONDS * 1000+ while (Date.now() < deadline) {+ const update = await api.getComputerEngineUpdate(computerId, updateId)+ if (update.status === 'failed') throw new Error(update.error || t('me.agentsUpdateFailed'))+ if (update.status === 'succeeded') {+ await useComputers.getState().refresh()+ return+ }+ await new Promise((resolve) => window.setTimeout(resolve, 2000))+ await useComputers.getState().refresh()+ }+ setErr(t('me.agentsUpdateWaiting', { name: useComputers.getState().byId[computerId]?.name ?? '' }))+ } catch (e) {+ setErr(e instanceof Error ? e.message : String(e))+ } finally {+ setUpdatingCli(null)+ }+ }+return (<div className="space-y-6"><Section title={t('me.sectionComputers')}>@@ -1199,11 +1228,11 @@ function ComputersTab() {</div>{row.updateCommand && (<div className="mt-2">- {/* The card describes another machine, so say where the- command has to run — copying it here and pasting it- into a local shell would update the wrong computer. */}+ {/* The card describes another machine. The button+ runs the updater there; the command stays for+ anyone who would rather do it by hand. */}<div className="text-[11px] text-ink-400 mb-1">- {t('me.agentsRunOnComputer', { name: c.name })}+ {t('me.agentsUpdateHint', { name: c.name })}</div><div className="flex items-center gap-2"><pre className="flex-1 min-w-0 font-mono text-[11px] truncate bg-ink-900 text-cloud rounded-[8px] px-2 py-1.5 select-all">{row.updateCommand}</pre>@@ -1218,6 +1247,17 @@ function ComputersTab() {>{copiedCli === copyKey ? t('me.copied') : t('me.agentsCopyUpdate')}</button>+ {row.outdated && (+ <button+ type="button"+ disabled={updatingCli !== null}+ onClick={(e) => { e.stopPropagation(); void updateEngine(c.id, row.id) }}+ className="shrink-0 px-3 py-1.5 rounded-[8px] text-[12px] font-semibold text-white disabled:opacity-50"+ style={{ background: 'var(--skype)' }}+ >+ {updatingCli === copyKey ? t('me.agentsUpdating') : t('me.agentsUpdate')}+ </button>+ )}</div></div>)}diff --git a/src/locales/en.ts b/src/locales/en.tsindex 2dfe3dd..d62f841 100644--- a/src/locales/en.ts+++ b/src/locales/en.ts@@ -1360,7 +1360,11 @@ export const en = {'me.agentsCliCurrent': 'up to date','me.agentsCliUpdateAvailable': 'update available','me.agentsCopyUpdate': 'Copy command',- 'me.agentsRunOnComputer': 'Run this on {name}',+ 'me.agentsUpdate': 'Update',+ 'me.agentsUpdating': 'Updating…',+ 'me.agentsUpdateFailed': 'The engine update failed. You can retry or run the command on that computer.',+ 'me.agentsUpdateHint': 'Cumora can run this on {name} — or copy the command to do it there yourself.',+ 'me.agentsUpdateWaiting': 'No word from {name} yet — the install may still be running, or that computer runs an older Cumora that ignored the request. If the badge is still there, copy the command and run it there.','me.computerStatus.online': 'online','me.computerStatus.busy': 'busy','me.computerStatus.offline': 'offline',diff --git a/src/locales/zh-CN.ts b/src/locales/zh-CN.tsindex 386d438..b94f942 100644--- a/src/locales/zh-CN.ts+++ b/src/locales/zh-CN.ts@@ -1362,7 +1362,11 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {'me.agentsCliCurrent': '已是最新','me.agentsCliUpdateAvailable': '有更新','me.agentsCopyUpdate': '复制命令',- 'me.agentsRunOnComputer': '在 {name} 上运行此命令',+ 'me.agentsUpdate': '升级',+ 'me.agentsUpdating': '升级中…',+ 'me.agentsUpdateFailed': '引擎升级失败,可以重试或在那台电脑上手动运行命令。',+ 'me.agentsUpdateHint': '可以让 Cumora 直接在 {name} 上执行,也可以复制命令自己在那台机器上运行。',+ 'me.agentsUpdateWaiting': '{name} 还没有回报——可能还在安装,也可能那台电脑上的 Cumora 版本较旧、不认识这条指令。如果“有更新”还在,就复制命令自己运行。','me.computerStatus.online': '在线','me.computerStatus.busy': '忙碌','me.computerStatus.offline': '离线',diff --git a/tests/computer-engine-update.test.ts b/tests/computer-engine-update.test.tsnew file mode 100644index 0000000..d58086f--- /dev/null+++ b/tests/computer-engine-update.test.ts@@ -0,0 +1,62 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import vm from 'node:vm'+import { test } from 'node:test'+import ts from 'typescript'++// Execute the real click handler without adding a React test framework.+const source = ts.createSourceFile('MeView.tsx',+ readFileSync(new URL('../src/desktop/MeView.tsx', import.meta.url), 'utf8'),+ ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)+let handler = ''+function findHandler(node: ts.Node): void {+ if (ts.isFunctionDeclaration(node) && node.name?.text === 'updateEngine') handler = node.getText(source)+ ts.forEachChild(node, findHandler)+}+findHandler(source)+assert.ok(handler, 'the engine update click handler must exist')+const javascript = ts.transpileModule(handler, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText++for (const outcome of ['succeeded', 'failed'] as const) {+ test(`engine update ignores ordinary scans and waits for its own ${outcome} result`, async () => {+ let release!: () => void+ const pending = new Promise<void>((resolve) => { release = resolve })+ let status: 'running' | typeof outcome = 'running'+ let busy: string | null = null+ let error: string | null = null+ let reads = 0+ const computer = { name: 'Test computer', enginesDetectedAt: 'before' }+ const context = vm.createContext({+ ENGINE_UPDATE_TTL_SECONDS: 900,+ api: {+ updateComputerEngine: async () => ({ updateId: 'operation-1' }),+ getComputerEngineUpdate: async (id: string, updateId: string) => {+ assert.equal(id, 'computer')+ assert.equal(updateId, 'operation-1')+ reads+++ return { status, error: outcome === 'failed' ? 'fixture upgrade failed' : undefined }+ },+ },+ useComputers: { getState: () => ({+ byId: { computer },+ refresh: async () => { computer.enginesDetectedAt = 'unrelated-scan' },+ }) },+ setErr: (value: string | null) => { error = value },+ setUpdatingCli: (value: string | null) => { busy = value },+ window: { setTimeout: (callback: () => void) => { void pending.then(callback) } },+ Date, t: (key: string) => key,+ })+ vm.runInContext(`${javascript}; globalThis.runUpdate = updateEngine`, context)+ const running = context.runUpdate('computer', 'codex') as Promise<void>+ await new Promise<void>((resolve) => setImmediate(resolve))+ computer.enginesDetectedAt = 'manual-refresh'+ assert.equal(busy, 'computer:codex')+ assert.equal(error, null)+ status = outcome+ release()+ await running+ assert.equal(reads, 2)+ assert.equal(busy, null)+ assert.equal(error, outcome === 'failed' ? 'fixture upgrade failed' : null)+ })+}