Skip to content

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.

autonomous-device: add focus.step, one tick of the cable dial's carousel

leo5e793c88e0e7
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.ts
index 107f8fef7..efd1c8310 100644
--- a/cli/src/cable/cableHost.spec.ts
+++ b/cli/src/cable/cableHost.spec.ts
@@ -371,6 +371,42 @@ describe('DaemonCableHost.listAgents across machines', () => {
expect(focused).toHaveBeenCalledWith('other', 'r1')
})
+ it('steps focus along the ring, wrapping at both ends, with the same forward the dial uses', async () => {
+ AGENTS.length = 0
+ for (const agentId of ['a1', 'a2', 'a3']) {
+ AGENTS.push({ agentId, registeredAt: 1, active: true, terminalAvailable: true, engine: 'claude' })
+ }
+ const focused = vi.fn()
+ const host = new DaemonCableHost(wiring({ focused }))
+ await settled(host)
+ // Tiles in the window's order, not registration order; a3 has no tile and is never stepped onto.
+ host.setDesk(['a2', 'a1'])
+
+ expect(await host.stepFocus('next', 'a2')).toEqual({ machineId: 'mine', agentId: 'a1' })
+ expect(await host.stepFocus('next', 'a1')).toEqual({ machineId: 'mine', agentId: 'a2' })
+ expect(await host.stepFocus('previous', 'a2')).toEqual({ machineId: 'mine', agentId: 'a1' })
+ // Off the ring, or nothing focused: the walk starts at the first (next) or last (previous) tile.
+ expect(await host.stepFocus('next', 'a3')).toMatchObject({ agentId: 'a2' })
+ expect(await host.stepFocus('previous', undefined)).toMatchObject({ agentId: 'a1' })
+ expect(focused.mock.calls.map((c) => c[1])).toEqual(['a1', 'a2', 'a1', 'a2', 'a1'])
+ })
+
+ it('steps onto a remote tile with that machine’s id, and reports an empty desk', async () => {
+ AGENTS.length = 0
+ AGENTS.push({ agentId: 'a1', registeredAt: 1, active: true, terminalAvailable: true, engine: 'claude' })
+ const focused = vi.fn()
+ const host = new DaemonCableHost(wiring({ focused }), crossFleet({ other: [{ id: 'r1', name: 'api' }] }))
+ await settled(host)
+ host.setDesk(['a1', 'r1'])
+ expect(await host.stepFocus('next', 'a1')).toEqual({ machineId: 'other', agentId: 'r1' })
+ expect(focused).toHaveBeenLastCalledWith('other', 'r1')
+
+ AGENTS.length = 0
+ const empty = new DaemonCableHost(wiring({ focused }))
+ await settled(empty)
+ expect(await empty.stepFocus('next', undefined)).toBe('no_agents')
+ })
+
it('reports a focus with no edge, on or off the desk', async () => {
// `edge` is gone with the arcs. It answered "which tile does this replace" for an agent the window
// had none for, which the carousel could reach by walking past the end of the desk; it walks only
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index f516654f5..aa184112c 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -646,6 +646,23 @@ export class DaemonCableHost implements CableHost {
this.wiring.focused?.(machineId, agentId)
}
+ /**
+ * One tick of the carousel, for a device that has no ring of its own: the paired Autonomous device
+ * asks for "next"/"previous" and this picks the neighbour the USB dial's thumb would land on — the same
+ * walk (`listAgents()` ring order), the same wrap at either end, and the same `focus()` forward to the
+ * app. With no current agent on the ring the walk starts at its first (next) or last (previous) tile.
+ */
+ async stepFocus(direction: 'next' | 'previous', currentAgentId?: string): Promise<{ machineId: string; agentId: string } | 'no_agents'> {
+ const walk = (await this.listAgents()).filter((a) => !a.offRing).map((a) => a.id)
+ if (walk.length === 0) return 'no_agents'
+ const at = currentAgentId ? walk.indexOf(currentAgentId) : -1
+ const agentId = at < 0
+ ? walk[direction === 'next' ? 0 : walk.length - 1]
+ : walk[(at + (direction === 'next' ? 1 : walk.length - 1)) % walk.length]
+ this.focus(agentId)
+ return { machineId: this.machineOf(agentId), agentId }
+ }
+
scrolled(phase: 'down' | 'move' | 'up', dy: number, velocity: number): void {
// THE ENDS ARE LOGGED, THE MIDDLE IS NOT. A stroke is a `down`, a dozen `move`s and an `up`, several
// times a second: logging the middle buries every other line in the file. But the failure this
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index ed97c4802..4e74c2e42 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -4588,6 +4588,9 @@ async function runForeground(session: AuthSession): Promise<void> {
requestAppFocus: (agentId, expiresAt, focusRevision) => backend.sendFirstLocal({
type: 'device_focus', payload: { machineId: backend.machineId, agentId, expiresAt, focusRevision },
}),
+ // The dial's own carousel tick, borrowed: ring order and wrap from the cable host, `dial_focus` to
+ // the window, `app_focus` back. Without a window the forward is a no-op, so say so up front.
+ stepFocus: (direction, currentAgentId) => backend.hasLocalClient() ? cableHost.stepFocus(direction, currentAgentId) : Promise.resolve('no_app'),
agents: () => registry.advertised().map(s => ({ agentId: s.agentId, name: projectDisplayName(s), engine: s.engine,
state: turnStartedAt.has(s.sessionId) ? 'running' : 'idle' })),
submit: submitAgent,
diff --git a/cli/src/lib/autonomous-device/service.spec.ts b/cli/src/lib/autonomous-device/service.spec.ts
index c96d36436..cd6634416 100644
--- a/cli/src/lib/autonomous-device/service.spec.ts
+++ b/cli/src/lib/autonomous-device/service.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { randomUUID } from 'node:crypto'
-import { AutonomousDeviceService, type AutonomousDeviceFrame } from './service.js'
+import { AUTONOMOUS_DEVICE_CAPABILITIES, AutonomousDeviceService, type AutonomousDeviceFrame } from './service.js'
function fixture(now?: () => number, fullAnswer?: string) {
const submit = vi.fn(), stop = vi.fn(async () => true), answer = vi.fn(async () => true)
@@ -60,6 +60,119 @@ describe('Autonomous device local-agent service', () => {
} finally { vi.useRealTimers() }
})
+ describe('focus.step', () => {
+ const DESK = ['a', 'b', 'c']
+ function stepFixture(desk = DESK, acknowledge = true) {
+ const stepFocus = vi.fn(async (direction: 'next' | 'previous', current: string | undefined) => {
+ if (!desk.length) return 'no_agents' as const
+ const at = current ? desk.indexOf(current) : -1
+ const agentId = at < 0 ? desk[direction === 'next' ? 0 : desk.length - 1] : desk[(at + (direction === 'next' ? 1 : desk.length - 1)) % desk.length]
+ // The app acknowledges on its own tick, the way `dial_focus` → `app_focus` does.
+ if (acknowledge) setTimeout(() => service.appFocus('machine', agentId, 'window'), 0)
+ return { machineId: 'machine', agentId }
+ })
+ const events: AutonomousDeviceFrame[] = []
+ const service = new AutonomousDeviceService({ machineId: 'machine', stepFocus,
+ agents: () => desk.map(agentId => ({ agentId, name: agentId.toUpperCase(), engine: 'claude', state: 'idle' })),
+ submit: vi.fn(), stop: async () => true, answer: async () => true, cancelDelivery: () => true, recent: () => [], emit: f => events.push(f) })
+ const step = (direction: 'next' | 'previous', over: Record<string, unknown> = {}) => service.request('device',
+ { type: 'focus.step', requestId: randomUUID(), idempotencyKey: randomUUID(), direction, focusRevision: service.focusSnapshot().focusRevision, ...over })
+ return { service, stepFocus, events, step }
+ }
+
+ it('advertises the capability', () => {
+ expect(new AutonomousDeviceService({ machineId: 'm', agents: () => [], submit: vi.fn(), stop: async () => true, answer: async () => true, cancelDelivery: () => true, recent: () => [] }))
+ .toBeDefined()
+ expect(AUTONOMOUS_DEVICE_CAPABILITIES).toContain('focus.step')
+ })
+
+ it('walks next and previous through the desk and wraps at both ends', async () => {
+ const f = stepFixture()
+ f.service.appFocus('machine', 'b', 'window')
+ expect((await f.step('next')).focus).toEqual({ machineId: 'machine', agentId: 'c', name: 'C' })
+ expect((await f.step('next')).focus).toMatchObject({ agentId: 'a' })
+ expect((await f.step('previous')).focus).toMatchObject({ agentId: 'c' })
+ expect((await f.step('previous')).focus).toMatchObject({ agentId: 'b' })
+ expect(f.stepFocus.mock.calls.map(c => c[1])).toEqual(['b', 'c', 'a', 'c'])
+ expect(f.events.filter(e => e.kind === 'focus.changed')).toHaveLength(5)
+ })
+
+ it('starts from the first or last tile when nothing is focused', async () => {
+ const f = stepFixture()
+ expect((await f.step('previous')).focus).toMatchObject({ agentId: 'c' })
+ const g = stepFixture()
+ expect((await g.step('next')).focus).toMatchObject({ agentId: 'a' })
+ })
+
+ it('answers a single-agent desk with the same focus and no wait', async () => {
+ const f = stepFixture(['only'])
+ f.service.appFocus('machine', 'only', 'window')
+ const before = f.service.focusSnapshot()
+ const result = await f.step('next')
+ expect(result.focus).toMatchObject({ agentId: 'only' })
+ expect(result.focusRevision).toBe(before.focusRevision)
+ expect(f.events.filter(e => e.kind === 'focus.changed')).toHaveLength(1)
+ })
+
+ it('refuses a stale revision without moving', async () => {
+ const f = stepFixture()
+ f.service.appFocus('machine', 'a', 'window')
+ const stale = f.service.focusSnapshot().focusRevision
+ f.service.appFocus('machine', 'b', 'window')
+ expect((await f.step('next', { focusRevision: stale })).error).toMatchObject({ code: 'FOCUS_CHANGED' })
+ expect(f.stepFocus).not.toHaveBeenCalled()
+ expect(f.service.focusSnapshot().focus).toMatchObject({ agentId: 'b' })
+ })
+
+ it('replays a retried gesture instead of stepping twice, even once the revision is stale', async () => {
+ const f = stepFixture()
+ f.service.appFocus('machine', 'a', 'window')
+ const req = { type: 'focus.step', requestId: randomUUID(), idempotencyKey: 'gesture1', direction: 'next', focusRevision: f.service.focusSnapshot().focusRevision }
+ const first = await f.service.request('device', req)
+ expect(first.focus).toMatchObject({ agentId: 'b' })
+ // The first tick already moved focus, so the key's revision is stale now — the retry still gets its result.
+ const retry = await f.service.request('device', { ...req, requestId: randomUUID() })
+ expect(retry).toEqual({ ...first, requestId: retry.requestId })
+ expect(f.stepFocus).toHaveBeenCalledTimes(1)
+ expect((await f.service.request('device', { ...req, requestId: randomUUID(), direction: 'previous' })).error).toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' })
+ // Revoke forgets the gesture with the device: the same key from a re-paired device is a new tick.
+ f.service.revoke('device')
+ expect((await f.service.request('device', { ...req, requestId: randomUUID(), focusRevision: f.service.focusSnapshot().focusRevision })).focus).toMatchObject({ agentId: 'c' })
+ // Another device's identical key is its own gesture.
+ expect((await f.service.request('other', { ...req, requestId: randomUUID(), focusRevision: f.service.focusSnapshot().focusRevision })).focus).toMatchObject({ agentId: 'a' })
+ expect(f.stepFocus).toHaveBeenCalledTimes(3)
+ })
+
+ it('fails clearly when the app never acknowledges, and the retry repeats that answer', async () => {
+ vi.useFakeTimers()
+ try {
+ const f = stepFixture(DESK, false)
+ f.service.appFocus('machine', 'a', 'window')
+ const req = { type: 'focus.step', requestId: randomUUID(), idempotencyKey: 'gesture1', direction: 'next', focusRevision: f.service.focusSnapshot().focusRevision }
+ const pending = f.service.request('device', req)
+ await vi.advanceTimersByTimeAsync(2001)
+ expect((await pending).error).toMatchObject({ code: 'FOCUS_UNAVAILABLE' })
+ expect((await f.service.request('device', { ...req, requestId: randomUUID() })).error).toMatchObject({ code: 'FOCUS_UNAVAILABLE' })
+ expect(f.stepFocus).toHaveBeenCalledTimes(1)
+ expect(f.service.focusSnapshot().focus).toMatchObject({ agentId: 'a' })
+ } finally { vi.useRealTimers() }
+ })
+
+ it('reports no agents, no app, and bad requests without pretending to move', async () => {
+ expect((await stepFixture([]).step('next')).error).toMatchObject({ code: 'NO_AGENTS' })
+ const noApp = new AutonomousDeviceService({ machineId: 'machine', stepFocus: async () => 'no_app',
+ agents: () => [{ agentId: 'a', name: 'A', engine: 'claude', state: 'idle' }],
+ submit: vi.fn(), stop: async () => true, answer: async () => true, cancelDelivery: () => true, recent: () => [] })
+ const base = { type: 'focus.step', idempotencyKey: 'k', direction: 'next', focusRevision: noApp.focusSnapshot().focusRevision }
+ expect((await noApp.request('device', { ...base, requestId: randomUUID() })).error).toMatchObject({ code: 'FOCUS_UNAVAILABLE' })
+ const f = stepFixture()
+ expect((await f.step('next', { direction: 'sideways' })).error).toMatchObject({ code: 'INVALID_REQUEST' })
+ expect((await f.step('next', { focusRevision: undefined })).error).toMatchObject({ code: 'INVALID_REQUEST' })
+ expect((await f.step('next', { machineId: 'machine' })).error).toMatchObject({ code: 'INVALID_REQUEST' })
+ expect(f.stepFocus).not.toHaveBeenCalled()
+ })
+ })
+
it('reserves before dispatch and deduplicates concurrent sends without selecting another agent', async () => {
const f = fixture()
const [a, b] = await Promise.all([f.service.request('device', f.send()), f.service.request('device', f.send())])
diff --git a/cli/src/lib/autonomous-device/service.ts b/cli/src/lib/autonomous-device/service.ts
index 7d86414ad..448f181da 100644
--- a/cli/src/lib/autonomous-device/service.ts
+++ b/cli/src/lib/autonomous-device/service.ts
@@ -15,6 +15,12 @@ export interface AutonomousDeviceServiceOptions {
machineId: string; serverInstanceId?: string; now?: () => number
agents: () => AutonomousDeviceAgent[]
requestAppFocus?: (agentId: string, expiresAt: number, focusRevision: string) => boolean
+ /**
+ * Turn the app's focus one agent along the desk, the way the USB dial does — same ring, same wrap,
+ * same `dial_focus` forward. Resolves to the agent it asked the app to show; the app's own `app_focus`
+ * acknowledgment is what makes the move real. `'no_app'` when no Desktop window is connected.
+ */
+ stepFocus?: (direction: 'next' | 'previous', currentAgentId: string | undefined) => Promise<{ machineId: string; agentId: string } | 'no_agents' | 'no_app'>
submit: (agentId: string, text: string, deliveryId: string) => void
cancelDelivery: (deliveryId: string) => boolean
stop: (agentId: string) => Promise<boolean>
@@ -32,9 +38,11 @@ export interface AutonomousDeviceServiceOptions {
emit?: (frame: AutonomousDeviceFrame) => void
}
interface Entry { deviceId: string; digest: string; receipt: AutonomousDeviceReceipt }
-const CAPABILITIES = ['focus.get', 'focus.ensure', 'agents.list', 'turn.send', 'turn.stop', 'status', 'recap', 'question.answer', 'receipt.get'] as const
+const CAPABILITIES = ['focus.get', 'focus.ensure', 'focus.step', 'agents.list', 'turn.send', 'turn.stop', 'status', 'recap', 'question.answer', 'receipt.get'] as const
export const AUTONOMOUS_DEVICE_CAPABILITIES: string[] = [...CAPABILITIES]
const MUTATIONS = new Set(['turn.send', 'turn.stop', 'question.answer'])
+const STEP_RESULTS_MAX = 512
+const APP_FOCUS_WAIT_MS = 2000
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const KEY = /^[A-Za-z0-9_-]{1,64}$/
const TTL = 30 * 60_000
@@ -85,6 +93,39 @@ export class AutonomousDeviceService {
focusRevision: `${this.serverInstanceId}:${this.focusCounter}` }
}
private ensuringFocus: Promise<ReturnType<AutonomousDeviceService['focusSnapshot']>> | undefined
+ /** Settled `focus.step` outcomes by (device, idempotencyKey): a retried gesture is one tick, not two. */
+ private readonly steps = new Map<string, { deviceId: string; digest: string; result: Promise<ReturnType<AutonomousDeviceService['focusSnapshot']>> }>()
+
+ private stepFocus(deviceId: string, req: Record<string, unknown>): Promise<ReturnType<AutonomousDeviceService['focusSnapshot']>> {
+ if (req.direction !== 'next' && req.direction !== 'previous') fail('INVALID_REQUEST', 'direction must be next or previous')
+ if (!KEY.test(String(req.idempotencyKey ?? ''))) fail('INVALID_REQUEST', 'Invalid idempotencyKey')
+ if (typeof req.focusRevision !== 'string' || !req.focusRevision) fail('INVALID_REQUEST', 'focusRevision must be a nonempty string')
+ const digest = createHash('sha256').update(canonical({ ...req, requestId: null, idempotencyKey: null })).digest('hex')
+ const key = this.key(deviceId, String(req.idempotencyKey))
+ const previous = this.steps.get(key)
+ if (previous) {
+ if (previous.digest !== digest) fail('IDEMPOTENCY_CONFLICT', 'Key already belongs to a different operation or payload')
+ return previous.result
+ }
+ const result = this.performStep(req.direction, req.focusRevision)
+ result.catch(() => undefined) // settled either way; the retry re-awaits it
+ this.steps.set(key, { deviceId, digest, result })
+ // ponytail: FIFO eviction, no TTL — a step result is a snapshot, nothing waits on it like a receipt.
+ if (this.steps.size > STEP_RESULTS_MAX) this.steps.delete(this.steps.keys().next().value as string)
+ return result
+ }
+
+ private async performStep(direction: 'next' | 'previous', focusRevision: string): Promise<ReturnType<AutonomousDeviceService['focusSnapshot']>> {
+ const before = this.focusSnapshot()
+ if (focusRevision !== before.focusRevision) fail('FOCUS_CHANGED', 'App focus changed before the step; nothing was moved')
+ if (!this.options.stepFocus) fail('FOCUS_UNAVAILABLE', 'Stepping focus is not wired on this machine')
+ const target = await this.options.stepFocus(direction, before.focus?.agentId)
+ if (target === 'no_agents') fail('NO_AGENTS', 'No agent is on the desk to step to')
+ if (target === 'no_app') fail('FOCUS_UNAVAILABLE', 'Open Harness Desktop to select an agent')
+ // A desk of one: the only neighbour is the agent already in front — nothing to move, nothing to await.
+ if (before.focus?.machineId === target.machineId && before.focus.agentId === target.agentId) return before
+ return this.waitForAppFocus(Date.now() + APP_FOCUS_WAIT_MS, s => s.focusRevision !== before.focusRevision)
+ }
/** Enable-time fallback only. The desktop must acknowledge its selected pane. */
private ensureFocus(): Promise<ReturnType<AutonomousDeviceService['focusSnapshot']>> {
@@ -93,18 +134,18 @@ export class AutonomousDeviceService {
if (this.ensuringFocus) return this.ensuringFocus
const first = this.options.agents()[0]
if (!first) fail('NO_AGENTS', 'No local agent is available')
- const expiresAt = Date.now() + 2000
+ const expiresAt = Date.now() + APP_FOCUS_WAIT_MS
if (!this.options.requestAppFocus?.(first.agentId, expiresAt, current.focusRevision)) {
fail('FOCUS_UNAVAILABLE', 'Open Harness Desktop to select an agent')
}
- this.ensuringFocus = this.waitForAppFocus(expiresAt).finally(() => { this.ensuringFocus = undefined })
+ this.ensuringFocus = this.waitForAppFocus(expiresAt, s => !!s.focus).finally(() => { this.ensuringFocus = undefined })
return this.ensuringFocus
}
- private async waitForAppFocus(expiresAt: number): Promise<ReturnType<AutonomousDeviceService['focusSnapshot']>> {
+ private async waitForAppFocus(expiresAt: number, done: (s: ReturnType<AutonomousDeviceService['focusSnapshot']>) => boolean): Promise<ReturnType<AutonomousDeviceService['focusSnapshot']>> {
for (;;) {
const snapshot = this.focusSnapshot()
- if (snapshot.focus) return snapshot
+ if (done(snapshot)) return snapshot
if (Date.now() >= expiresAt) fail('FOCUS_UNAVAILABLE', 'Harness Desktop did not acknowledge focus')
await new Promise(resolve => setTimeout(resolve, 20))
}
@@ -167,6 +208,7 @@ export class AutonomousDeviceService {
if (this.turns.get(entry.receipt.agentId) === entry) this.turns.delete(entry.receipt.agentId)
this.entries.delete(key)
}
+ for (const [key, step] of this.steps) if (step.deviceId === deviceId) this.steps.delete(key)
// A newly paired identity cannot replay the previous device's request receipts.
this.events = []
}
@@ -223,7 +265,7 @@ export class AutonomousDeviceService {
try {
if (!UUID.test(String(req.requestId))) fail('INVALID_REQUEST', 'requestId must be a UUIDv4')
if (!AUTONOMOUS_DEVICE_CAPABILITIES.includes(type)) fail('UNSUPPORTED_CAPABILITY', 'Operation is not supported')
- const allowed = ['type', 'requestId', ...(['agents.list', 'focus.get', 'focus.ensure'].includes(type) ? [] : type === 'receipt.get' ? ['idempotencyKey'] : ['machineId', 'agentId']),
+ const allowed = ['type', 'requestId', ...(['agents.list', 'focus.get', 'focus.ensure'].includes(type) ? [] : type === 'receipt.get' ? ['idempotencyKey'] : type === 'focus.step' ? ['direction', 'idempotencyKey', 'focusRevision'] : ['machineId', 'agentId']),
...(MUTATIONS.has(type) ? ['idempotencyKey'] : []), ...(type === 'turn.send' ? ['text', 'focusRevision'] : type === 'question.answer' ? ['questionRequestId', 'answers', 'focusRevision'] : type === 'recap' ? ['n'] : [])]
if (Object.keys(req).some(k => !allowed.includes(k))) fail('INVALID_REQUEST', 'Unknown request field')
if (type === 'receipt.get') {
@@ -232,6 +274,7 @@ export class AutonomousDeviceService {
}
if (type === 'focus.get') return response(this.focusSnapshot())
if (type === 'focus.ensure') return response(await this.ensureFocus())
+ if (type === 'focus.step') return response(await this.stepFocus(deviceId, req))
if ('focusRevision' in req && (typeof req.focusRevision !== 'string' || !req.focusRevision)) fail('INVALID_REQUEST', 'focusRevision must be a nonempty string')
if (type === 'agents.list') {
return response({ machineId: this.options.machineId, agents: this.options.agents().map(a => {
diff --git a/docs/autonomous-device-integration.md b/docs/autonomous-device-integration.md
new file mode 100644
index 000000000..8a048757e
--- /dev/null
+++ b/docs/autonomous-device-integration.md
@@ -0,0 +1,303 @@
+# Autonomous device ↔ Mac: direct discovery and original Harness E2EE
+
+The Mac discovers Autonomous OS on the local network and connects **directly to the device**.
+No manual IP address, device backend credentials, cloud device registration, or backend relay is
+involved in this path. The existing Harness Mac login/start behavior is unchanged; an already
+running daemon can pair and operate while its backend connection is offline. Buddy is untouched.
+
+## Discovery and pairing
+
+Autonomous OS already advertises `_autonomous._tcp` using Avahi. CLI uses `bonjour-service` to
+browse that existing service for three seconds. It returns stable DNS-SD instance IDs and the
+advertised host/port; no new Avahi service or script is needed. Metadata is untrusted discovery,
+not authorization. The user selects a discovered device and enters the code displayed by it.
+
+```sh
+harness autonomous-device discover --json
+harness autonomous-device pair --device '<discovery id>' --code-stdin
+harness autonomous-device status --json
+harness autonomous-device list --json
+harness autonomous-device revoke '<full fingerprint>'
+```
+
+Desktop writes the device code to stdin and closes stdin. Terminal users can use
+`pair <device-code> --device <discovery-id>`. No response echoes the code. No address entry, listen,
+replace or blanket revoke command exists. A stale discovery ID returns DEVICE_NOT_FOUND; if the
+selected device has not opened pairing, NO_INTENT. Wrong code fails the original PAKE and closes
+the attempted socket; a retry makes a fresh socket and requests a new device intent.
+
+CLI connects `ws://<discovered-host>:<SRV-port>/api/harness/ws`. The service may advertise port80;
+its existing nginx must forward WebSocket upgrade for that exact route to OS-server. Never hardcode
+OS port5000 or ask the user to type it. First message:
+
+```json
+{"type":"machine_select","payload":{"machineId":"stable-harness-machine-id","label":"Mac name"}}
+```
+
+OS responds machine_selected. During device pairing it sends original e2e_pair_intent role device;
+CLI accepts the human code and delegates to the existing E2eeManager. After original PAKE, OS
+sends original e2e_hello on the same direct socket. CLI waits for authentication as the exact newly
+paired device before reporting success. On reconnect, OS sends e2e_hello using its stored pin.
+
+The Mac retains only `{discoveryId,fingerprint}` association metadata in
+`${ADAPTER_DATA_DIR}/autonomous-device-connections.json`; keys and trust remain exclusively in
+original E2eeManager/paired.json. Every 15 seconds it rediscovers disconnected saved devices.
+Discovered reconnect identity must match the saved fingerprint, even if a different identity is
+already trusted elsewhere. Revocation deletes the association, closes its direct socket and stops
+reconnect. Browser/dial pairings retain their existing behavior and are never blanket-revoked.
+
+Direct connections enter the **same** daemon manager via isolated connIds and targeted sends.
+Inbound direct whitelist is original device PAKE/cancel/hello/status plus Autonomous device app
+RPC, never generic backend/terminal/admin handlers, setup claims or remote-password PAKE.
+Pair intent/PAKE is accepted only during an explicit direct pairing attempt. Backend disconnection
+drops relay sessions but preserves direct ones. Offline pairing availability is checked for the
+specific pending connection, so a direct socket cannot authorize pairing an offline browser slot.
+Only an authenticated application hello activates recap generation/notifications.
+
+## Local management facade
+
+All routes remain on the credential-checked loopback hook server. There is no new Mac LAN listener.
+
+| Route | Input/result |
+|---|---|
+| GET `/api/autonomous-device/discover` | `{devices:[{id,name,host,port}]}` discovered candidates |
+| POST `/api/autonomous-device/pair/start` | `{code,device:<discovery-id>}` → `{state:"paired",label,fingerprint}` |
+| GET `/api/autonomous-device/pair/status` | existing pending device status idle/waiting/running |
+| GET `/api/autonomous-device/status` | `{transport:"direct",connected,paired,sessions,proto:1}`; connected/sessions count authenticated application-ready direct sessions only |
+| GET `/api/autonomous-device/list` | `{devices:[{id:fingerprint,fingerprint,label,pairedAt,online,role,current}]}` existing trusted device-role identities |
+| POST `/api/autonomous-device/revoke` | `{id:<full fingerprint>}` → `{revoked:1}` |
+| GET `/api/autonomous-device/receipt?deviceId=…&idempotencyKey=…` | existing receipt; deviceId here is canonical public key |
+
+Discovery id and trusted fingerprint are distinct identifiers. A user chooses a discovery record
+for pairing; revoke targets the exact existing trusted fingerprint. Original `harness pair` and
+browser/dial UI behavior are unchanged. Direct pairing is initiated by the named facade above.
+When the device revokes its own local trust, it sends the authenticated application request
+`{type:"pair.revoke",requestId}` and waits for `pair.revoke_result` before closing its socket.
+The CLI then removes that exact device identity and its reconnect metadata. A socket close without
+this request remains `offline`, rather than being treated as a revoke, so transient LAN failures do
+not unpair the device.
+
+## Existing encrypted wire, unchanged
+
+Client identity and session use `cli/src/lib/e2ee/core.ts` and `manager.ts` exactly:
+
+- `e2e_pair_intent`, `e2e_pair_intent_result`, `e2e_pair_cancel`, `e2e_pake` payload rounds 1–5;
+ CPace CI `autonomous-e2e-pair|agent:<machineId>|a:adapter|b:device`.
+- `e2e_hello` payload `{identityPub,ephPub,sig}` using existing `helloSig`.
+- `e2e_welcome` payload `{webEphPub,ephPub,sig,enc}` using existing `welcomeSig`. `enc` is AEAD
+ server counter 0, AAD `e2e-welcome`, plaintext `{groupKey,epoch,features}`.
+- Existing X25519 sessionKeys, pairwise counters/replay window and `e2e_rekey` behavior.
+- No custom canonical hello/welcome signature, challenge, `autonomous_device_finished`, or custom
+ identity file. The device needs its own existing E2EE identity/pin, separate from Buddy.
+
+After original E2EE session establishment on the direct socket, application RPC uses:
+
+```json
+{"type":"autonomous_device_request","machineId":"selected-machine","payload":{"__e2e":{"v":1,"k":"p","n":0,"ct":"..."}}}
+```
+
+AAD uses existing wrapPayload: `1|autonomous_device_request||p|`; no dbSessionId on this envelope.
+The encrypted payload is the full application request. CLI intercepts before frame logging,
+requires an authenticated role-device session and ciphertext, and derives receipt identity from
+that session, never from a client-supplied identifier. Results use outer `autonomous_device_result`
+and events use outer `autonomous_device_event`, encrypted via existing wrapTarget with the same
+empty dbSessionId AAD convention. Machine targeting is explicit in the inner application request. No cloud routing is involved.
+
+First encrypted application request:
+
+```json
+{"type":"hello","requestId":"uuid","proto":1,"resume":{"serverInstanceId":"previous","cursor":4}}
+```
+
+Result plaintext: `{type:"hello_result",requestId,proto:1,machineId,serverInstanceId,capabilities,
+resumed,cursor}`. Resume is optional. This is application capability/resume negotiation, not a new
+cryptographic handshake. Existing session proof is the encrypted request. Then replay/resync and
+normal requests below follow. Result plaintext retains the service's `<operation>_result` type.
+Events retain full `{type:"event",...}` inside their encrypted outer envelope. Old browsers and
+dials remain on their existing request/event protocol.
+
+## Application requests, results and events
+
+All requests have UUIDv4 `requestId`. Unknown fields are rejected. Responses use
+`{type:"<operation>_result",requestId,...}`. Application failures before acceptance have
+`error:{code,message}` without a receipt. Mutations successfully reserved have `status` and receipt;
+a duplicate may return any retained receipt state. Supported operations:
+
+| Operation | Additional request fields | Success fields |
+|---|---|---|
+| `focus.ensure` | none | Same snapshot as `focus.get`; enable-time first-agent fallback acknowledged by Desktop |
+| `focus.get` | none | `focus:null\|{machineId,agentId,name?},focusRevision` |
+| `focus.step` | `direction:"next"\|"previous",idempotencyKey,focusRevision` | Same snapshot as `focus.get`, after Desktop acknowledged the new agent — see *Stepping focus* |
+| `agents.list` | none | `machineId,agents:[{machineId,agentId,name,engine,state,recap?}]` — `recap` is the agent's newest turn headline (≤200 chars, the same string `recap` returns as `turns[0].recap`); absent until a turn has been summarised |
+| `status` | `machineId,agentId` | `machineId,agentId,state,openQuestion:null\|{requestId,questions}` |
+| `recap` | `machineId,agentId,n?` (default 3, integer 1–5) | `machineId,agentId,turns:[{kind,text,recap?,fullText?}]` |
+| `turn.send` | `machineId,agentId,idempotencyKey,text,focusRevision?` | `status,receipt` |
+| `turn.stop` | `machineId,agentId,idempotencyKey` | `status,receipt` |
+| `question.answer` | `machineId,agentId,idempotencyKey,questionRequestId,answers,focusRevision?` | `status,receipt` |
+| `receipt.get` | `idempotencyKey` | `receipt:null\|Receipt` |
+
+`idempotencyKey` matches `[A-Za-z0-9_-]{1,64}`. Prompt must be nonblank and ≤16 KiB UTF-8;
+it is never truncated. Answers is a nonempty object mapping question keys to string answers.
+Question ID must still be open. Question answering cannot approve tool permissions.
+Agent state currently derives `running`/`idle` from the local registry/turn tracker.
+There is no CLI selection operation: the desktop app supplies the voice target through explicit
+local `app_focus {agentId}` frames. `app_focus {agentId:null}` clears the owning connection's focus;
+disconnecting that connection also clears it, but an older connection cannot clear a newer owner.
+Opening terminal streams does not establish voice focus. Before the first app focus, focus is null.
+`focus.get` is advertised in hello capabilities and requires only a request ID. `focus.changed`
+events carry the same `{focus,focusRevision}` snapshot in their payload. Revisions are opaque strings
+unique across server restarts; every change of focus changes the revision, including focus A→B→A. Reannouncing the same target
+keeps its revision stable while transferring ownership to the announcing connection.
+A removed local agent clears focus when the snapshot is read. Remote app focus is reported with its
+remote machine ID; this local-only device facade does not substitute a local target or relay dispatch.
+OS can display the snapshot on Monitor Pairing and poll it to recover missed events.
+
+Voice clients pass the snapshot's `focusRevision` with explicit `machineId,agentId` on `turn.send`
+and `question.answer`. After checking retained duplicates, the service synchronously verifies both
+revision and target before reserving or dispatching new work. Mismatch returns `FOCUS_CHANGED`
+without a receipt: that request did not dispatch. A duplicate keeps its original receipt even if
+focus moved. Requests without `focusRevision` retain legacy explicit-target behavior. `turn.stop`
+does not accept the field, so stopping an existing turn remains tied to its original target.
+
+Receipt:
+
+```json
+{"idempotencyKey":"device-1","deliveryId":"<uuid>","operation":"turn.send","state":"queued","machineId":"machine","agentId":"agent","serverInstanceId":"<uuid>","turnId":null,"error":null,"at":1757302040000}
+```
+
+States: `queued`, `delivered`, `started`, `completed`, `rejected`, `unknown`. `turnId` is local
+receipt correlation generated when start is observed, not an engine-native transcript ID.
+`status` is `accepted` or `duplicate`; accepted means a reservation was created, not delivery or
+completion. After reservation every result carries a receipt, including revoked or failed requests.
+A proven failure is `receipt.state:"rejected"`; failure details remain inside `receipt.error`.
+Successful stop/answer transitions its own receipt to completed; an unconfirmed outcome is unknown.
+Submit exceptions and ambiguous post-dispatch failures are unknown. Only proven no-delivery cases
+may be rejected. `receipt:null` means no information, never proof a request did not run.
+
+Dedupe is reserved synchronously before dispatch, keyed `(deviceId,idempotencyKey)`, comparing all
+validated request fields except correlation IDs (normalized to null before canonical SHA-256).
+Same key/different intent → `IDEMPOTENCY_CONFLICT`. Receipt capacity is 512 total. Completed and
+rejected entries age out after 30 minutes from their last transition. At capacity, the oldest
+completed/rejected receipt is evicted, even if younger than 30 minutes; retention is bounded by
+both capacity and TTL. Outstanding/unknown entries are never silently evicted: if all 512 are
+unresolved, new mutations receive `BACKPRESSURE`. Evicting these entries would permit a duplicate
+live prompt; this explicit exception takes precedence over unconditional oldest-entry eviction.
+A retired key may be treated as new, so never auto-resend after `receipt:null`. All receipts/events are
+RAM-only. Every daemon start has a new UUID `serverInstanceId`; no mutation auto-replay is safe
+across restart. Revoke clears the old device's receipts and event replay history.
+
+Events are encrypted full objects:
+
+```json
+{"type":"event","eventId":1,"serverInstanceId":"<uuid>","machineId":"machine","agentId":"agent","kind":"receipt.updated","payload":{"receipt":{},"idempotencyKey":"device-1"}}
+```
+
+Kinds include `receipt.updated`, `turn.started`, `turn.done`, `turn.error`, `turn.summary`,
+`turn.tool`, `agent.error`, `question.open`, `question.close`.
+
+`turn.summary` payload and `recap` turn entries carry three views of one answer, and a consumer should
+prefer `turns[].fullText`, then `turn.summary.fullText`, then `text`:
+
+| Field | Limit | What it is |
+|---|---|---|
+| `recap` | 60 chars | the first prose sentence — a tile headline |
+| `text` | 250 chars | the answer flattened to one line and clipped — a glance |
+| `fullText` | 8192 bytes UTF-8 | the assistant's final message as shown on screen, markdown and line breaks intact |
+
+`agents.list` inlines only the first of the three, so a list view has a status line per agent without one
+`recap` round-trip each. Only the headline, by arithmetic again: the list is uncapped, and `text` or
+`fullText` on every row would put a machine with a few dozen agents over the socket's frame limit.
+
+`fullText` is optional and absent when no answer was recorded, so read it defensively. It holds only the
+final user-facing response — never tool transcripts, hidden reasoning or terminal output — and it costs
+no extra model call: it is the same text the local summarizer already receives.
+
+The 8192-byte cap is arithmetic, not taste: the direct socket accepts 65536 bytes, `recap` may return
+five turns at once, and sealed payloads grow by roughly 37% through AEAD and base64. Oversized truncation
+is UTF-8 safe and marked with a trailing `…`. `text` and `recap` are unchanged byte-for-byte, and the
+shared `commander_event` card is not widened — the USB dial's encoder throws above an 8 KiB frame, so the
+field is added only to the events this service emits. Question-open payload is
+`{questionRequestId,questions}`. Status uses `openQuestion.requestId` for that same identifier.
+Only device-origin turns with known correlation include `idempotencyKey`/`turnId`.
+Ring capacity 500; cursor is `(serverInstanceId,eventId)`. Matching retained cursor replays newer
+events. Changed instance or stale cursor returns encrypted `{type:"resync",reason:
+"instance_changed"|"cursor_too_old",serverInstanceId,cursor}`. First connect also requests resync.
+OS re-reads agents/status and reconciles outstanding keys using receipt.get. Queued means wait;
+delivered/started/completed means adopt; rejected means report; unknown/null means inspect and ask
+before resending. Never automatically replay mutations on reconnect.
+
+Application errors include `INVALID_REQUEST`, `UNSUPPORTED_CAPABILITY`, `MISSING_TARGET`,
+`MACHINE_MISMATCH`, `AGENT_NOT_FOUND`, `NO_AGENTS`, `FOCUS_UNAVAILABLE`, `FOCUS_CHANGED`, `PAYLOAD_TOO_LARGE`, `QUESTION_STALE`,
+`IDEMPOTENCY_CONFLICT`, `BACKPRESSURE`, `RATE_LIMITED`, `REVOKED`, `INTERNAL`.
+A per-relay-connection token bucket permits burst 20, refilling one request/second, with at most four async
+requests in flight; a new relay connection starts a new quota. Excess returns an error result.
+Direct transport uses an outbound WebSocket; reconnection rediscovers the saved service identity. There is
+currently no server-wide request timeout guarantee.
+
+## Implementation and validation
+
+`discovery.ts` browses existing mDNS with bonjour-service; `direct.ts` owns outbound sockets and
+non-secret reconnect associations. `relay.ts` is the retained application/E2EE adapter name, not a
+network backend dependency; it sends on the direct connId through existing manager wrapTarget.
+`service.ts` retains local agent dispatch and bounded receipt/dedupe logic.
+Focused CLI tests and typecheck pass, including discovered-target-only pairing, failed-attempt
+fresh retry, authentication before success and reconnect identity mismatch. Real mDNS discovery and direct Go OS ↔ CLI integration passed with the backend never connected:
+advertised SRV port, wrong-code/fresh retry, original PAKE/session, encrypted list/send/dedupe,
+restart/reconnect and revoke/unpair. This is a real local client/server test, not physical-device deployment.
+Full CLI regression passed: `npm test -- --maxWorkers=1 --testTimeout=30000 --hookTimeout=30000`
+(144 files / 1,871 tests passed; 5 files / 50 tests skipped), plus `npm run typecheck`.
+The default 5-second test deadline timed out in existing password/scrypt tests under local load;
+the serial run uses command-line deadlines only and does not change test files or configuration.
+No physical device deployment.
+
+### Enable-time default agent
+
+The optional negotiated `focus.ensure` capability accepts only `{type:"focus.ensure",requestId}`.
+It preserves any current app focus, including focus on a remote machine; the OS remains responsible
+for refusing an unsupported remote target. With no focus, it asks one connected local Desktop window
+to select the first agent in the local `agents.list` order using its ordinary pane selection path.
+Desktop reannounces an existing selection instead of replacing it. Only the existing `app_focus`
+acknowledgment establishes authoritative focus; no task is dispatched and no headless target is invented.
+Concurrent requests share the same two-second wait. Missing agents return `NO_AGENTS`; no window or
+no acknowledgment returns `FOCUS_UNAVAILABLE`. The local `device_focus` frame carries an expiration
+so a delayed request cannot open a pane after the wait. This operation is for enabling voice mode,
+never for recovering a missing target during an utterance. Older CLIs without this capability require
+an explicit app selection. `focus.get`, events, pairing, and normal turn dispatch remain unchanged.
+The automatic app acknowledgment carries its original focus revision; CLI discards it if a newer explicit selection arrived while the request was in flight.
+
+### Stepping focus
+
+`focus.step` is one tick of the USB dial's carousel, requested by the paired device instead of a thumb:
+
+```json
+{"type":"focus.step","requestId":"<uuid>","idempotencyKey":"<uuid per gesture>","direction":"next","focusRevision":"<from focus.get>"}
+```
+
+`direction` is `next` or `previous`; `idempotencyKey` matches `[A-Za-z0-9_-]{1,64}`; `focusRevision`
+is required. Success is the same `{focus,focusRevision}` snapshot `focus.get` returns, read **after**
+Desktop acknowledged the new selection through its ordinary `app_focus` frame; a `focus.changed` event
+carries the same snapshot, as for any other change. No headless target is invented.
+
+The walk is the dial's: the Desktop window's open tiles in tile order (with no window, every agent in
+rail order — this computer first, then other machines in wheel order), wrapping at both ends. Agents
+without a tile are never stepped onto. With nothing focused, `next` starts at the first tile and
+`previous` at the last. A desk of one agent answers with the current snapshot at once; nothing moves.
+The move itself is the same `dial_focus` forward the cable dial uses, so the app decides what a
+selection means exactly as it does for the dial.
+
+Order of checks: a retained result for `(deviceId,idempotencyKey)` is returned first, success or
+error, so a retried gesture is one tick, never two (same key with a different `direction` or
+`focusRevision` → `IDEMPOTENCY_CONFLICT`). Only a new key is then checked against the current
+revision: a stale `focusRevision` returns `FOCUS_CHANGED` and nothing moves. Retained results are
+RAM-only, capped at 512 per daemon, evicted oldest first, and cleared by revoke like receipts.
+
+Errors: `NO_AGENTS` when the walk is empty; `FOCUS_UNAVAILABLE` when no Desktop window is connected
+or it did not acknowledge within two seconds (the daemon does not retry — read `focus.get` before
+sending again); `INVALID_REQUEST` for a bad direction, key or revision.
+
+Target limits are unchanged. The walk may step onto a tile that belongs to another machine, because
+the window can show one; the local daemon then reports the app's focus leaving this machine
+(`focus:null`, new revision, or the remote target if Desktop announces it here), and `turn.send`
+to that target still returns `MACHINE_MISMATCH`. The OS remains responsible for showing that a
+remote target is not supported for dispatch. Pairing, transport, credentials and task dispatch are
+untouched; older CLIs do not list `focus.step` in hello capabilities.
diff --git a/docs/vi/autonomous-device-integration_vi.md b/docs/vi/autonomous-device-integration_vi.md
new file mode 100644
index 000000000..f3e4715ba
--- /dev/null
+++ b/docs/vi/autonomous-device-integration_vi.md
@@ -0,0 +1,146 @@
+# Autonomous device ↔ Mac trực tiếp
+
+Mac tự tìm Autonomous OS qua service Avahi `_autonomous._tcp` đang có, dùng bonjour-service
+browse ba giây. Không nhập IP, không backend relay hoặc credential cloud trên thiết bị. Giữ
+login/start của Harness Mac như cũ; daemon đang chạy vẫn pair/điều khiển khi backend offline.
+Buddy không dùng và không sửa.
+
+```sh
+harness autonomous-device discover --json
+harness autonomous-device pair --device '<discovery-id>' --code-stdin
+harness autonomous-device status --json
+harness autonomous-device list --json
+harness autonomous-device revoke '<full fingerprint>'
+```
+
+Thiết bị sinh/hiển thị mã; Desktop chọn thiết bị tìm thấy rồi ghi mã vào stdin của CLI, không argv/log.
+Discovery trả `{devices:[{id,name,host,port}]}`. CLI dial trực tiếp
+`ws://<host>:<SRV-port>/api/harness/ws`, dùng đúng port quảng bá (có thể80), nginx chuyển Upgrade
+cho route đó. Không hardcode5000, không thêm Avahi/script. Frame đầu machine_select payload
+machineId/label; OS trả machine_selected và e2e_pair_intent nếu đang pair. Sau mã nhập đúng, chạy
+PAKE và e2e_hello/welcome gốc; CLI chờ session đúng identity trước báo paired.
+
+Không listener Mac mới, custom handshake/trust store, role mới hay backend onboarding. Inbound
+trực tiếp chỉ nhận PAKE/cancel/hello/status cần thiết và app RPC; không setup token/remote password,
+terminal/admin. Intent/PAKE chỉ được nhận trong lần pair chủ động. Backend offline không xóa
+direct session hoặc cho phép pair nhầm browser slot.
+
+Metadata `${ADAPTER_DATA_DIR}/autonomous-device-connections.json` chỉ lưu discoveryId/fingerprint;
+key/pin vẫn ở E2eeManager/paired.json gốc. Mỗi15giây tìm lại thiết bị đã lưu và reconnect. Publickey
+reconnect phải đúng fingerprint association; mDNS không cấp quyền. Revoke đóng socket và bỏ
+association, không ảnh hưởng browser/dial khác. Sai mã đóng attempt để lần sau có socket/intent mới.
+Chỉ app hello đã xác thực mới bật recap/notification.
+
+Facade loopback có credential: GET discover; POST pair/start `{code,device}`; GET pair/status;
+GET status (transport direct); GET list (id là fingerprint, khác discoveryId); POST revoke `{id}`;
+GET receipt query deviceId canonical publickey và idempotencyKey. Không listen/address/replace/all.
+
+Khi device tự revoke trust cục bộ, nó gửi application request đã xác thực
+`{type:"pair.revoke",requestId}` và đợi `pair.revoke_result` trước khi đóng socket. CLI sẽ xóa đúng
+identity đó cùng metadata reconnect. Socket chỉ đóng mà không có request này vẫn là `offline`, không
+được hiểu là revoke, để lỗi mạng thoáng qua không unpair device.
+
+Wire dùng nguyên e2e_* gốc role device, CI b:device. App outer autonomous_device_request/result/event
+vẫn pairwise encrypted với empty dbSessionId AAD; helper relay.ts chỉ là adapter ứng dụng dùng chung
+crypto, không kết nối backend. Request agents.list/status/recap/turn.send/turn.stop/question.answer/
+receipt.get giữ target rõ và receipt/dedupe. Không replay mutation khi mất kết nối; unknown không
+có nghĩa chưa gửi. Cache512/ring500 và schema đầy đủ ở [bản EN](../autonomous-device-integration.md).
+
+## Focus của app cho voice
+
+CLI quảng bá capability `focus.get`; request `{type:"focus.get",requestId}` trả
+`{type:"focus.get_result",requestId,focus:null|{machineId,agentId,name?},focusRevision}`.
+Event `focus.changed` có payload `{focus,focusRevision}` cùng schema. Monitor Pairing hiển thị
+snapshot này; OS có thể poll để phục hồi khi bỏ lỡ event.
+
+Nguồn focus là frame local tường minh `app_focus {agentId}` từ Desktop, không phải `terminal_open`.
+Ban đầu focus là null. `app_focus {agentId:null}` hoặc đóng socket đang sở hữu focus sẽ xóa focus;
+socket cũ không được xóa focus của socket mới. Mỗi thay đổi focus đổi revision, kể cả A→B→A; thông báo lại cùng target giữ nguyên revision
+nhưng chuyển quyền sở hữu sang socket thông báo;
+revision là chuỗi opaque có server instance ID nên khác sau restart. Khi đọc snapshot, agent local
+đã bị xóa làm focus thành null và đổi revision. Focus máy remote giữ đúng machine ID remote;
+facade device chỉ hỗ trợ máy đã pair, không thay bằng agent local hoặc tự relay task.
+
+`turn.send` và `question.answer` nhận `focusRevision` tùy chọn bên cạnh target ID tường minh.
+Sau bước kiểm tra receipt trùng, service kiểm tra đồng bộ revision và target trước khi reserve/gửi.
+Sai revision hoặc target trả `FOCUS_CHANGED` không receipt: request đó chưa dispatch. Request trùng
+đã reserve vẫn trả receipt cũ dù focus đổi. Client cũ không truyền revision vẫn dùng target tường minh
+như trước. `turn.stop` không nhận trường này, tiếp tục nhắm target của lượt đang chạy.
+
+`turn.summary` và mỗi phần tử `recap.turns[]` mang ba mức của cùng một câu trả lời; bên tiêu thụ nên
+ưu tiên `turns[].fullText`, rồi `turn.summary.fullText`, rồi `text`:
+
+| Trường | Giới hạn | Là gì |
+|---|---|---|
+| `recap` | 60 ký tự | câu văn xuôi đầu tiên — tiêu đề ô tile |
+| `text` | 250 ký tự | câu trả lời bị làm phẳng một dòng rồi cắt — để liếc |
+| `fullText` | 8192 byte UTF-8 | tin nhắn cuối của agent đúng như hiện trên màn hình, giữ markdown và xuống dòng |
+
+`fullText` là tuỳ chọn, vắng mặt khi chưa ghi được câu trả lời nào, nên phải đọc phòng thủ. Nó chỉ chứa
+phản hồi cuối hướng tới người dùng — không có transcript tool, suy luận ẩn hay output terminal — và
+không tốn thêm lần gọi model: đó chính là văn bản mà bộ tóm tắt cục bộ vốn đã nhận.
+
+Trần 8192 byte là phép tính chứ không phải khẩu vị: socket direct nhận 65536 byte, `recap` có thể trả
+năm lượt một lần, và payload đã seal phình khoảng 37% qua AEAD và base64. Cắt vượt trần là cắt an toàn
+UTF-8, kèm `…` ở cuối. `text` và `recap` giữ nguyên từng byte, và card `commander_event` dùng chung
+không bị nới — encoder của dial USB ném lỗi khi frame vượt 8 KiB, nên trường này chỉ thêm vào event do
+service này phát ra.
+
+Typecheck/focused test đã đạt gồm chỉ chọn discovery, retry socket mới, chờ authenticated identity
+và từ chối reconnect giả mạo. Real mDNS/direct Go OS ↔ CLI đã đạt khi backend chưa từng kết nối: discovery SRV, sai mã/retry,
+PAKE/session, encrypted list/send/dedupe, restart/reconnect và revoke/unpair. Status chỉ đếm direct
+session đã xác thực và app-ready, không đếm socket thô. Full CLI đã đạt với
+`npm test -- --maxWorkers=1 --testTimeout=30000 --hookTimeout=30000`: 144 file / 1.871 test pass,
+5 file / 50 test skip; `npm run typecheck` đạt. Lần chạy deadline mặc định 5 giây bị timeout ở
+các test password/scrypt sẵn có khi máy chịu tải. Chỉ đổi deadline qua lệnh chạy serial, không
+sửa test hoặc cấu hình để né lỗi. Không deploy hoặc pair thiết bị thật.
+
+### Agent mặc định khi bật mode
+
+Capability tùy chọn `focus.ensure` nhận `{type:"focus.ensure",requestId}` và trả cùng snapshot
+`{focus,focusRevision}` như `focus.get`. Nếu app đã có focus thì giữ nguyên, kể cả máy remote;
+OS vẫn từ chối target remote chưa được hỗ trợ. Nếu chưa có focus, CLI yêu cầu một cửa sổ Desktop
+local chọn agent đầu tiên theo thứ tự `agents.list`, dùng flow chọn pane hiện có. Desktop đang có
+lựa chọn sẽ gửi lại focus đó thay vì thay đổi. Chỉ xác nhận `app_focus` mới thiết lập target chính thức;
+không gửi task hay tự đặt target khi không có app.
+Các request đồng thời dùng chung lần chờ tối đa hai giây. Không có agent trả `NO_AGENTS`; không có
+cửa sổ hoặc không nhận xác nhận trả `FOCUS_UNAVAILABLE`. Frame local `device_focus` có thời hạn để
+request đến trễ không mở pane sau khi hết thời gian chờ. Chỉ gọi khi bật voice mode, không gọi giữa
+utterance để tự đổi target. CLI cũ chưa có capability cần chọn agent trong app. Pairing, đọc focus,
+event và dispatch task thông thường giữ nguyên.
+Xác nhận focus tự động mang revision ban đầu; CLI bỏ qua nếu user đã chọn focus mới trong lúc request đang truyền.
+
+### Chuyển focus từng bước
+
+`focus.step` là một nấc xoay của carousel trên dial USB, nhưng do thiết bị đã pair yêu cầu thay vì ngón tay:
+
+```json
+{"type":"focus.step","requestId":"<uuid>","idempotencyKey":"<uuid mỗi gesture>","direction":"next","focusRevision":"<từ focus.get>"}
+```
+
+`direction` là `next` hoặc `previous`; `idempotencyKey` khớp `[A-Za-z0-9_-]{1,64}`; `focusRevision`
+bắt buộc. Thành công trả đúng snapshot `{focus,focusRevision}` như `focus.get`, đọc **sau khi** Desktop
+xác nhận lựa chọn mới qua frame `app_focus` thông thường; event `focus.changed` mang cùng snapshot như
+mọi lần đổi focus khác. Không tự đặt target khi không có app.
+
+Thứ tự đi là của dial: các tile đang mở trong cửa sổ Desktop theo thứ tự tile (không có cửa sổ thì
+mọi agent theo thứ tự rail — máy này trước, rồi các máy khác theo thứ tự wheel), xoay vòng ở cả hai
+đầu. Agent không có tile không bao giờ được bước tới. Chưa có focus thì `next` bắt đầu ở tile đầu,
+`previous` ở tile cuối. Chỉ có một agent thì trả ngay snapshot hiện tại, không chuyển gì. Bước chuyển
+dùng đúng forward `dial_focus` của dial cáp, nên app quyết định ý nghĩa của việc chọn y như với dial.
+
+Thứ tự kiểm tra: kết quả đã lưu cho `(deviceId,idempotencyKey)` được trả trước, dù thành công hay lỗi,
+nên gesture retry là một nấc chứ không phải hai (cùng key nhưng khác `direction` hoặc `focusRevision`
+→ `IDEMPOTENCY_CONFLICT`). Chỉ key mới mới được so với revision hiện tại: `focusRevision` cũ trả
+`FOCUS_CHANGED` và không chuyển. Kết quả lưu chỉ trong RAM, tối đa 512 mỗi daemon, xoá cũ nhất trước,
+và bị xoá khi revoke như receipt.
+
+Lỗi: `NO_AGENTS` khi không có gì để bước tới; `FOCUS_UNAVAILABLE` khi không có cửa sổ Desktop hoặc
+app không xác nhận trong hai giây (daemon không retry — đọc `focus.get` trước khi gửi lại);
+`INVALID_REQUEST` khi direction, key hoặc revision sai.
+
+Giới hạn target giữ nguyên. Bước chuyển có thể rơi vào tile thuộc máy khác vì cửa sổ có thể đang mở
+tile đó; daemon local khi đó báo focus của app rời máy này (`focus:null` với revision mới, hoặc
+target remote nếu Desktop công bố ở đây), và `turn.send` tới target đó vẫn trả `MACHINE_MISMATCH`.
+OS vẫn chịu trách nhiệm hiển thị rằng target remote chưa được hỗ trợ dispatch. Pairing, transport,
+credential và flow gửi task không đổi; CLI cũ không liệt kê `focus.step` trong capabilities của hello.