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
Select initial desktop focus for device voice activation
leo8202bd4a8ce8
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 8210bfee4..8e8259827 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -478,6 +478,22 @@ describe('BackendSocket outbound queue', () => {await socket.stop()})+ it('sends a device focus request to one desktop window only', async () => {+ const socket = new BackendSocket('token')+ const first = vi.fn(() => true), second = vi.fn(() => true)+ const frame = { type: 'device_focus', payload: { agentId: 'first' } }+ expect(socket.sendFirstLocal(frame)).toBe(false)+ socket.registerLocalClient('local:first', { sendFrame: first, sendBinary: () => true })+ socket.registerLocalClient('local:second', { sendFrame: second, sendBinary: () => true })+ first.mockClear(); second.mockClear()+ expect(socket.sendFirstLocal(frame)).toBe(true)+ expect(first).toHaveBeenCalledExactlyOnceWith(frame)+ expect(second).not.toHaveBeenCalled()+ await socket.unregisterLocalClient('local:first')+ await socket.unregisterLocalClient('local:second')+ await socket.stop()+ })+it('hands a blocked agent to the window without putting the question on the cloud leg', async () => {const socket = new BackendSocket('token')expect(socket.hasLocalClient()).toBe(false)diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 9fb7c3422..731561e23 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -690,6 +690,15 @@ export class BackendSocket {}}+ /** Ask one local desktop to select focus, without opening panes in every window. */+ sendFirstLocal(frame: Frame): boolean {+ for (const [connId, sink] of this.localClients) {+ if (sink.sendFrame(frame)) return true+ void this.unregisterLocalClient(connId)+ }+ return false+ }+/** Send an up-frame to exactly ONE web connection (E2EE pairing/welcome + targeted RPC replies). */sendTo(connId: string, frame: Frame): void {const direct = this.directDeviceSinks.get(connId)diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 3edeb0733..ec0549086 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -2896,7 +2896,9 @@ async function runForeground(session: AuthSession): Promise<void> {const localWsServer = attachLocalWsServer(hookServer, {// The window and the dial are one desk: opening an agent in the app brings the dial to it, switching// the dial's machine first when the app moved to another one.- onAppFocusState: (machineId, agentId, connId) => {+ onAppFocusState: (machineId, agentId, connId, expectedRevision) => {+ // A delayed automatic selection cannot replace a newer explicit user choice.+ if (expectedRevision && autonomousDeviceService?.focusSnapshot().focusRevision !== expectedRevision) return falseif (agentId === null) {if (appVoiceFocus?.connId === connId) appVoiceFocus = undefined} else appVoiceFocus = { machineId, agentId, connId }@@ -4198,6 +4200,9 @@ async function runForeground(session: AuthSession): Promise<void> {autonomousDeviceService = new AutonomousDeviceService({machineId: backend.machineId,+ requestAppFocus: (agentId, expiresAt, focusRevision) => backend.sendFirstLocal({+ type: 'device_focus', payload: { machineId: backend.machineId, agentId, expiresAt, focusRevision },+ }),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.tsindex 0be094807..de370b7cc 100644--- a/cli/src/lib/autonomous-device/service.spec.ts+++ b/cli/src/lib/autonomous-device/service.spec.ts@@ -12,6 +12,54 @@ function fixture(now?: () => number, fullAnswer?: string) {}describe('Autonomous device local-agent service', () => {+ it('ensures focus through the desktop once for concurrent enables', async () => {+ const requestAppFocus = vi.fn(() => true)+ const submit = vi.fn()+ const service = new AutonomousDeviceService({ machineId: 'machine',+ agents: () => [{ agentId: 'first', name: 'First', engine: 'claude', state: 'idle' }],+ requestAppFocus, submit, stop: async () => true, answer: async () => true,+ cancelDelivery: () => true, recent: () => [] })+ const request = () => service.request('device', { type: 'focus.ensure', requestId: randomUUID() })+ const first = request(), second = request()+ expect(requestAppFocus).toHaveBeenCalledTimes(1)+ expect(requestAppFocus.mock.calls[0]).toEqual(['first', expect.any(Number), expect.any(String)])+ expect(service.focusSnapshot().focus).toBeNull()+ // A user selection wins over the suggested first agent, even on another machine.+ service.appFocus('remote', 'chosen', 'window')+ expect((await first).focus).toEqual({ machineId: 'remote', agentId: 'chosen' })+ expect((await second).focus).toEqual({ machineId: 'remote', agentId: 'chosen' })+ await request()+ expect(requestAppFocus).toHaveBeenCalledTimes(1)+ expect(submit).not.toHaveBeenCalled()+ })++ it('requires an app acknowledgment and never invents headless focus', async () => {+ const f = fixture()+ const request = { type: 'focus.ensure', requestId: randomUUID() }+ expect((await f.service.request('device', request)).error).toMatchObject({ code: 'FOCUS_UNAVAILABLE' })+ expect(f.service.focusSnapshot().focus).toBeNull()+ const empty = new AutonomousDeviceService({ machineId: 'machine', agents: () => [],+ submit: vi.fn(), stop: async () => true, answer: async () => true,+ cancelDelivery: () => true, recent: () => [] })+ expect((await empty.request('device', request)).error).toMatchObject({ code: 'NO_AGENTS' })+ })++ it('expires unacknowledged focus requests without retrying', async () => {+ vi.useFakeTimers()+ try {+ const requestAppFocus = vi.fn(() => true)+ const service = new AutonomousDeviceService({ machineId: 'machine',+ agents: () => [{ agentId: 'first', name: 'First', engine: 'claude', state: 'idle' }],+ requestAppFocus, submit: vi.fn(), stop: async () => true, answer: async () => true,+ cancelDelivery: () => true, recent: () => [] })+ const pending = service.request('device', { type: 'focus.ensure', requestId: randomUUID() })+ await vi.advanceTimersByTimeAsync(2001)+ expect((await pending).error).toMatchObject({ code: 'FOCUS_UNAVAILABLE' })+ expect(requestAppFocus).toHaveBeenCalledTimes(1)+ expect(service.focusSnapshot().focus).toBeNull()+ } finally { vi.useRealTimers() }+ })+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.tsindex 4cd947d7e..e64ae8496 100644--- a/cli/src/lib/autonomous-device/service.ts+++ b/cli/src/lib/autonomous-device/service.ts@@ -12,6 +12,7 @@ export interface AutonomousDeviceDelivery { deliveryId: string; sessionId: strinexport interface AutonomousDeviceServiceOptions {machineId: string; serverInstanceId?: string; now?: () => numberagents: () => AutonomousDeviceAgent[]+ requestAppFocus?: (agentId: string, expiresAt: number, focusRevision: string) => booleansubmit: (agentId: string, text: string, deliveryId: string) => voidcancelDelivery: (deliveryId: string) => booleanstop: (agentId: string) => Promise<boolean>@@ -29,7 +30,7 @@ export interface AutonomousDeviceServiceOptions {emit?: (frame: AutonomousDeviceFrame) => void}interface Entry { deviceId: string; digest: string; receipt: AutonomousDeviceReceipt }-const CAPABILITIES = ['focus.get', 'agents.list', 'turn.send', 'turn.stop', 'status', 'recap', 'question.answer', 'receipt.get'] as const+const CAPABILITIES = ['focus.get', 'focus.ensure', 'agents.list', 'turn.send', 'turn.stop', 'status', 'recap', 'question.answer', 'receipt.get'] as constexport const AUTONOMOUS_DEVICE_CAPABILITIES: string[] = [...CAPABILITIES]const MUTATIONS = new Set(['turn.send', 'turn.stop', 'question.answer'])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@@ -81,6 +82,31 @@ export class AutonomousDeviceService {return { focus: this.focused ? { ...this.focused, ...(agent ? { name: agent.name } : {}) } : null,focusRevision: `${this.serverInstanceId}:${this.focusCounter}` }}+ private ensuringFocus: Promise<ReturnType<AutonomousDeviceService['focusSnapshot']>> | undefined++ /** Enable-time fallback only. The desktop must acknowledge its selected pane. */+ private ensureFocus(): Promise<ReturnType<AutonomousDeviceService['focusSnapshot']>> {+ const current = this.focusSnapshot()+ if (current.focus) return Promise.resolve(current)+ 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+ 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 })+ return this.ensuringFocus+ }++ private async waitForAppFocus(expiresAt: number): Promise<ReturnType<AutonomousDeviceService['focusSnapshot']>> {+ for (;;) {+ const snapshot = this.focusSnapshot()+ if (snapshot.focus) return snapshot+ if (Date.now() >= expiresAt) fail('FOCUS_UNAVAILABLE', 'Harness Desktop did not acknowledge focus')+ await new Promise(resolve => setTimeout(resolve, 20))+ }+ }constructor(private readonly options: AutonomousDeviceServiceOptions) {this.serverInstanceId = options.serverInstanceId ?? randomUUID()this.now = options.now ?? Date.now@@ -189,7 +215,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'].includes(type) ? [] : type === 'receipt.get' ? ['idempotencyKey'] : ['machineId', 'agentId']),+ const allowed = ['type', 'requestId', ...(['agents.list', 'focus.get', 'focus.ensure'].includes(type) ? [] : type === 'receipt.get' ? ['idempotencyKey'] : ['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') {@@ -197,6 +223,7 @@ export class AutonomousDeviceService {return response({ receipt: this.receipt(deviceId, String(req.idempotencyKey)) })}if (type === 'focus.get') return response(this.focusSnapshot())+ if (type === 'focus.ensure') return response(await this.ensureFocus())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 => ({ ...a, machineId: this.options.machineId })) })if (typeof req.agentId !== 'string' || !req.agentId || typeof req.machineId !== 'string') fail('MISSING_TARGET', 'machineId and agentId are required')diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.tsindex a2538b19c..c3bcd292b 100644--- a/cli/src/localWsServer.spec.ts+++ b/cli/src/localWsServer.spec.ts@@ -199,6 +199,25 @@ describe('local CLI WebSocket', () => {expect(states[2]).toEqual(states[1])})+ it('keeps stale automatic focus off the dial and forwards its revision for validation', async () => {+ const backend = new FakeBackend()+ const focus = vi.fn(() => false), dial = vi.fn()+ server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })+ local = attachLocalWsServer(server, { machineId, backend, onAppFocusState: focus, onAppFocus: dial })+ await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve))+ const ws = new WebSocket(`ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/local-ws`)+ await onceOpen(ws)+ const connected = onceMessage(ws)+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))+ await connected+ ws.send(JSON.stringify({ type: 'app_focus', payload: { agentId: 'first', focusRevision: 'old:0' } }))+ await vi.waitFor(() => expect(focus).toHaveBeenCalledTimes(1))+ expect(focus).toHaveBeenCalledWith(machineId, 'first', expect.any(String), 'old:0')+ expect(dial).not.toHaveBeenCalled()+ expect(backend.frames).toHaveLength(0)+ ws.close()+ })+it('carries the window\'s answer about a spoken task, and keeps it off the wire', async () => {const backend = new FakeBackend()const replies: Array<{ voiceId: string; reply: unknown }> = []diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex e05853d57..5cc3760b6 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -41,7 +41,7 @@ export interface LocalWsServerOptions {/** The desktop app opened an agent's terminal — which agent, and on which machine. Lets the dial follow* the window, so the two screens stay one desk. *//** Explicit app focus, including clear/disconnect, for voice routing independent of the dial. */- onAppFocusState?: (machineId: string, agentId: string | null, connId: string) => void+ onAppFocusState?: (machineId: string, agentId: string | null, connId: string, expectedRevision?: string) => unknownonAppFocus?: (machineId: string, agentId: string) => void/** Every agent the window currently has a tile for, across all its machines. */onAppPanes?: (agentIds: string[]) => void@@ -363,7 +363,9 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOconst agentId = (moved?.payload as Record<string, unknown> | undefined)?.agentIdif (moved?.type === 'app_focus') {if (agentId === null || (typeof agentId === 'string' && agentId)) {- options.onAppFocusState?.(boundMachineId, agentId, connId)+ const revision = (moved.payload as Record<string, unknown>)?.focusRevision+ if (options.onAppFocusState?.(boundMachineId, agentId, connId,+ typeof revision === 'string' ? revision : undefined) === false) returnif (agentId) options.onAppFocus?.(boundMachineId, agentId)}// Focus is local desk state and must never be forwarded to a remote machine.diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex a28accf4c..0d35d99ca 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1115,6 +1115,7 @@ class AppNotifier extends ChangeNotifier {}String? _announcedFocusMachineId;+ String? _deviceFocusRevision;@visibleForTestingFuture<bool> Function(String machineId, String? agentId)?@@ -1142,6 +1143,7 @@ class AppNotifier extends ChangeNotifier {? send(machineId, agentId): _pool?[machineId]?.sendTerminalFrame('app_focus', {'agentId': agentId,+ if (_deviceFocusRevision != null) 'focusRevision': _deviceFocusRevision,});if (pending != null) unawaited(pending.catchError((_) => false));}@@ -3868,6 +3870,38 @@ class AppNotifier extends ChangeNotifier {await addAgentToSwarm(machineId, agentId);}+ /// Enable-time fallback: preserve the user's current choice and acknowledge it.+ /// Selection records focus before waiting for terminal attachment, so a later+ /// user click is never overwritten by completion of an asynchronous open.+ Future<void> ensureDeviceFocus(Map<String, dynamic> payload) async {+ final expiresAt = payload['expiresAt'];+ final machineId = payload['machineId'];+ final agentId = payload['agentId'];+ final focusRevision = payload['focusRevision'];+ if (expiresAt is! num ||+ expiresAt <= DateTime.now().millisecondsSinceEpoch ||+ machineId is! String ||+ agentId is! String ||+ agentId.isEmpty ||+ focusRevision is! String ||+ focusRevision.isEmpty) {+ return;+ }+ if (focusedPane?.agentId != null) {+ _announceAppFocus();+ return;+ }+ // Tag only the synchronous fallback announcement, never a later user click.+ late Future<void> selection;+ _deviceFocusRevision = focusRevision;+ try {+ selection = selectAgent(machineId, agentId);+ } finally {+ _deviceFocusRevision = null;+ }+ await selection;+ }+/// The dial turned to an agent. Ordinary selection, the same path a click on the rail takes.////// It used to take a `DeskEdge` and, for an agent with no tile, replace the pane at that end — the@@ -4801,6 +4835,9 @@ class AppNotifier extends ChangeNotifier {(payload['velocity'] as num?)?.round() ?? 0,);break;+ case 'device_focus':+ unawaited(ensureDeviceFocus(payload));+ break;case 'dial_focus':// Turning the dial to an agent brings that agent's terminal up here — the ordinary selection// path, the same one a click on the rail takes, failing the same way for a missing terminal,diff --git a/desktop/test/terminal_pane_test.dart b/desktop/test/terminal_pane_test.dartindex 1d2e16556..e8f34f913 100644--- a/desktop/test/terminal_pane_test.dart+++ b/desktop/test/terminal_pane_test.dart@@ -117,6 +117,41 @@ void main() {});tearDown(() => app.dispose());+ test('device fallback opens and announces the candidate', () async {+ await app.ensureDeviceFocus({+ 'machineId': 'm1',+ 'agentId': 'a',+ 'focusRevision': 'instance:0',+ 'expiresAt': DateTime.now().millisecondsSinceEpoch + 2000,+ });+ expect(app.focusedPane?.agentId, 'a');+ expect(frames.last, ('m1', 'a'));+ });++ test('device fallback preserves an existing remote selection', () async {+ await app.assignAgentToPane(null, 'm2', 'c');+ frames.clear();+ await app.ensureDeviceFocus({+ 'machineId': 'm1',+ 'agentId': 'a',+ 'focusRevision': 'instance:0',+ 'expiresAt': DateTime.now().millisecondsSinceEpoch + 2000,+ });+ expect(app.focusedPane?.agentId, 'c');+ expect(frames, [('m2', 'c')]);+ });++ test('expired device fallback never opens a pane', () async {+ await app.ensureDeviceFocus({+ 'machineId': 'm1',+ 'agentId': 'a',+ 'focusRevision': 'instance:0',+ 'expiresAt': DateTime.now().millisecondsSinceEpoch - 1,+ });+ expect(app.focusedPane, isNull);+ expect(frames, isEmpty);+ });+test('closing focused pane selects replacement, then clears last pane', () async {await app.assignAgentToPane(null, 'm1', 'a');await app.assignAgentToPane(null, 'm1', 'b');diff --git a/docs/autonomous-device-integration.md b/docs/autonomous-device-integration.mdindex efcc444d5..0c6136248 100644--- a/docs/autonomous-device-integration.md+++ b/docs/autonomous-device-integration.md@@ -125,6 +125,7 @@ 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` || `agents.list` | none | `machineId,agents:[{machineId,agentId,name,engine,state}]` || `status` | `machineId,agentId` | `machineId,agentId,state,openQuestion:null\|{requestId,questions}` |@@ -243,3 +244,18 @@ Full CLI regression passed: `npm test -- --maxWorkers=1 --testTimeout=30000 --hoThe 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.diff --git a/docs/vi/autonomous-device-integration_vi.md b/docs/vi/autonomous-device-integration_vi.mdindex fb0c6b1c6..172473785 100644--- a/docs/vi/autonomous-device-integration_vi.md+++ b/docs/vi/autonomous-device-integration_vi.md@@ -94,3 +94,18 @@ session đã xác thực và app-ready, không đếm socket thô. Full CLI đã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ôngsử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.