The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
The command bar is an experiment: a process of its own, started at its first command (#937)
Deecdacbcd4f4ed
diff --git a/cli/e2e/commandBar.e2e.ts b/cli/e2e/commandBar.e2e.tsnew file mode 100644index 000000000..6fe6471fe--- /dev/null+++ b/cli/e2e/commandBar.e2e.ts@@ -0,0 +1,222 @@+/**+ * The command bar, an experiment in a process of its own (services/commandBar.ts), on the real daemon,+ * deciding through a fake JEV on this computer (`HARNESS_TEST_JEV_URL`) with a fixture key: never+ * OpenRouter. Both doors the apps use: the socket's `command_bar` (a window here, as a remote owner's app+ * asks over the relay) and the hook server's `/api/command-bar/*` (the desktop's own command bar).+ *+ * What moving it out of the core must keep: a decision answered as before; two at once per connection,+ * BUSY beyond; a connection that closes has its decisions aborted, which frees their slots. What being an+ * experiment adds: no process until its first request; its process killed in the middle of a decision costs+ * that decision alone, answered SERVICE_UNAVAILABLE at once at either door, while the core and every agent go+ * on; and a command bar that cannot start is refused plainly at both doors.+ */+import { mkdirSync } from 'node:fs'+import { createServer, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient, type Frame } from './harness/client.js'+import { IsolatedDaemon, until } from './harness/daemon.js'++/** The process the command bar runs in, as the master names it. */+const HOST = 'commandBar'++/** One call the command bar made to JEV: what it asked, whether its caller went, and its answer. */+interface Asked { questions: string[]; closed: boolean; answer(): void }++/** JEV's Decisions endpoint, as the command bar calls it, answering one candidate as a clear choice. */+class FakeJev {+ readonly asked: Asked[] = []+ /** Hold every answer until `answer()` is called on it: a decision in flight. */+ hold = false+ private server: Server | null = null+ url = ''++ async start(): Promise<void> {+ this.server = createServer((req, res) => {+ const chunks: Buffer[] = []+ req.on('data', (chunk: Buffer) => chunks.push(chunk))+ req.on('end', () => {+ // A caller that went before it finished sending (a process killed) leaves nothing to answer.+ let body: { questions: Record<string, unknown> }+ try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { res.destroy(); return }+ const questions = Object.keys(body.questions)+ const answers = questions.includes('fit')+ ? { fit: { type: 'noul', noul: 0.95 } }+ : {+ intent: { type: 'choice', choice: 'open', probabilities: { open: 0.97, none: 0.03 } },+ pick_open: { type: 'choice', choice: 'c0', probabilities: { c0: 0.97, none: 0.03 } },+ }+ const asked: Asked = {+ questions,+ closed: false,+ answer: () => { if (!res.writableEnded && !res.destroyed) res.end(JSON.stringify({ answers })) },+ }+ res.on('close', () => { if (!res.writableEnded) asked.closed = true })+ this.asked.push(asked)+ if (!this.hold) asked.answer()+ })+ })+ await new Promise<void>((resolve) => this.server!.listen(0, '127.0.0.1', resolve))+ this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/decisions`+ }++ release(): void {+ this.hold = false+ for (const asked of this.asked) asked.answer()+ }++ async stop(): Promise<void> {+ this.release()+ this.server?.closeAllConnections()+ await new Promise<void>((resolve) => this.server ? this.server.close(() => resolve()) : resolve())+ }+}++/** What the window's command bar sends: the prompt and the one action it could take. */+const REQUEST = { prompt: 'take me back to the release notes', candidates: [{ id: 'open:notes', kind: 'open', title: 'Release notes', detail: 'Writing the release notes' }] }+/** JEV's clear choice of it, as the command bar answers it. */+const DECIDED = { selectedId: 'open:notes', suggestions: [], fit: 0.95, autoExecute: true, reviewReason: null, provider: 'OpenRouter' }++/** The command bar's processes the master started, by the pids it logged: the last is the one running. */+const started = (d: IsolatedDaemon): number[] =>+ [...d.log().matchAll(new RegExp(`\\[harnessd\\] service ${HOST} started \\(pid (\\d+)\\)`, 'g'))].map((match) => Number(match[1]))++/** The hook server's door, as the desktop calls it. */+async function http(d: IsolatedDaemon, route: 'status' | 'resolve', body?: unknown, signal?: AbortSignal): Promise<{ status: number; body: Record<string, any> }> {+ const response = await fetch(`http://127.0.0.1:${d.port}/api/command-bar/${route}`, {+ method: route === 'status' ? 'GET' : 'POST',+ headers: { 'x-adapter-local': '1', 'content-type': 'application/json' },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ signal,+ })+ return { status: response.status, body: await response.json() as Record<string, any> }+}++/** A `command_bar` asked without waiting: its answer, when it comes. */+function ask(client: LocalClient): Promise<Record<string, any>> {+ return client.request('command_bar', { request: REQUEST }, 60_000)+}+const withoutTiming = (answer: Record<string, any>) => { const { elapsedMs: _elapsed, requestId: _id, ...rest } = answer; return rest }++describe('the command bar, an experiment in its own process', () => {+ let daemon: IsolatedDaemon | undefined+ let jev: FakeJev | undefined+ afterEach(async () => { await daemon?.close(); daemon = undefined; await jev?.stop(); jev = undefined })+ const fresh = async (env: Record<string, string> = {}) => {+ jev = new FakeJev()+ await jev.start()+ const d = await IsolatedDaemon.create({ env: {+ OPENROUTER_API_KEY: 'fixture-only-not-a-key',+ HARNESS_TEST_JEV_URL: jev.url,+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200',+ HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',+ ...env,+ } })+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })+ await d.start()+ return { d, jev }+ }++ it('has no process until its first command, then decides at both doors through it, as it did in the core', async () => {+ const { d } = await fresh()+ const client = await LocalClient.connect(d)+ await until('the services to connect', () => d.log().includes('[services] search connected') || null, 30_000, 200)+ expect(started(d), 'a command bar no one used').toEqual([])+ expect(withoutTiming(await ask(client))).toEqual(DECIDED)+ expect(started(d)).toHaveLength(1)+ const status = await http(d, 'status')+ expect(status).toEqual({ status: 200, body: { success: true, data: { configured: true, provider: 'OpenRouter', model: 'typesafe/jev-1.13' } } })+ const resolved = await http(d, 'resolve', REQUEST)+ expect(resolved.status).toBe(200)+ expect(withoutTiming(resolved.body.data)).toEqual(DECIDED)+ // What it refuses, it refuses in the same words.+ expect(withoutTiming(await client.request('command_bar', { request: { prompt: '' } }))).toEqual({ error: 'INVALID_REQUEST', detail: 'This command or its workspace context is too large or invalid.' })+ expect(await http(d, 'resolve', { prompt: '' })).toEqual({ status: 400, body: { success: false, error: { code: 'INVALID_REQUEST', message: 'This command or its workspace context is too large or invalid.' } } })+ expect(started(d)).toHaveLength(1)+ expect(d.coresStarted()).toBe(1)+ client.close()+ })++ it('takes two at once from a connection, BUSY beyond; a connection that closes has its own aborted, and their slots back', async () => {+ const { d, jev } = await fresh()+ const closing = await LocalClient.connect(d)+ const other = await LocalClient.connect(d)+ // On first, so that what follows is the command bar's limits and not its start.+ expect(withoutTiming(await ask(other))).toEqual(DECIDED)+ jev.hold = true+ const asked = jev.asked.length+ // Never answered: their connection closes first.+ void ask(closing).catch(() => null)+ void ask(closing).catch(() => null)+ await until('two decisions to reach JEV', () => jev.asked.length >= asked + 2 || null, 30_000, 100)+ // The connection's third, at once: the socket's own limit, in its own words.+ expect(withoutTiming(await ask(closing))).toEqual({ error: 'BUSY' })+ // Another connection, and the HTTP door: the command bar's two at once in all, in its words.+ expect(withoutTiming(await ask(other))).toEqual({ error: 'BUSY', detail: 'Too many commands at once. Try again in a moment.' })+ expect(await http(d, 'resolve', REQUEST)).toEqual({ status: 429, body: { success: false, error: { code: 'BUSY', message: 'Too many commands at once. Try again in a moment.' } } })+ expect(jev.asked).toHaveLength(asked + 2)+ closing.close()+ await until('JEV to see both of the closed connection\'s calls abandoned', () => jev.asked.slice(asked).every((one) => one.closed) || null, 30_000, 100)+ // Their slots are free again: the other connection decides.+ jev.hold = false+ expect(withoutTiming(await ask(other))).toEqual(DECIDED)+ // The HTTP door: a client that goes before its answer has its decision aborted the same way.+ jev.hold = true+ const before = jev.asked.length+ const going = new AbortController()+ const abandoned = http(d, 'resolve', REQUEST, going.signal).catch(() => null)+ await until('the HTTP decision to reach JEV', () => jev.asked.length > before || null, 30_000, 100)+ going.abort()+ await abandoned+ await until('JEV to see the HTTP decision abandoned', () => jev.asked.at(-1)!.closed || null, 30_000, 100)+ expect(d.coresStarted()).toBe(1)+ other.close()+ })++ it('killed in the middle of a decision: it fails at once at either door, cleanly, and the core and its agents go on', async () => {+ const { d, jev } = await fresh()+ const client = await LocalClient.connect(d)+ const cwd = join(d.projectsDir, 'command-bar-killed')+ mkdirSync(cwd, { recursive: true })+ const created = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)+ expect(created.error).toBeUndefined()+ const agentId = created.agent.id as string+ expect(withoutTiming(await ask(client))).toEqual(DECIDED)+ jev.hold = true+ const asked = jev.asked.length+ const overSocket = ask(client)+ const overHttp = http(d, 'resolve', REQUEST)+ await until('both decisions to reach JEV', () => jev.asked.length >= asked + 2 || null, 30_000, 100)+ const before = started(d)+ process.kill(before.at(-1)!, 'SIGKILL')+ expect(withoutTiming(await overSocket)).toEqual({ error: 'SERVICE_UNAVAILABLE', service: 'commandBar', retryable: true })+ expect(await overHttp).toEqual({ status: 503, body: { success: false, error: { code: 'UNAVAILABLE', message: 'The command bar is off or restarting. Choose an action below, or try again in a moment.' } } })+ // The agent was never the command bar's: it takes its turn as before.+ const ended = client.next((frame: Frame) => frame.type === 'turn_ended' && frame.agentId === agentId, 60_000, 'turn_ended')+ client.send('message', { agentId, content: 'while the command bar was gone' })+ await ended+ expect(d.coresStarted()).toBe(1)+ // The master brings it back, and it decides again.+ jev.release()+ const answer = await until('the command bar to decide again', async () => {+ const again = withoutTiming(await ask(client))+ return again.error ? null : again+ }, 60_000, 500)+ expect(answer).toEqual(DECIDED)+ expect(started(d).length).toBeGreaterThan(before.length)+ client.close()+ })++ it('one that cannot start is refused plainly at both doors, and nothing else notices', async () => {+ const { d } = await fresh({ HARNESSD_TEST_FAULTS: 'commandBar' })+ const client = await LocalClient.connect(d)+ const [overSocket, overHttp] = await Promise.all([ask(client), http(d, 'resolve', REQUEST)])+ expect(withoutTiming(overSocket)).toEqual({ error: 'SERVICE_UNAVAILABLE', service: 'commandBar', retryable: true })+ expect(overHttp).toEqual({ status: 503, body: { success: false, error: { code: 'UNAVAILABLE', message: 'The command bar is off or restarting. Choose an action below, or try again in a moment.' } } })+ expect((await client.request('agents_list', {})).error).toBeUndefined()+ expect(d.coresStarted()).toBe(1)+ client.close()+ }, 120_000)+})diff --git a/cli/e2e/compat.e2e.ts b/cli/e2e/compat.e2e.tsindex 608bddf85..93fef09f9 100644--- a/cli/e2e/compat.e2e.ts+++ b/cli/e2e/compat.e2e.ts@@ -17,7 +17,7 @@* `COMPAT_FROM=<that>/dist/cli.js npm run test:e2e -- compat`. `COMPAT_REPORT=<file>` writes both* sides' answers and every difference, for reading one by one.*/-import { execFileSync } from 'node:child_process'+import { execFileSync, spawn } from 'node:child_process'import { copyFileSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'import { hostname, tmpdir } from 'node:os'import { dirname, join } from 'node:path'@@ -123,6 +123,57 @@ function differences(a: unknown, b: unknown, path = ''): Array<{ path: string; freturn [{ path, from: a, to: b }]}+/**+ * The command bar (services/commandBar.ts; in the core before), at its two doors: the socket's `command_bar`+ * and the hook server's `/api/command-bar/*`. With no OpenRouter key: what reaches JEV is the same code on+ * either build, and no test may call it. The key is read from `ORI_CREDENTIALS_PATH`, a FIFO here, so that+ * a decision waits on it, in flight, for as long as nothing writes: what each door answers beyond its+ * limits, two at once per connection and two at once in all, is compared too.+ */+async function commandBar(d: IsolatedDaemon, answers: Answers, walk: (value: unknown) => unknown, client: LocalClient): Promise<void> {+ const request = { prompt: 'take me back to the release notes', candidates: [{ id: 'open:notes', kind: 'open', title: 'Release notes', detail: 'Writing the release notes' }] }+ const http = async (step: string, route: string, init: { method?: string; headers?: Record<string, string>; body?: string } = {}) => {+ const response = await fetch(`http://127.0.0.1:${d.port}/api/command-bar/${route}`, {+ method: init.method ?? (route === 'status' ? 'GET' : 'POST'),+ headers: init.headers ?? { 'x-adapter-local': '1', 'content-type': 'application/json' },+ ...(init.body === undefined ? {} : { body: init.body }),+ })+ answers[step] = walk({ status: response.status, body: await response.json() })+ }+ const ask = async (step: string, on: LocalClient, payload: Record<string, unknown>) => {+ answers[step] = walk(await on.request('command_bar', payload, 60_000).catch(() => ({ '<no reply>': true })))+ }+ // Refused before any key is read.+ await ask('command_bar with nothing', client, {})+ await ask('command_bar too large', client, { request: { prompt: 'x'.repeat(2_001), candidates: [] } })+ await http('command bar over HTTP without the native header', 'resolve', { headers: { 'content-type': 'application/json' }, body: '{}' })+ await http('command bar over HTTP from a browser', 'resolve', { headers: { 'x-adapter-local': '1', origin: 'https://example.com' }, body: '{}' })+ await http('command bar over HTTP, the wrong method', 'resolve', { method: 'GET' })+ await http('command bar over HTTP, not JSON', 'resolve', { body: '{' })+ await http('command bar over HTTP, too large', 'resolve', { body: 'x'.repeat(129_000) })+ await http('command bar over HTTP, invalid', 'resolve', { body: JSON.stringify({ prompt: '' }) })+ // Two decisions in flight on one connection, each waiting on the key: its third is refused by the+ // socket's limit, another connection's and the HTTP door's by the command bar's own.+ const other = await LocalClient.connect(d)+ const waiting = [client.request('command_bar', { request }, 60_000), client.request('command_bar', { request }, 60_000)]+ await new Promise((done) => setTimeout(done, 3_000))+ await ask('command_bar, a connection\'s third at once', client, { request })+ await ask('command_bar, another connection beyond two at once', other, { request })+ await http('command bar over HTTP beyond two at once', 'resolve', { body: JSON.stringify(request) })+ // The key, written for every reader from now on: none, so each decision ends there. A pause after each+ // write, or a reader still reading could be fed by the next writer forever and never reach its end.+ const writer = spawn('/bin/sh', ['-c', 'while :; do printf "{}" > "$1"; sleep 0.2; done', 'sh', d.env.ORI_CREDENTIALS_PATH!], { stdio: 'ignore' })+ try {+ answers['command_bar, the two that waited'] = walk(await Promise.all(waiting))+ await ask('command_bar', other, { request })+ await http('command bar status over HTTP', 'status')+ await http('command bar over HTTP', 'resolve', { body: JSON.stringify(request) })+ } finally {+ writer.kill()+ other.close()+ }+}+/** The scenario, on one daemon: what it answered, made comparable. */async function scenario(d: IsolatedDaemon): Promise<Answers> {const known = new Map<string, string>()@@ -249,6 +300,7 @@ async function scenario(d: IsolatedDaemon): Promise<Answers> {await ask('grid_fleet_run', 'grid_fleet_run', { args: ['--remote', 'ls', '--json'], timeoutMs: 5_000 })await ask('grid_fleet_cancel', 'grid_fleet_cancel', { commandId: 'compat-not-running' })await ask('agent_create on a grid model', 'agent_create', { engine: 'codex', cwd: cwd('codex'), gridModel: 'Qwen3-Coder-30B', gridName: 'mine', bypassPermission: true })+ await commandBar(d, answers, walk, client)await ask('a request nobody answers', 'compat_unknown_request')await ask('agent_create_status for no such creation', 'agent_create_status', { creationId: 'compat-no-such-creation' })@@ -320,9 +372,11 @@ describe.skipIf(!FROM)('what the apps see, compared with the released build', ()copyFileSync(join(dirname(FROM!), 'notify.mjs'), join(released, 'notify.mjs'))for (const dir of [build, released]) writeFileSync(join(dir, 'package.json'), '{"type":"module"}\n')+ // Where each side reads its OpenRouter key: a FIFO, so that a command bar decision can wait on it.+ const ori = (side: string) => { const path = join(scratch, `${side}.ori`); execFileSync('mkfifo', [path]); return path }for (const [side, options] of [- ['released', { scriptPath: join(released, 'cli.js'), env: { ADAPTER_CLI_DIR: released, HARNESS_GRID_BIN: NO_GRID } }],- ['this', { scriptPath: join(build, 'cli.js'), env: { ADAPTER_CLI_DIR: build, HARNESS_GRID_BIN: NO_GRID } }],+ ['released', { scriptPath: join(released, 'cli.js'), env: { ADAPTER_CLI_DIR: released, HARNESS_GRID_BIN: NO_GRID, ORI_CREDENTIALS_PATH: ori('released') } }],+ ['this', { scriptPath: join(build, 'cli.js'), env: { ADAPTER_CLI_DIR: build, HARNESS_GRID_BIN: NO_GRID, ORI_CREDENTIALS_PATH: ori('this') } }],] as const) {const d = await IsolatedDaemon.create(options)// tmux titles each new pane with the machine's name as it is then, and a daemon refuses that titlediff --git a/cli/scripts/command-bar-server.ts b/cli/scripts/command-bar-server.tsindex b7c036cd8..dedd3dfdf 100644--- a/cli/scripts/command-bar-server.ts+++ b/cli/scripts/command-bar-server.ts@@ -1,7 +1,11 @@/** Run the JEV experiment without replacing or restarting the user's Harness daemon. */import { createServer } from 'node:http'+import { COMMAND_BAR_REQUESTS, emptyPorts } from '../src/core/api.js'+import { createServiceHost } from '../src/core/serviceHost.js'import { commandBarService } from '../src/lib/commandBar.js'-import { handleCommandBarHttp } from '../src/lib/commandBarHttp.js'+import { handleCommandBarHttp, routedCommandBar } from '../src/lib/commandBarHttp.js'+import { processCoreApi } from '../src/services/processCoreApi.js'+import { startCommandBar } from '../src/services/commandBar.js'// Optional hidden input for a throwaway experiment. Never write credentials to disk or argv.if (process.argv.includes('--key-stdin')) {@@ -34,8 +38,13 @@ if (process.argv.includes('--key-stdin')) {const port = Number(process.env.HARNESS_JEV_PORT ?? '18476')if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error('HARNESS_JEV_PORT must be between 1024 and 65535')+// The command bar in this process, behind the same door the daemon gives it, with nothing of a daemon's.+const host = createServiceHost(emptyPorts())+host.serve('commandBar', startCommandBar, processCoreApi('', 'commandBar'), COMMAND_BAR_REQUESTS)+const door = routedCommandBar({ serviceRouter: host.route, onConnectionClosed: host.closeConnection })+const server = createServer((req, res) => {- void handleCommandBarHttp(req, res, commandBarService).then(handled => {+ void handleCommandBarHttp(req, res, door).then(handled => {if (!handled && !res.writableEnded) { res.writeHead(404); res.end() }}).catch(() => { if (!res.destroyed) { res.writeHead(500); res.end() } })})diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 907263a0b..da23636f1 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -287,7 +287,13 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {// runs in the viewers' process, beside the viewer servers it forwards to (services/viewers.ts), and with it// the headless browser capture the surfaces render with (sharing/viewer.ts), Share's other user. The core// keeps the frame types it gates (lib/viewerFrames.ts) and hands each frame on (core/viewerStreams.ts).-const CORE_CLOSURE_BUDGET = 75_070+//+// Then at 74,629 in 340, from 74,974 in 342: the command bar is an experiment, in a process of its own+// from its first request (services/commandBar.ts); its JEV decisions with their zod schemas+// (lib/commandBar.ts) and the OpenRouter key reader only it still loaded here (lib/openrouter.ts) leave.+// Its HTTP door stays, forwarding to it (lib/commandBarHttp.ts), and so does ⌘K's task delivery, the+// devices'.+const CORE_CLOSURE_BUDGET = 74_730/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */const EDGE: RegExp[] = [diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 9ed916f61..8d57e59f1 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -396,7 +396,34 @@ describe('agent_update opened: one "last used" for every app', () => {})describe('viewer forwarding authentication', () => {- it.each(['command_bar', 'route_task', 'route_send'])('requires a sealed owner session for %s', async type => {+ it('routes a sealed command_bar to the command bar with its connection, who asked, and nothing in the clear', async () => {+ const socket = relaySocket('token')+ const routed: Array<{ type: string; asker: unknown }> = []+ socket.serviceRouter = (type, _payload, asker, reply) => { routed.push({ type, asker }); reply({ selectedId: null }); return true }+ const ownerCommands = vi.spyOn(socket.ownerCommands, 'request')+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const role = vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')+ const clear = { type: 'command_bar', payload: { requestId: 'one', request: { prompt: 'fixture', candidates: [] } } }+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(clear)+ const sealedReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: 'command_bar_result', payload: { __e2e: 'sealed' } })+ await dispatchDown(socket, clear, 'remote')+ expect(routed).toEqual([])+ const sealed = { type: 'command_bar', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }+ // A device's session asks as no owner: the command bar refuses it (services/commandBar.ts).+ role.mockReturnValue('device')+ await dispatchDown(socket, sealed, 'remote')+ role.mockReturnValue('web')+ await dispatchDown(socket, sealed, 'remote')+ expect(routed).toEqual([+ { type: 'command_bar', asker: { local: false, owner: false, connection: 'remote', requestId: 'one' } },+ { type: 'command_bar', asker: { local: false, owner: true, connection: 'remote', requestId: 'one' } },+ ])+ expect(ownerCommands).not.toHaveBeenCalled()+ expect(sealedReply).toHaveBeenCalledWith('remote', 'command_bar_result', 'one', { selectedId: null })+ await socket.stop()+ })++ it.each(['route_task', 'route_send'])('requires a sealed owner session for %s', async type => {const socket = relaySocket('token'), internals = socket as anyconst request = vi.spyOn(socket.ownerCommands, 'request').mockResolvedValue({ ok: true })vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex dc0fd506a..561218523 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -33,7 +33,7 @@ import { engineInstallRecipe } from './lib/engineInstall.js'import { agentFrame, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'import { agentTokenUsage } from './lib/agentTokenUsage.js'import { terminalHandoffRequest } from './lib/terminalHandoff.js'-import { OwnerCommands, OWNER_COMMAND_TYPES } from './lib/ownerCommands.js'+import { OwnerCommands, OWNER_COMMAND_TYPES, ROUTE_COMMAND_TYPES } from './lib/ownerCommands.js'import { VIEWER_DOWN_TYPES } from './lib/viewerFrames.js'import type { TerminalStreamManager } from './lib/terminalStreamManager.js'import { encodeTerminalLocal, type TerminalBinaryClear } from './lib/terminalBinary.js'@@ -810,7 +810,7 @@ export class BackendSocket {// A paired owner can run the machine's orchestrator; observers and device sessions cannot.// Both requests and replies are encrypted, including project artifacts.- if (OWNER_COMMAND_TYPES.has(type)) {+ if (ROUTE_COMMAND_TYPES.has(type)) {if (!owner) { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }void this.ownerCommands.request(connId, type, payload).then(result => reply(type, requestId, result))returndiff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex f094612ec..09b5d529c 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -401,6 +401,9 @@ export const STORE_REQUESTS = ['dsh_list', 'dsh_install', 'dsh_update', 'dsh_remexport const USAGE_REQUESTS = ['usage_read'] as const/** The machine monitor (services/monitor.ts). */export const MONITOR_REQUESTS = ['machine_resources'] as const+/** The command bar (services/commandBar.ts), an experiment: the socket's `command_bar`, and the hook server's+ * `/api/command-bar/*`, which it asks as `command_bar_http`. */+export const COMMAND_BAR_REQUESTS = ['command_bar', 'command_bar_http'] as const/** The project and folder readers (services/projects.ts). */export const PROJECTS_REQUESTS = ['git_pull_request', 'git_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const/**@@ -478,6 +481,8 @@ export const EXPERIMENTS: Readonly<Record<string, { requests: readonly string[];collaboration: { requests: TEAMS_REQUESTS, state: ['teams'] },// Its invitations and links: a harness was shared from here.sharing: { requests: SHARE_REQUESTS, state: ['harness-shares.json', 'harness-collaboration.json'] },+ // Request-only: it keeps nothing, so it is on from its first request until the daemon stops.+ commandBar: { requests: COMMAND_BAR_REQUESTS, state: [] },}/** The core's calls into Share: an observer's frame as the relay handed it over, the relay gone (every observerdiff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 74c6df3ee..8536cc03a 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -119,7 +119,7 @@ import { createAgentUpdate } from './agents/update.js'import { createEngineHooks, installEngineHooks } from './engines/hooks.js'import { createCursorTaskHooks } from './engines/cursorTasks.js'import { databaseHistory } from './transcripts/databaseHistory.js'-import { createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'+import { COMMAND_BAR_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'import { createServiceHost, testFaults } from './serviceHost.js'import { startStalls } from './stall.js'import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'@@ -144,7 +144,7 @@ import { CORE_EXIT_STOP, CORE_EXIT_UPDATE, PROBE_COMMAND, PROBE_TIMEOUT_MS } froimport { localSocketPath, refuseServedDataFolder, type LocalSocketServer } from '../lib/localSocket.js'import { saveDaemonPort } from '../lib/daemonEndpoint.js'import { publishHookRoute } from '../lib/hookRoutes.js'-import { commandBarService } from '../lib/commandBar.js'+import { routedCommandBar } from '../lib/commandBarHttp.js'import { BackendSocket, isLocalClientId } from '../backendSocket.js'import { createGatewayLink, laneOf } from './gatewayLink.js'import { createWifiCore } from './wifi.js'@@ -1273,6 +1273,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// An agent's branch and pull request, a project's repository and preview, a folder's subfolders and a// media file from an agent's project (services/projects.ts): in this process, or in the edge host.if (!outOfProcess.has('projects')) serviceHost.serve('projects', inline!.startProjects, coreApi, PROJECTS_REQUESTS)+ if (!outOfProcess.has('commandBar')) serviceHost.serve('commandBar', inline!.startCommandBar, coreApi, COMMAND_BAR_REQUESTS)serviceHost.serve('shell', startShell, coreApi, SHELL_REQUESTS)// Models: grid access and its pin, the model pictures on agents' frames, the keystroke prewarm, where an// agent on a grid model sends its inference, and the models requests the apps send (services/models.ts):@@ -1709,7 +1710,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Which agent a hook belongs to, and what a SessionEnd means (core/engines/hooks.ts).const engineHooks = createEngineHooks({ tmuxBackend, agentReconciler, registry })const { server: hookServer, port: hookPort, localSocket } = await startHookServer(daemonPort(), {- onCommandBar: commandBarService,+ onCommandBar: routedCommandBar(backend),onAutonomousDeviceRequest: async (method, target, body) => {// Until the pieces below are built; after, a piece that could not be is refused by the requests// that need it, and the rest (list, status, revoke) answer from the pairings.diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.tsindex 33c839dca..86c2d4286 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -339,6 +339,9 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {// saved project or a request (core/api.ts `EXPERIMENTS`). Its projects' files and the frames of their// Directors; the agents it runs are the core's.orchestrator: { services: ['orchestrator'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },+ // The command bar (services/commandBarProcess.ts), an experiment: started at its first request. What it holds+ // is at most eight decisions in flight and one bounded JEV answer each (lib/commandBar.ts).+ commandBar: { services: ['commandBar'], heapLimitMiB: 128, rssLimitMiB: 384, onDemand: true },// Tab collaboration and teams, an experiment: the prompt scopes, a few drafts and fingerprints per agent, and// beside them the teams, their mailbox and the tab channels (services/collaborationProcess.ts), each on its// own link to the core. Started only once it is on (core/api.ts `EXPERIMENTS`).diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex b5992def6..92d9277ee 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -8,14 +8,26 @@ import { registry, type RegisteredSession } from './lib/registry.js'import { env } from './config/env.js'import { readHookCredential } from './lib/hookAuth.js'import { CommandBarService } from './lib/commandBar.js'+import { routedCommandBar } from './lib/commandBarHttp.js'+import { COMMAND_BAR_REQUESTS, emptyPorts } from './core/api.js'+import { createServiceHost } from './core/serviceHost.js'+import { startCommandBar, type Commands } from './services/commandBar.js'+import { fakeCore } from './testing/fakeCore.js'import { ENGINES } from './engines/types.js'let server: Server | null = nulldescribe('native command bar endpoints', () => {+ /** The command bar in this process, behind the core's door to it, as `HARNESSD_SERVICES=none` runs it. */+ const commandBar = (commands: Commands) => {+ const host = createServiceHost(emptyPorts(), { log: () => {} })+ host.serve('commandBar', (core) => startCommandBar(core, commands), fakeCore(), COMMAND_BAR_REQUESTS)+ return routedCommandBar({ serviceRouter: host.route, onConnectionClosed: host.closeConnection })+ }+it('requires a native local header and rejects browser origins before evaluating', async () => {const decide = vi.fn()- const { base } = await start({ onCommandBar: { status: vi.fn(), decide } })+ const { base } = await start({ onCommandBar: commandBar({ status: vi.fn(), decide }) })const attempts: Record<string, string>[] = [{}, { 'x-adapter-local': '1', origin: 'https://example.com' }]for (const headers of attempts) {const response = await fetch(`${base}/api/command-bar/resolve`, { method: 'POST', headers, body: '{}' })@@ -25,7 +37,7 @@ describe('native command bar endpoints', () => {})it('returns configuration without credentials and wraps useful setup errors', async () => {- const { base } = await start({ onCommandBar: new CommandBarService({ key: async () => null }) })+ const { base } = await start({ onCommandBar: commandBar(new CommandBarService({ key: async () => null })) })const headers = { 'x-adapter-local': '1', 'content-type': 'application/json' }const status = await fetch(`${base}/api/command-bar/status`, { headers })expect(await status.json()).toMatchObject({ success: true, data: { configured: false, provider: 'OpenRouter' } })@@ -559,8 +571,8 @@ describe('the daemon socket', () => {const dir = mkdtempSync('/tmp/hsock-')const socketPath = join(dir, 'daemon.sock')const onStatus = vi.fn(() => ({ ok: true }))- const commandBar = { status: vi.fn(async () => ({ configured: false })), decide: vi.fn() }- const started = await startHookServer(0, { onRegistered: vi.fn(), onSessionEnd: vi.fn(), onStatus, onCommandBar: commandBar as never }, { socketPath })+ const door = { ask: vi.fn(async () => ({ status: 200, body: { success: true, data: { configured: false } } })), closed: vi.fn() }+ const started = await startHookServer(0, { onRegistered: vi.fn(), onSessionEnd: vi.fn(), onStatus, onCommandBar: door }, { socketPath })server = started.servertry {expect(started.localSocket?.path).toBe(socketPath)diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 090f055f2..6badc3724 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -20,8 +20,7 @@ import { hookCredentialMatches, loadOrCreateHookCredential } from './lib/hookAutimport { routeStoreRequest, type StoreHandler } from './lib/storeProxy.js'import type { HookTerminalHint } from './lib/terminalTypes.js'import { ENGINES, type AgentEngine } from './engines/types.js'-import type { CommandBarService } from './lib/commandBar.js'-import { handleCommandBarHttp } from './lib/commandBarHttp.js'+import { handleCommandBarHttp, type CommandBarDoor } from './lib/commandBarHttp.js'import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'import { isTrustedLocal, listenLocalSocket, type LocalSocketServer } from './lib/localSocket.js'@@ -55,7 +54,7 @@ export interface PairOutcome {}export interface HookServerHandlers {- onCommandBar?: Pick<CommandBarService, 'status' | 'decide'>+ onCommandBar?: CommandBarDooronAutonomousDeviceRequest?: (method: string, target: string, body?: unknown) => Promise<{ status: number; body: unknown }>onRegistered: (diff --git a/cli/src/lib/commandBarHttp.spec.ts b/cli/src/lib/commandBarHttp.spec.tsnew file mode 100644index 000000000..5b331c6cd--- /dev/null+++ b/cli/src/lib/commandBarHttp.spec.ts@@ -0,0 +1,94 @@+import { createServer, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { handleCommandBarHttp, routedCommandBar, type CommandBarDoor } from './commandBarHttp.js'++let server: Server | null = null+afterEach(async () => {+ server?.closeAllConnections()+ await new Promise<void>((resolve) => server ? server.close(() => resolve()) : resolve())+ server = null+})++/** The door on a loopback server of its own, as the hook server and the experiment server serve it. */+async function serve(door?: CommandBarDoor): Promise<string> {+ server = createServer((req, res) => {+ void handleCommandBarHttp(req, res, door).then((handled) => { if (!handled) { res.writeHead(404); res.end() } })+ })+ await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/command-bar`+}+const LOCAL = { 'x-adapter-local': '1', 'content-type': 'application/json' }+const read = async (response: Response) => ({ status: response.status, body: await response.json() })++describe('the command bar\'s HTTP door', () => {+ it('asks the command bar on a connection of its own, and answers with what it said', async () => {+ const ask = vi.fn(async (payload: Record<string, unknown>, _connection: string) => payload.route === 'status'+ ? { status: 200, body: { success: true, data: { configured: false } } }+ : { status: 503, body: { success: false, error: { code: 'OPENROUTER_REQUIRED', message: 'Connect OpenRouter.' } } })+ const closed = vi.fn()+ const base = await serve({ ask, closed })+ expect(await read(await fetch(`${base}/status`, { headers: LOCAL }))).toEqual({ status: 200, body: { success: true, data: { configured: false } } })+ expect(await read(await fetch(`${base}/resolve`, { method: 'POST', headers: LOCAL, body: '{"prompt":"x"}' })))+ .toEqual({ status: 503, body: { success: false, error: { code: 'OPENROUTER_REQUIRED', message: 'Connect OpenRouter.' } } })+ expect(ask.mock.calls[0][0]).toEqual({ route: 'status' })+ expect(ask.mock.calls[1][0]).toEqual({ route: 'resolve', body: { prompt: 'x' } })+ // Each HTTP request its own connection, and none said to close once answered.+ expect(ask.mock.calls[0][1]).toMatch(/^http:/)+ expect(ask.mock.calls[1][1]).not.toBe(ask.mock.calls[0][1])+ expect(closed).not.toHaveBeenCalled()+ expect((await fetch(`${base.replace('/command-bar', '')}/other`)).status).toBe(404)+ })++ it('says plainly when the command bar is off or down, and answers anything else it cannot read as unavailable', async () => {+ const ask = vi.fn()+ .mockResolvedValueOnce({ error: 'SERVICE_UNAVAILABLE', service: 'commandBar', retryable: true })+ .mockResolvedValueOnce({ error: 'SERVICE_FAILED', service: 'commandBar' })+ .mockRejectedValueOnce(new Error('router gone'))+ const base = await serve({ ask, closed: vi.fn() })+ expect(await read(await fetch(`${base}/status`, { headers: LOCAL }))).toEqual({ status: 503, body: { success: false, error: { code: 'UNAVAILABLE', message: 'The command bar is off or restarting. Choose an action below, or try again in a moment.' } } })+ for (let i = 0; i < 2; i++) {+ expect(await read(await fetch(`${base}/status`, { headers: LOCAL }))).toEqual({ status: 502, body: { success: false, error: { code: 'UNAVAILABLE', message: 'Command bar unavailable.' } } })+ }+ })++ it('tells the command bar when a client goes before its answer', async () => {+ let answer!: (value: Record<string, unknown>) => void+ const ask = vi.fn((_payload: Record<string, unknown>, _connection: string) => new Promise<Record<string, unknown>>((resolve) => { answer = resolve }))+ const closed = vi.fn()+ const base = await serve({ ask, closed })+ const going = new AbortController()+ const request = fetch(`${base}/resolve`, { method: 'POST', headers: LOCAL, body: '{}', signal: going.signal }).catch(() => null)+ await vi.waitFor(() => expect(ask).toHaveBeenCalled())+ going.abort()+ await request+ await vi.waitFor(() => expect(closed).toHaveBeenCalledWith(ask.mock.calls[0][1]))+ // Its answer, when it comes, goes nowhere.+ answer({ status: 200, body: { success: true, data: {} } })+ })++ it('without a command bar, says to start one', async () => {+ const base = await serve()+ expect(await read(await fetch(`${base}/status`, { headers: LOCAL }))).toEqual({ status: 503, body: { success: false, error: { code: 'UNAVAILABLE', message: 'Start the command bar experiment server or updated daemon.' } } })+ })+})++describe('the daemon\'s door to the command bar', () => {+ it('routes as a process on this computer, on the door\'s connection, and is told when that connection closes', async () => {+ const socket = {+ serviceRouter: vi.fn((_type: string, _payload: Record<string, unknown>, _asker: unknown, reply: (result: Record<string, unknown>) => void) => { reply({ status: 200, body: {} }); return true }),+ onConnectionClosed: vi.fn(),+ }+ const door = routedCommandBar(socket)+ expect(await door.ask({ route: 'status' }, 'http:1')).toEqual({ status: 200, body: {} })+ expect(socket.serviceRouter).toHaveBeenCalledWith('command_bar_http', { route: 'status' }, { local: true, owner: true, connection: 'http:1' }, expect.any(Function))+ door.closed('http:1')+ expect(socket.onConnectionClosed).toHaveBeenCalledWith('http:1')+ // No service declares it (a core with none), or no router yet: unavailable, never a hang.+ socket.serviceRouter.mockReturnValueOnce(false)+ expect(await door.ask({ route: 'status' }, 'http:2')).toEqual({ error: 'SERVICE_UNAVAILABLE' })+ const bare = routedCommandBar({ serviceRouter: null, onConnectionClosed: null })+ expect(await bare.ask({ route: 'status' }, 'http:3')).toEqual({ error: 'SERVICE_UNAVAILABLE' })+ bare.closed('http:3')+ })+})diff --git a/cli/src/lib/commandBarHttp.ts b/cli/src/lib/commandBarHttp.tsindex ad67175a6..14270131f 100644--- a/cli/src/lib/commandBarHttp.ts+++ b/cli/src/lib/commandBarHttp.ts@@ -1,11 +1,33 @@+import { randomUUID } from 'node:crypto'import type { IncomingMessage, ServerResponse } from 'node:http'-import { CommandBarError, type CommandBarService } from './commandBar.js'+import type { Asker } from '../core/api.js'import { isTrustedLocal } from './localSocket.js'+/**+ * Where the HTTP door sends what it was asked: the command bar's `command_bar_http` request+ * (services/commandBar.ts), asked on `connection`, which `closed` says ended before its answer.+ */+export interface CommandBarDoor {+ ask(payload: Record<string, unknown>, connection: string): Promise<Record<string, unknown>>+ closed(connection: string): void+}++/** The daemon's door: through the core's service router, as a process on this computer, so that the+ * command bar is reached wherever it runs, and refused SERVICE_UNAVAILABLE while it is off or down. */+export function routedCommandBar(socket: {+ serviceRouter: ((type: string, payload: Record<string, unknown>, asker: Asker, reply: (result: Record<string, unknown>) => void) => boolean) | null+ onConnectionClosed: ((connId: string) => void) | null+}): CommandBarDoor {+ return {+ ask: (payload, connection) => new Promise((resolve) => {+ if (!socket.serviceRouter?.('command_bar_http', payload, { local: true, owner: true, connection }, resolve)) resolve({ error: 'SERVICE_UNAVAILABLE' })+ }),+ closed: (connection) => { socket.onConnectionClosed?.(connection) },+ }+}+/** Shared by the daemon and the isolated experiment server. Returns false for other routes. */-export async function handleCommandBarHttp(- req: IncomingMessage, res: ServerResponse, service?: Pick<CommandBarService, 'status' | 'decide'>,-): Promise<boolean> {+export async function handleCommandBarHttp(req: IncomingMessage, res: ServerResponse, door?: CommandBarDoor): Promise<boolean> {const path = (req.url ?? '').split('?')[0]if (path !== '/api/command-bar/status' && path !== '/api/command-bar/resolve') return falseconst json = (status: number, body: unknown) => {@@ -19,12 +41,14 @@ export async function handleCommandBarHttp(if (req.headers['x-adapter-local'] !== '1' || !loopback || req.headers.origin) {fail(403, 'FORBIDDEN', 'Native local client required.'); return true}- if (!service) { fail(503, 'UNAVAILABLE', 'Start the command bar experiment server or updated daemon.'); return true }+ if (!door) { fail(503, 'UNAVAILABLE', 'Start the command bar experiment server or updated daemon.'); return true }const isStatus = path.endsWith('/status')if (req.method !== (isStatus ? 'GET' : 'POST')) { fail(405, 'METHOD', 'Unsupported method.'); return true }- const abort = new AbortController()+ // Each request is a connection of its own to the command bar: a client that goes before its answer+ // has its decision aborted, as when the decision ran in this process.+ const connection = `http:${randomUUID()}`let uploadTimer: ReturnType<typeof setTimeout> | undefined- const onClose = () => { if (!res.writableEnded) abort.abort() }+ const onClose = () => { if (!res.writableEnded) door.closed(connection) }res.on('close', onClose)try {let body: unknown@@ -42,11 +66,13 @@ export async function handleCommandBarHttp(try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')) }catch { fail(400, 'INVALID_REQUEST', 'Invalid command request.'); return true }}- const data = isStatus ? await service.status() : await service.decide(body, abort.signal)- json(200, { success: true, data })- } catch (error) {- if (error instanceof CommandBarError) fail(error.status, error.code, error.message)+ const answer = await door.ask(isStatus ? { route: 'status' } : { route: 'resolve', body }, connection)+ if (typeof answer.status === 'number' && answer.body && typeof answer.body === 'object') json(answer.status, answer.body)+ // The command bar is an experiment, off or restarting: said plainly, never as a failure of the request.+ else if (answer.error === 'SERVICE_UNAVAILABLE') fail(503, 'UNAVAILABLE', 'The command bar is off or restarting. Choose an action below, or try again in a moment.')else fail(502, 'UNAVAILABLE', 'Command bar unavailable.')+ } catch {+ fail(502, 'UNAVAILABLE', 'Command bar unavailable.')} finally { clearTimeout(uploadTimer); res.off('close', onClose) }return true}diff --git a/cli/src/lib/ownerCommands.spec.ts b/cli/src/lib/ownerCommands.spec.tsindex 6b6b443e6..929b4ff05 100644--- a/cli/src/lib/ownerCommands.spec.ts+++ b/cli/src/lib/ownerCommands.spec.ts@@ -1,20 +1,16 @@import { describe, expect, it, vi } from 'vitest'import { OwnerCommands } from './ownerCommands.js'-import { CommandBarError } from './commandBar.js'describe('owner browser commands', () => {- it('uses the desktop decision service without executing its choice', async () => {- const decide = vi.fn().mockResolvedValue({ selectedId: 'send:a', autoExecute: false })- const commands = new OwnerCommands({ decide }), send = vi.fn()- commands.onRouteSend = send- const request = { prompt: 'Send a task', candidates: [] }- expect(await commands.request('one', 'command_bar', { request })).toEqual({ selectedId: 'send:a', autoExecute: false })- expect(decide).toHaveBeenCalledWith(request, expect.any(AbortSignal))- expect(send).not.toHaveBeenCalled()+ it('leaves the command bar to its own service', async () => {+ const commands = new OwnerCommands()+ commands.onRouteTask = vi.fn()+ expect(await commands.request('one', 'command_bar', { request: { prompt: 'Send a task', candidates: [] } })).toEqual({ error: 'UNSUPPORTED' })+ expect(commands.onRouteTask).not.toHaveBeenCalled()})it('validates task delivery and preserves the daemon refusal', async () => {- const commands = new OwnerCommands({ decide: vi.fn() })+ const commands = new OwnerCommands()const send = vi.fn().mockReturnValue({ ok: false, machine: 'fixture', reason: 'offline' })commands.onRouteSend = sendfor (const payload of [{}, { agentId: 'a', text: '' }, { agentId: 'a', text: 'x'.repeat(16_001) }]) {@@ -24,22 +20,25 @@ describe('owner browser commands', () => {expect(await commands.request('one', 'route_send', { agentId: 'a', text: 'hello' })).toEqual({ ok: false, machine: 'fixture', reason: 'offline' })expect(send).toHaveBeenCalledWith('a', 'hello')expect(await commands.request('one', 'route_task', { text: 'hello' })).toEqual({ error: 'UNSUPPORTED' })+ commands.onRouteSend = undefined+ expect(await commands.request('one', 'route_send', { agentId: 'a', text: 'hello' })).toEqual({ error: 'UNSUPPORTED' })})- it('bounds pending decisions and aborts only the disconnecting connection', async () => {- const decide = vi.fn().mockImplementation((_raw, signal: AbortSignal) => new Promise((_, reject) => {- signal.addEventListener('abort', () => reject(new CommandBarError(499, 'CANCELLED', 'Command cancelled.')))- }))- const commands = new OwnerCommands({ decide })- const one = commands.request('one', 'command_bar', { request: {} })- const two = commands.request('one', 'command_bar', { request: {} })- const other = commands.request('other', 'command_bar', { request: {} })- expect(await commands.request('one', 'command_bar', { request: {} })).toEqual({ error: 'BUSY' })+ it('bounds pending deliveries per connection and in all, and answers a delivery that throws', async () => {+ const answers: Array<(value: never) => void> = []+ const commands = new OwnerCommands()+ commands.onRouteTask = vi.fn(() => new Promise<never>((resolve) => { answers.push(resolve) }))+ const one = commands.request('one', 'route_task', { text: 'a' })+ const two = commands.request('one', 'route_task', { text: 'b' })+ expect(await commands.request('one', 'route_task', { text: 'c' })).toEqual({ error: 'BUSY' })+ const others = Array.from({ length: 6 }, (_, i) => commands.request(`other-${i}`, 'route_task', { text: 'd' }))+ expect(await commands.request('last', 'route_task', { text: 'e' })).toEqual({ error: 'BUSY' })commands.closeConnection('one')- expect(await one).toMatchObject({ error: 'CANCELLED' })- expect(await two).toMatchObject({ error: 'CANCELLED' })- expect(decide.mock.calls[2][1].aborted).toBe(false)commands.closeAll()- expect(await other).toMatchObject({ error: 'CANCELLED' })+ for (const answer of answers) answer({ agentId: 'a' } as never)+ expect(await one).toEqual({ agentId: 'a' })+ await Promise.all([two, ...others])+ commands.onRouteTask = vi.fn(async () => { throw new Error('router down') })+ expect(await commands.request('one', 'route_task', { text: 'a' })).toEqual({ error: 'COMMAND_UNAVAILABLE', detail: 'This machine could not complete the command. Try again.' })})})diff --git a/cli/src/lib/ownerCommands.ts b/cli/src/lib/ownerCommands.tsindex 41cc020fe..7d96079f2 100644--- a/cli/src/lib/ownerCommands.ts+++ b/cli/src/lib/ownerCommands.ts@@ -1,23 +1,21 @@-import { CommandBarError, commandBarService, type CommandBarService } from './commandBar.js'import type { LocalWsServerOptions } from '../localWsServer.js'-import { OWNER_COMMAND_TYPES } from './relayFrames.js'-export { OWNER_COMMAND_TYPES } from './relayFrames.js'+import { ROUTE_COMMAND_TYPES } from './relayFrames.js'+export { OWNER_COMMAND_TYPES, ROUTE_COMMAND_TYPES } from './relayFrames.js'-/** The same decisions and task delivery as the desktop, behind the paired-owner boundary.- * A decision never executes an action. The client still reviews and commits the selected action. */+/** ⌘K's task delivery from a remote owner's app, as the desktop does it, behind the paired-owner boundary.+ * The command bar's decisions, which never execute an action, are a service of their own+ * (services/commandBar.ts); the client still reviews and commits the selected action. */export class OwnerCommands {onRouteTask?: LocalWsServerOptions['onRouteTask']onRouteSend?: LocalWsServerOptions['onRouteSend']private readonly pending = new Map<AbortController, string>()- constructor(private readonly commands: Pick<CommandBarService, 'decide'> = commandBarService) {}async request(connId: string, type: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {- if (!OWNER_COMMAND_TYPES.has(type)) return { error: 'UNSUPPORTED' }+ if (!ROUTE_COMMAND_TYPES.has(type)) return { error: 'UNSUPPORTED' }if (this.pending.size >= 8 || [...this.pending.values()].filter(id => id === connId).length >= 2) return { error: 'BUSY' }const abort = new AbortController()this.pending.set(abort, connId)try {- if (type === 'command_bar') return await this.commands.decide(payload.request, abort.signal)const text = typeof payload.text === 'string' ? payload.text.trim() : ''if (!text || text.length > 16_000) return { error: 'INVALID_REQUEST' }if (type === 'route_task') {@@ -28,10 +26,8 @@ export class OwnerCommands {if (typeof agentId !== 'string' || !agentId.length || agentId.length > 160) return { error: 'INVALID_REQUEST' }if (!this.onRouteSend) return { error: 'UNSUPPORTED' }return await this.onRouteSend(agentId, text)- } catch (error) {- return error instanceof CommandBarError- ? { error: error.code, detail: error.message }- : { error: 'COMMAND_UNAVAILABLE', detail: 'This machine could not complete the command. Try again.' }+ } catch {+ return { error: 'COMMAND_UNAVAILABLE', detail: 'This machine could not complete the command. Try again.' }} finally { this.pending.delete(abort) }}diff --git a/cli/src/lib/relayFrames.ts b/cli/src/lib/relayFrames.tsindex 8389c7176..14676f815 100644--- a/cli/src/lib/relayFrames.ts+++ b/cli/src/lib/relayFrames.ts@@ -70,8 +70,10 @@ export class RelayConnectError extends Error {*/export const DAEMON_LOCAL_ONLY_TYPES: ReadonlySet<string> = new Set(['device_key_added', 'device_key_removed', 'device_conflict', 'device_keys_changed'])-/** The owner's commands from the window's command bar and ⌘K, sealed and the owner's only (lib/ownerCommands.ts). */-export const OWNER_COMMAND_TYPES = new Set(['command_bar', 'route_task', 'route_send'])+/** ⌘K's task delivery, which the devices answer (lib/ownerCommands.ts). */+export const ROUTE_COMMAND_TYPES: ReadonlySet<string> = new Set(['route_task', 'route_send'])+/** The owner's commands from the window's command bar (services/commandBar.ts) and ⌘K, sealed and the owner's only. */+export const OWNER_COMMAND_TYPES = new Set(['command_bar', ...ROUTE_COMMAND_TYPES])/** The pair brain, machine to machine (daemons/BRAIN.md): retired, and refused (lib/e2ee/applicationFrames.ts). */export const PAIR_REQUESTS = new Set(['pair_watch', 'pair_journal', 'pair_read', 'pair_list','pair_answer', 'pair_send', 'pair_stop', 'pair_start', 'pair_pause', 'pair_resume'])diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.tsindex 639648586..5f298ca73 100644--- a/cli/src/serviceProcess.ts+++ b/cli/src/serviceProcess.ts@@ -36,6 +36,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M['collaboration', async () => (await import('./services/collaborationProcess.js')).runCollaborationService],['sharing', async () => (await import('./services/sharingProcess.js')).runSharingService],['orchestrator', async () => (await import('./services/orchestratorProcess.js')).runOrchestratorService],+ ['commandBar', async () => (await import('./services/commandBarProcess.js')).runCommandBarService],['gateway', async () => (await import('./gateway/gatewayProcess.js')).runGatewayService],['models', async () => (await import('./services/modelsProcess.js')).runModelsService],['devices', async () => (await import('./services/devicesProcess.js')).runDevicesService],diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.mdindex 0c8ed42d6..2539ffcac 100644--- a/cli/src/services/AGENTS.md+++ b/cli/src/services/AGENTS.md@@ -140,9 +140,9 @@ way back).## Experiments-An experiment (the orchestrator, Tab collaboration, Share) is a service that costs nothing until it is-on: its own process, which the master starts only when the core asks for it (`want`), when one of its-requests arrives or, as the core starts, when its saved state is in the data folder. Off, nothing of it runs or+An experiment (the orchestrator, Tab collaboration, Share, the command bar) is a service that costs nothing+until it is on: its own process, which the master starts only when the core asks for it (`want`), when one of+its requests arrives or, as the core starts, when its saved state is in the data folder. Off, nothing of it runs oris loaded anywhere; one failing costs its own process and nothing else. `e2e/experiments.e2e.ts` proves it:off, on by request, on by saved state, killed, hung and crashing on every start.diff --git a/cli/src/services/commandBar.spec.ts b/cli/src/services/commandBar.spec.tsnew file mode 100644index 000000000..e5fdc99f5--- /dev/null+++ b/cli/src/services/commandBar.spec.ts@@ -0,0 +1,130 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { COMMAND_BAR_REQUESTS, emptyPorts, type Asker } from '../core/api.js'+import { createServiceHost } from '../core/serviceHost.js'+import { CommandBarError, CommandBarService, commandBarService } from '../lib/commandBar.js'+import { fakeCore } from '../testing/fakeCore.js'+import { commandsFor, startCommandBar, type Commands } from './commandBar.js'++const OWNER: Asker = { local: false, owner: true, connection: 'web-1' }+const REQUEST = { prompt: 'open the release notes', candidates: [] }++/** A decision that waits until its signal aborts, then fails as the real one does when its asker goes. */+function waitingDecide() {+ const started: AbortSignal[] = []+ const decide = vi.fn((_raw: unknown, signal?: AbortSignal) => new Promise<Record<string, unknown>>((_resolve, reject) => {+ started.push(signal!)+ signal!.addEventListener('abort', () => reject(new CommandBarError(499, 'TIMEOUT', 'Command cancelled.')))+ }))+ return { decide, started, status: vi.fn() }+}++/** The command bar behind the core's host, in this process: its requests routed with their connection. */+function hosted(commands: Commands) {+ const host = createServiceHost(emptyPorts(), { log: () => {} })+ host.serve('commandBar', (core) => startCommandBar(core, commands), fakeCore(), COMMAND_BAR_REQUESTS)+ const answers: Array<Record<string, unknown>> = []+ const ask = (connection: string | undefined, owner = true) => {+ const answered = new Promise<Record<string, unknown>>((resolve) => {+ host.route('command_bar', { request: REQUEST }, { local: false, owner, ...(connection ? { connection } : {}) }, resolve)+ })+ void answered.then((answer) => { answers.push(answer) })+ return answered+ }+ return { host, ask, answers }+}++describe('the command bar', () => {+ afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })++ it('decides for the owner with the answer the socket gave, and refuses anyone else before deciding', async () => {+ const decide = vi.fn(async () => ({ selectedId: 'send:a', autoExecute: false }))+ const { ask } = hosted({ status: vi.fn(), decide })+ expect(await ask('web-1')).toEqual({ selectedId: 'send:a', autoExecute: false })+ expect(decide).toHaveBeenCalledWith(REQUEST, expect.any(AbortSignal))+ expect(await ask('device-1', false)).toEqual({ error: 'OWNER_REQUIRED' })+ expect(decide).toHaveBeenCalledOnce()+ })++ it('takes two at once from a connection and eight in all, and answers BUSY beyond, as the socket did', async () => {+ const commands = waitingDecide()+ const { host, ask, answers } = hosted(commands)+ const mine = [ask('one'), ask('one')]+ expect(await ask('one')).toEqual({ error: 'BUSY' })+ // Requests with no connection (a core from before connections) are each their own.+ const others = [ask('two'), ask('two'), ask(undefined), ask(undefined), ask(undefined), ask('three')]+ expect(await ask('four')).toEqual({ error: 'BUSY' })+ expect(commands.decide).toHaveBeenCalledTimes(8)+ // A connection's slots come back as its decisions end: closed here, so they end at once.+ host.closeConnection('one')+ expect(await Promise.all(mine)).toEqual([{ error: 'TIMEOUT', detail: 'Command cancelled.' }, { error: 'TIMEOUT', detail: 'Command cancelled.' }])+ void ask('one')+ expect(commands.decide).toHaveBeenCalledTimes(9)+ for (const connection of ['one', 'two', 'three']) host.closeConnection(connection)+ await vi.waitFor(() => expect(answers.filter((answer) => answer.error === 'TIMEOUT')).toHaveLength(6))+ // Those with no connection are never closed by another's closing.+ expect(commands.started.filter((signal) => !signal.aborted)).toHaveLength(3)+ void others+ })++ it('aborts a connection\'s decisions when it closes, and no other connection\'s, with the real decision', async () => {+ const calls: AbortSignal[] = []+ // JEV that never answers: only an abort ends the call.+ const fetch = vi.fn((_url: unknown, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {+ calls.push(init!.signal!)+ init!.signal!.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))+ }))+ const commands = new CommandBarService({ fetch: fetch as typeof globalThis.fetch, key: async () => 'fixture-only', timeoutMs: 60_000 })+ const { host, ask } = hosted(commands)+ const gone = ask('gone')+ const stays = ask('stays')+ await vi.waitFor(() => expect(calls).toHaveLength(2))+ host.closeConnection('gone')+ expect(await gone).toEqual({ error: 'TIMEOUT', detail: 'Command cancelled.' })+ expect(calls.map((signal) => signal.aborted)).toEqual([true, false])+ host.closeConnection('stays')+ expect(await stays).toEqual({ error: 'TIMEOUT', detail: 'Command cancelled.' })+ })++ it('answers a failure in the command bar\'s own words, and anything else as this machine unable to', async () => {+ const decide = vi.fn()+ .mockRejectedValueOnce(new CommandBarError(503, 'OPENROUTER_REQUIRED', 'Connect OpenRouter.'))+ .mockRejectedValueOnce(new Error('socket hang up'))+ const requests = startCommandBar(fakeCore(), { status: vi.fn(), decide })+ expect(await requests.command_bar({ request: REQUEST }, OWNER)).toEqual({ error: 'OPENROUTER_REQUIRED', detail: 'Connect OpenRouter.' })+ expect(await requests.command_bar({ request: REQUEST }, OWNER)).toEqual({ error: 'COMMAND_UNAVAILABLE', detail: 'This machine could not complete the command. Try again.' })+ })++ it('answers the HTTP door with the status and body it answered with, for a process on this computer only', async () => {+ const status = vi.fn()+ .mockResolvedValueOnce({ configured: true, provider: 'OpenRouter', model: 'typesafe/jev-1.13' })+ .mockRejectedValueOnce(new Error('keychain locked'))+ const decide = vi.fn()+ .mockResolvedValueOnce({ selectedId: null, suggestions: [] })+ .mockRejectedValueOnce(new CommandBarError(429, 'BUSY', 'Too many commands at once. Try again in a moment.'))+ const requests = startCommandBar(fakeCore(), { status, decide })+ const local: Asker = { local: true, owner: true, connection: 'http:1' }+ const closed = new AbortController().signal+ expect(await requests.command_bar_http({ route: 'status' }, local, closed)).toEqual({ status: 200, body: { success: true, data: { configured: true, provider: 'OpenRouter', model: 'typesafe/jev-1.13' } } })+ expect(await requests.command_bar_http({ route: 'resolve', body: REQUEST }, local, closed)).toEqual({ status: 200, body: { success: true, data: { selectedId: null, suggestions: [] } } })+ expect(decide).toHaveBeenCalledWith(REQUEST, closed)+ expect(await requests.command_bar_http({ route: 'resolve', body: REQUEST }, local, closed)).toEqual({ status: 429, body: { success: false, error: { code: 'BUSY', message: 'Too many commands at once. Try again in a moment.' } } })+ expect(await requests.command_bar_http({ route: 'status' }, local, closed)).toEqual({ status: 502, body: { success: false, error: { code: 'UNAVAILABLE', message: 'Command bar unavailable.' } } })+ expect(await requests.command_bar_http({ route: 'status' }, OWNER)).toEqual({ error: 'UNSUPPORTED' })+ expect(status).toHaveBeenCalledTimes(2)+ })++ it('decides through OpenRouter, or through a fake JEV on this computer for the end-to-end tests only', async () => {+ expect(commandsFor({})).toBe(commandBarService)+ expect(() => commandsFor({ HARNESS_TEST_JEV_URL: 'https://openrouter.example/decisions' })).toThrow('loopback')+ expect(() => commandsFor({ HARNESS_TEST_JEV_URL: 'http://192.168.1.4:9000/' })).toThrow('loopback')+ const fetch = vi.fn(async () => new Response(JSON.stringify({ answers: {} })))+ vi.stubGlobal('fetch', fetch)+ vi.stubEnv('OPENROUTER_API_KEY', 'fixture-only')+ const fake = commandsFor({ HARNESS_TEST_JEV_URL: 'http://127.0.0.1:4100/decisions' })+ await expect(fake.decide({ prompt: 'x', candidates: [{ id: 'a', kind: 'open', title: 'A', detail: '' }] })).rejects.toMatchObject({ code: 'INVALID_DECISION' })+ expect(String((fetch.mock.calls[0] as unknown[])[0])).toBe('http://127.0.0.1:4100/decisions')+ // Started with no commands given, it decides through OpenRouter.+ expect(Object.keys(startCommandBar(fakeCore()))).toEqual([...COMMAND_BAR_REQUESTS])+ vi.unstubAllEnvs()+ })+})diff --git a/cli/src/services/commandBar.ts b/cli/src/services/commandBar.tsnew file mode 100644index 000000000..a190f7c38--- /dev/null+++ b/cli/src/services/commandBar.ts@@ -0,0 +1,75 @@+/**+ * The command bar: JEV's decisions for the window's command bar and ⌘K (lib/commandBar.ts), an experiment+ * that runs in a process of its own, started when one of its requests arrives. Moved out of the core as it+ * was (docs/design/2026-10-06-core-boundary-next.md, "Light features"): the core keeps only its doors, and+ * nothing in the core depends on it. Off, or its process down, its requests are refused SERVICE_UNAVAILABLE.+ *+ * Its two doors, with the answers each gave from the core:+ * - `command_bar`, a request on the socket (a remote owner's app, or a window here): the decision, or+ * `{ error, detail }`. At most two at once per connection and eight in all, and a connection that closes+ * has its own aborted (lib/ownerCommands.ts did both, keyed by the socket's connection id; the core now+ * gives that id with every request, and says when it closes: `Asker.connection`, `closed`).+ * - `command_bar_http`, the hook server's `/api/command-bar/status` and `/resolve` (lib/commandBarHttp.ts),+ * which checks who asks and reads the body, and asks here on a connection of its own for each HTTP request:+ * the HTTP status and body to answer with. Only a process on this computer may ask it.+ *+ * One `CommandBarService` answers both, so its own bounds (two decisions at once, twenty a minute) hold+ * across the doors, as they did when both called the core's one instance.+ */+import type { CoreApi, ServiceRequests } from '../core/api.js'+import { CommandBarError, CommandBarService, commandBarService } from '../lib/commandBar.js'++/** The requests the command bar answers, declared in core/api.ts for the core to route. */+export { COMMAND_BAR_REQUESTS } from '../core/api.js'++/** What the command bar decides with: lib/commandBar.ts's service, or a test's. */+export interface Commands {+ status(): Promise<unknown>+ decide(raw: unknown, signal?: AbortSignal): Promise<Record<string, unknown>>+}++/**+ * The JEV decisions, with what the tests point them at. `HARNESS_TEST_JEV_URL` (end-to-end tests only,+ * e2e/commandBar.e2e.ts) sends them to a fake Decisions endpoint on this computer instead of OpenRouter:+ * a loopback `http:` origin only, so a stray setting can never send the key anywhere else.+ */+export function commandsFor(env: NodeJS.ProcessEnv = process.env): Commands {+ const fake = env.HARNESS_TEST_JEV_URL+ if (!fake) return commandBarService+ const url = new URL(fake)+ if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1') throw new Error('HARNESS_TEST_JEV_URL must be a loopback http: URL')+ return new CommandBarService({ fetch: (_endpoint, init) => fetch(url, init) })+}++export function startCommandBar(_core: CoreApi, commands: Commands = commandsFor()): ServiceRequests {+ /** The socket's decisions in flight, each with the connection that asked: what its limits count. */+ const pending = new Map<object, unknown>()+ return {+ command_bar: async (payload, asker, closed) => {+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }+ // A request with no connection (from a core before connections were given) counts as its own.+ const connection = asker.connection ?? {}+ if (pending.size >= 8 || [...pending.values()].filter((id) => id === connection).length >= 2) return { error: 'BUSY' }+ const request = {}+ pending.set(request, connection)+ try {+ return await commands.decide(payload.request, closed)+ } catch (error) {+ return error instanceof CommandBarError+ ? { error: error.code, detail: error.message }+ : { error: 'COMMAND_UNAVAILABLE', detail: 'This machine could not complete the command. Try again.' }+ } finally { pending.delete(request) }+ },+ command_bar_http: async (payload, asker, closed) => {+ // The hook server's door asks as this computer; a remote client is not that door.+ if (!asker.local) return { error: 'UNSUPPORTED' }+ const fail = (status: number, code: string, message: string) => ({ status, body: { success: false, error: { code, message } } })+ try {+ const data = payload.route === 'status' ? await commands.status() : await commands.decide(payload.body, closed)+ return { status: 200, body: { success: true, data } }+ } catch (error) {+ return error instanceof CommandBarError ? fail(error.status, error.code, error.message) : fail(502, 'UNAVAILABLE', 'Command bar unavailable.')+ }+ },+ }+}diff --git a/cli/src/services/commandBarProcess.spec.ts b/cli/src/services/commandBarProcess.spec.tsnew file mode 100644index 000000000..08eab5108--- /dev/null+++ b/cli/src/services/commandBarProcess.spec.ts@@ -0,0 +1,30 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { runServiceProcess, type ServiceProcessOptions } from './process.js'+import { runCommandBarService } from './commandBarProcess.js'++// The real default reaches a real socket: never in a test.+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))++describe('the command bar in its own process', () => {+ afterEach(() => vi.clearAllMocks())++ it('answers with the same handlers as in the core\'s process', async () => {+ let options: ServiceProcessOptions | null = null+ const service = { stop: vi.fn() }+ const handle = runCommandBarService({+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',+ run: (given) => { options = given; return service },+ start: () => ({ command_bar: async () => ({ selectedId: null }), command_bar_http: async () => ({ status: 200, body: {} }) }),+ })+ expect(handle).toBe(service)+ expect(options).toMatchObject({ name: 'commandBar', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ expect(await options!.requests.command_bar!({}, { local: true, owner: true })).toEqual({ selectedId: null })+ })++ it('runs as a real service by default', () => {+ runCommandBarService({ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ expect(runServiceProcess).toHaveBeenCalledWith(expect.objectContaining({+ name: 'commandBar', requests: { command_bar: expect.any(Function), command_bar_http: expect.any(Function) },+ }))+ })+})diff --git a/cli/src/services/commandBarProcess.ts b/cli/src/services/commandBarProcess.tsnew file mode 100644index 000000000..c7e69f324--- /dev/null+++ b/cli/src/services/commandBarProcess.ts@@ -0,0 +1,29 @@+/**+ * The command bar in its own process (`harness __service commandBar`): the same handlers as in the core's+ * process (services/commandBar.ts). It asks the core nothing; the OpenRouter key it reads, the JEV calls it+ * makes and the zod schemas it validates them with are this process's alone.+ */+import { startCommandBar } from './commandBar.js'+import { runServiceProcess, type ServiceProcess } from './process.js'+import { processCoreApi } from './processCoreApi.js'++export interface CommandBarServiceOptions {+ dataDir: string+ socketPath: string+ machineId: string+ token: string+ /** Swapped in tests for one that does not touch the real socket or process. */+ run?: typeof runServiceProcess+ /** Swapped in tests for a command bar that calls no JEV. */+ start?: typeof startCommandBar+}++export function runCommandBarService(options: CommandBarServiceOptions): ServiceProcess {+ return (options.run ?? runServiceProcess)({+ name: 'commandBar',+ socketPath: options.socketPath,+ machineId: options.machineId,+ token: options.token,+ requests: (options.start ?? startCommandBar)(processCoreApi(options.dataDir, 'commandBar')),+ })+}diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.tsindex b6b34e48f..5b51ff9cd 100644--- a/cli/src/services/inline.spec.ts+++ b/cli/src/services/inline.spec.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'import { startGateway } from '../gateway/start.js'+import { startCommandBar } from './commandBar.js'import { startDevices } from './devices.js'import * as inline from './inline.js'import { startModels } from './models.js'@@ -17,6 +18,6 @@ import { startWorkspaces } from './workspaces.js'describe('the services the core runs in its own process only when they do not run in theirs', () => {it('are their own starts, unchanged: the same services either way', () => {- expect({ ...inline }).toEqual({ startDevices, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWorkspaces })+ expect({ ...inline }).toEqual({ startCommandBar, startDevices, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWorkspaces })})})diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.tsindex a87750d7a..875adaf9d 100644--- a/cli/src/services/inline.ts+++ b/cli/src/services/inline.ts@@ -13,6 +13,7 @@* declared in core/api.ts, which it loads either way.*/export { startGateway } from '../gateway/start.js'+export { startCommandBar } from './commandBar.js'export { startDevices } from './devices.js'export { startModels } from './models.js'export { startTeamsInCore } from './collaboration.js'