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.

fix(device): reveal prepared agents and unblock first-turn readiness (#247)

Leocf8d57f30081
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 5ec43f7f6..525b1e806 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -1701,6 +1701,7 @@ async function runForeground(session: AuthSession): Promise<void> {
}
}
let autonomousDeviceDirect: AutonomousDeviceDirect | undefined
+ let deviceStoreRef: ReturnType<typeof createDeviceStore> | undefined
let autonomousDeviceService: AutonomousDeviceService | undefined
let appVoiceFocus: { machineId: string; agentId: string; connId: string } | undefined
let backendRef: BackendSocket | undefined
@@ -3652,6 +3653,7 @@ async function runForeground(session: AuthSession): Promise<void> {
shareRelay,
// 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.
+ onDevicePrepareOpened: (operationId, agentId) => deviceStoreRef?.acknowledgeReveal(operationId, agentId),
onAppFocusState: (machineId, agentId, connId, expectedRevision) => {
// A delayed automatic selection cannot replace a newer explicit user choice.
if (expectedRevision && autonomousDeviceService?.focusSnapshot().focusRevision !== expectedRevision) return false
@@ -5443,7 +5445,12 @@ async function runForeground(session: AuthSession): Promise<void> {
const cable = new CableSession(cableHost, new DialLog(env.HARNESS_LOGS_DIR))
cableRef = cable
- const deviceStore = createDeviceStore({ dataDir: env.ADAPTER_DATA_DIR, machineId: backend.machineId, create: input => backend.onCreateAgent!(input) })
+ const deviceStore = createDeviceStore({ dataDir: env.ADAPTER_DATA_DIR, machineId: backend.machineId,
+ create: input => backend.onCreateAgent!(input),
+ reveal: (operationId, agentId) => { backend.sendFirstLocal({ type: 'device_prepare_open', payload: { operationId, machineId: backend.machineId, agentId } }) },
+ })
+ deviceStoreRef = deviceStore
+ deviceStore.startUiDelivery()
autonomousDeviceService = new AutonomousDeviceService({
store: deviceStore,
machineId: backend.machineId,
diff --git a/cli/src/lib/autonomous-device/store.spec.ts b/cli/src/lib/autonomous-device/store.spec.ts
index ffe9e1d4c..a08a70c55 100644
--- a/cli/src/lib/autonomous-device/store.spec.ts
+++ b/cli/src/lib/autonomous-device/store.spec.ts
@@ -23,7 +23,7 @@ function fixture(installed = true) {
create: vi.fn(async () => {
agents.push({ agentId: 'agent1', machineId: 'mac', packageId: pkg.packageId, workspace: '/projects/airplane', engine: 'claude', state: 'idle', runtime: 'ready' })
return { state: 'created' as const, agentId: 'agent1' }
- }), agents: () => agents,
+ }), agents: () => agents, reveal: vi.fn(),
}
const store = new AutonomousDeviceStore(deps)
const prepare = (key = 'airplane', extra: Record<string, unknown> = {}) => store.request('lamp', request('agent.prepare', {
@@ -37,6 +37,47 @@ function fixture(installed = true) {
return { deps, pkg, agents, store, prepare, settled, id, directory }
}
describe('device Store durable preparation', () => {
+ it('reveals before readiness, retries delivery, and persists the UI ack across restart', async () => {
+ const f = fixture()
+ f.deps.create.mockImplementationOnce(async () => {
+ f.agents.push({ agentId: 'agent1', machineId: 'mac', packageId: f.pkg.packageId,
+ workspace: '/projects/airplane', engine: 'claude', state: 'active', runtime: 'starting' })
+ return { state: 'created', agentId: 'agent1' }
+ })
+ const id = f.id(await f.prepare())
+ await vi.waitFor(() => expect(f.deps.reveal).toHaveBeenCalledWith(id, 'agent1'))
+ expect(f.store.get('lamp', id)).toMatchObject({ state: 'running', taskDispatched: false })
+ f.store.acknowledgeReveal(id, 'wrong-agent')
+ f.deps.reveal.mockClear()
+ f.store.get('lamp', id)
+ expect(f.deps.reveal).toHaveBeenCalled()
+ f.store.acknowledgeReveal(id, 'agent1')
+ f.deps.reveal.mockClear()
+ await f.prepare()
+ expect(f.deps.reveal).not.toHaveBeenCalled()
+ const restarted = new AutonomousDeviceStore(f.deps)
+ restarted.get('lamp', id)
+ expect(f.deps.reveal).not.toHaveBeenCalled()
+ expect(f.deps.create).toHaveBeenCalledOnce()
+ })
+ it('redelivers an unacknowledged UI intent after restart without another device poll', async () => {
+ const f = fixture()
+ const id = f.id(await f.prepare())
+ await f.settled(id)
+ f.deps.reveal.mockClear()
+ vi.useFakeTimers()
+ const restarted = new AutonomousDeviceStore(f.deps)
+ try {
+ restarted.startUiDelivery()
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(f.deps.reveal).toHaveBeenCalledWith(id, 'agent1')
+ restarted.acknowledgeReveal(id, 'agent1')
+ f.deps.reveal.mockClear()
+ await vi.advanceTimersByTimeAsync(4000)
+ expect(f.deps.reveal).not.toHaveBeenCalled()
+ expect(f.deps.create).toHaveBeenCalledOnce()
+ } finally { restarted.stopUiDelivery(); vi.useRealTimers() }
+ })
it('discovers metadata without claiming readiness or executing doctors/setup', async () => {
const f = fixture(false)
const result = await f.store.request('lamp', request('store.list', { query: 'blender' }))
diff --git a/cli/src/lib/autonomous-device/store.ts b/cli/src/lib/autonomous-device/store.ts
index 1e3586830..2619b7231 100644
--- a/cli/src/lib/autonomous-device/store.ts
+++ b/cli/src/lib/autonomous-device/store.ts
@@ -1,5 +1,5 @@
import { createHash, randomUUID } from 'node:crypto'
-import { closeSync, constants, fsyncSync, openSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { closeSync, constants, fsyncSync, openSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { z } from 'zod'
import { AgentCreationReceipts, creationFingerprint, type AgentCreationOutcome } from '../agentCreationReceipt.js'
@@ -23,9 +23,11 @@ export interface DeviceStoreDependencies {
workspace(request: PrepareRequest['workspace'], label: string): Promise<string>
create(packageId: string, cwd: string): Promise<AgentCreationOutcome>
agents(): StoreAgent[]
+ reveal?: (operationId: string, agentId: string) => void
now?: () => number
}
const JournalSchema = z.strictObject({
+ uiRevealed: z.boolean().optional(),
version: z.literal(1), owner: z.string(), fingerprint: z.string(), operation: DeviceOperationSchema,
})
type Journal = z.infer<typeof JournalSchema>
@@ -44,11 +46,55 @@ export class AutonomousDeviceStore {
private readonly checks = new Map<string, { state: 'passed' | 'failed' | 'unknown'; checkedAt: number; version: string | null; lines: string[] }>()
private readonly revoked = new Set<string>()
private readonly workspaces = new Map<string, string>()
+ private uiTimer?: ReturnType<typeof setInterval>
+ private readonly pendingUi = new Set<string>()
private readonly now: () => number
constructor(private readonly deps: DeviceStoreDependencies) {
this.receipts = new AgentCreationReceipts(join(deps.directory, 'creations'))
this.now = deps.now ?? Date.now
}
+ /** Durable UI delivery, independent of readiness and task delivery. Only local Desktop can ack. */
+ startUiDelivery(): void {
+ if (!this.deps.reveal || this.uiTimer) return
+ try {
+ for (const name of readdirSync(this.deps.directory)) {
+ if (!/^[a-f0-9]{64}\.json$/.test(name)) continue
+ try {
+ const row = this.read(name.slice(0, -5))
+ if (row?.operation.agentId && !row.uiRevealed) this.pendingUi.add(row.operation.operationId)
+ } catch { /* A corrupt record must not block other UI intents. */ }
+ }
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error }
+ this.uiTimer = setInterval(() => this.deliverUi(), 2000)
+ this.uiTimer.unref()
+ }
+ stopUiDelivery(): void { clearInterval(this.uiTimer); this.uiTimer = undefined }
+ acknowledgeReveal(operationId: string, agentId: string): void {
+ if (!this.pendingUi.has(operationId)) return
+ const row = this.read(operationId)
+ if (!row || row.operation.agentId !== agentId || this.revoked.has(operationId)) return
+ const next = { ...row, uiRevealed: true }
+ this.save(next)
+ row.uiRevealed = true
+ this.pendingUi.delete(operationId)
+ }
+ private queueReveal(row: Journal): void {
+ if (!this.deps.reveal || !row.operation.agentId || row.uiRevealed || this.revoked.has(row.operation.operationId)) return
+ this.pendingUi.add(row.operation.operationId)
+ this.deliverUi()
+ }
+ private deliverUi(): void {
+ for (const id of this.pendingUi) {
+ try {
+ const row = this.read(id)
+ if (!row || row.uiRevealed || this.revoked.has(id)) { this.pendingUi.delete(id); continue }
+ const agent = this.deps.agents().find(a => a.agentId === row.operation.agentId)
+ if (agent && agent.packageId === row.operation.packageId && agent.workspace === row.operation.workspace) {
+ this.deps.reveal?.(id, agent.agentId)
+ }
+ } catch { /* A disconnected UI must never fail preparation or replay creation. */ }
+ }
+ }
private file(id: string) { return join(this.deps.directory, `${id}.json`) }
private save(row: Journal, exclusive = false): void {
secureStateDirectory(this.deps.directory)
@@ -209,13 +255,14 @@ export class AutonomousDeviceStore {
return this.deps.create(req.packageId, cwd)
})
if (result.state === 'created') {
- this.change(row, { phase: 'launch', agentId: result.agentId, guidance: 'Waiting for the native engine conversation. Open this agent in Harness if login or trust prompts need attention.' })
+ this.change(row, { phase: 'launch', agentId: result.agentId, guidance: 'Waiting for the engine process. Harness Desktop will reveal this agent for any login or trust prompts.' })
} else if (result.state === 'failed') {
this.action(row, result.error, result.detail ?? result.error, 'Open Harness on this machine to resolve the engine/workspace error.'); return
} else {
this.action(row, 'CREATION_UNCONFIRMED', 'Agent creation may have executed; it will not be repeated', 'Inspect existing agents on this machine before starting anything else.'); return
}
this.authorized(row)
+ this.queueReveal(row)
this.refreshRuntime(row)
}
private refreshRuntime(row: Journal): void {
@@ -228,7 +275,7 @@ export class AutonomousDeviceStore {
if (agent.runtime === 'ready') {
if (row.operation.state !== 'ready') this.change(row, { state: 'ready', phase: 'complete', error: null, guidance: null })
} else if (agent.runtime === 'starting' && row.operation.state === 'ready') {
- this.change(row, { state: 'running', phase: 'launch', guidance: 'The engine is starting again; wait for its native conversation before sending a task.' })
+ this.change(row, { state: 'running', phase: 'launch', guidance: 'The engine is starting again; wait for its launch readiness before sending a task.' })
} else if (agent.runtime === 'unavailable' || this.now() - row.operation.updatedAt > 10 * 60_000) {
this.action(row, 'ENGINE_ACTION_REQUIRED', agent.error ?? 'Engine launch is not ready; login, trust or installation may require interaction.', 'Open the returned agent in Harness and complete its engine prompts. Do not create another agent automatically.')
}
@@ -245,6 +292,7 @@ export class AutonomousDeviceStore {
this.action(row, 'RECOVERY_REQUIRED', 'Daemon restarted during preparation; no install or creation will be replayed.', 'Inspect Harness and the workspace on this machine. Retry this same key to read its status; only deliberately use a new key after reconciling any side effects.')
}
}
+ this.queueReveal(row)
this.refreshRuntime(row)
return structuredClone(row.operation)
}
diff --git a/cli/src/lib/autonomous-device/storeRuntime.spec.ts b/cli/src/lib/autonomous-device/storeRuntime.spec.ts
index 645df8df3..16529c0ec 100644
--- a/cli/src/lib/autonomous-device/storeRuntime.spec.ts
+++ b/cli/src/lib/autonomous-device/storeRuntime.spec.ts
@@ -13,7 +13,7 @@ import * as engineLaunch from '../engineLaunch.js'
import { installDsh } from '../../dsh/install.js'
import { installedDsh, invalidateInstalledDsh } from '../../dsh/installed.js'
import { materializeWorkspace } from '../../dsh/materialize.js'
-import { createDeviceStore, deviceStorePackages } from './storeRuntime.js'
+import { createDeviceStore, deviceStorePackages, deviceStoreAgents } from './storeRuntime.js'
import { DeviceStoreResultSchema } from './storeContract.js'
import { HARNESS_MONOREPO } from '../../dsh/registry.js'
@@ -48,6 +48,18 @@ async function setup() {
return { source, cwd, create, store, request }
}
describe('device Store production adapter with real local package scripts', () => {
+ it('accepts confirmed launch readiness before the first native conversation exists', () => {
+ const session = { agentId: 'fresh', sessionId: '', active: true, engine: 'claude', cwd: root,
+ dsh: null, launch: { state: 'ready' } } as RegisteredSession
+ state.agents = [session]
+ expect(deviceStoreAgents('mac')[0].runtime).toBe('ready')
+ session.launch = { state: 'starting' }
+ expect(deviceStoreAgents('mac')[0].runtime).toBe('starting')
+ session.launch = { state: 'failed', error: 'ENGINE_FAILED' }
+ expect(deviceStoreAgents('mac')[0].runtime).toBe('unavailable')
+ session.launch = undefined
+ expect(deviceStoreAgents('mac')[0].runtime).toBe('starting')
+ })
it('uses actual installed inventory, doctor and materialization with safe creation arguments', async () => {
const f = await setup()
const reply = await f.store.request('lamp', f.request)
diff --git a/cli/src/lib/autonomous-device/storeRuntime.ts b/cli/src/lib/autonomous-device/storeRuntime.ts
index cf8856cf2..b816c40be 100644
--- a/cli/src/lib/autonomous-device/storeRuntime.ts
+++ b/cli/src/lib/autonomous-device/storeRuntime.ts
@@ -23,7 +23,7 @@ export function deviceStoreAgents(machineId: string): StoreAgent[] {
return registry.list().map(s => ({ agentId: s.agentId, machineId, packageId: s.dsh ? installedDsh(s.dsh)?.id ?? s.dsh : null,
engine: s.engine, workspace: canonicalPath(s.cwd), state: s.active ? 'active' : 'inactive',
runtime: !registry.terminalAvailable(s.agentId) || s.launch?.state === 'failed' ? 'unavailable'
- : s.launch?.state === 'starting' ? 'starting' : s.active ? (s.sessionId || s.engine === 'terminal' ? 'ready' : 'starting') : 'unavailable',
+ : s.launch?.state === 'starting' ? 'starting' : s.active ? (s.launch?.state === 'ready' || s.sessionId || s.engine === 'terminal' ? 'ready' : 'starting') : 'unavailable',
...(s.launch?.state === 'failed' ? { error: s.launch.detail ?? s.launch.error } : {}) }))
}
function trusted(entry: DshRegistryEntry | undefined): boolean {
@@ -53,9 +53,9 @@ export async function deviceStorePackages(): Promise<StorePackage[]> {
})
}
-export function createDeviceStore(options: { dataDir: string; machineId: string; create: NonNullable<BackendSocket['onCreateAgent']> }): AutonomousDeviceStore {
+export function createDeviceStore(options: { dataDir: string; machineId: string; create: NonNullable<BackendSocket['onCreateAgent']>; reveal?: (operationId: string, agentId: string) => void }): AutonomousDeviceStore {
return new AutonomousDeviceStore({
- directory: join(options.dataDir, 'device-preparations'), machineId: options.machineId,
+ directory: join(options.dataDir, 'device-preparations'), machineId: options.machineId, reveal: options.reveal,
packages: deviceStorePackages,
agents: () => deviceStoreAgents(options.machineId),
install: async (id, progress) => {
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
index d57c0d3a3..4e5c5f33f 100644
--- a/cli/src/localWsServer.spec.ts
+++ b/cli/src/localWsServer.spec.ts
@@ -3,7 +3,7 @@ import type { AddressInfo } from 'node:net'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { WebSocket } from 'ws'
import type { Frame, LocalClientSink } from './backendSocket.js'
-import { attachLocalWsServer, type LocalWsBackend, type LocalWsServer } from './localWsServer.js'
+import { attachLocalWsServer, type LocalWsBackend, type LocalWsServer, type LocalWsServerOptions } from './localWsServer.js'
import { encodeTerminalLocal, TerminalBinaryKind, type TerminalBinaryClear } from './lib/terminalBinary.js'
const machineId = 'machine-123'
@@ -59,14 +59,27 @@ describe('local CLI WebSocket', () => {
server = null
})
- async function start(backend: FakeBackend): Promise<string> {
+ async function start(backend: FakeBackend, extra: Partial<LocalWsServerOptions> = {}): Promise<string> {
server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })
- local = attachLocalWsServer(server, { machineId, backend })
+ local = attachLocalWsServer(server, { machineId, backend, ...extra })
await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))
const port = (server.address() as AddressInfo).port
return `ws://127.0.0.1:${port}/api/local-ws`
}
+ it('consumes validated preparation UI acknowledgements locally', async () => {
+ const backend = new FakeBackend(), opened = vi.fn()
+ const ws = new WebSocket(await start(backend, { onDevicePrepareOpened: opened }))
+ 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: 'device_prepare_opened', payload: { operationId: 'invalid', agentId: 'a' } }))
+ ws.send(JSON.stringify({ type: 'device_prepare_opened', payload: { operationId: 'a'.repeat(64), agentId: 'agent1' } }))
+ await vi.waitFor(() => expect(opened).toHaveBeenCalledExactlyOnceWith('a'.repeat(64), 'agent1'))
+ expect(backend.frames).toEqual([])
+ ws.close()
+ })
it('accepts loopback, selects the exact machine, and routes JSON plus HTRL binary', async () => {
const backend = new FakeBackend()
const url = await start(backend)
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index d0a5721a4..abe2e0881 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -53,6 +53,7 @@ export interface LocalWsServerOptions {
* 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, expectedRevision?: string) => unknown
+ onDevicePrepareOpened?: (operationId: string, agentId: string) => void
onAppFocus?: (machineId: string, agentId: string) => void
/** Every agent the window currently has a tile for, across all its machines. */
onAppPanes?: (agentIds: string[]) => void
@@ -351,6 +352,15 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
// to the close at the bottom.
const parsed = isBinary ? null : jsonFrame(raw)
+ // Local desktop acknowledgement only; never forward this through a remote relay.
+ if (parsed?.type === 'device_prepare_opened') {
+ const p = parsed.payload as Record<string, unknown> | undefined
+ if (!relay && boundMachineId === options.machineId && typeof p?.operationId === 'string'
+ && /^[a-f0-9]{64}$/.test(p.operationId) && typeof p.agentId === 'string' && p.agentId.length > 0 && p.agentId.length <= 200) {
+ options.onDevicePrepareOpened?.(p.operationId, p.agentId)
+ }
+ return
+ }
// THE APP MOVED — tell whoever wants to follow it, before the frame is dispatched either way.
// Sniffed here rather than in the backend socket because that path never sees a RELAYED machine's
// frames: those are forwarded upstream a few lines below and would be invisible, which is exactly
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 94163b5d3..30298d18c 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -7979,6 +7979,64 @@ class AppNotifier extends ChangeNotifier {
});
}
+ final _preparationOpens = <String, Future<bool>>{};
+ final _revealedPreparations = <String>{};
+
+ /// Reveal a prepared agent before its engine is ready, so login/trust stays
+ /// interactive. This only opens UI; task delivery belongs to the device.
+ Future<bool> revealPreparedAgent(
+ String machineId,
+ String agentId,
+ String operationId,
+ ) async {
+ final key = '$_authRevision/$machineId/$operationId';
+ if (_revealedPreparations.contains(key)) return true;
+ final agentKey = '$_authRevision/$machineId/$agentId';
+ final pending = _preparationOpens[agentKey];
+ if (pending != null) {
+ final opened = await pending;
+ if (opened) _revealedPreparations.add(key);
+ return opened;
+ }
+ final opening = _openPreparedAgent(machineId, agentId);
+ _preparationOpens[agentKey] = opening;
+ try {
+ final opened = await opening;
+ if (opened) _revealedPreparations.add(key);
+ return opened;
+ } finally {
+ _preparationOpens.remove(agentKey);
+ }
+ }
+
+ Future<bool> _openPreparedAgent(String machineId, String agentId) async {
+ final revision = _authRevision;
+ final machine = machineStates[machineId];
+ if (_disposed || machine == null || !await _awaitAgent(machine, agentId)) {
+ return false;
+ }
+ if (_disposed || revision != _authRevision || !identical(machineStates[machineId], machine)) {
+ return false;
+ }
+ await openAgentFromDial(machineId, agentId);
+ if (_disposed || revision != _authRevision || !identical(machineStates[machineId], machine) ||
+ !allPanes.any(
+ (p) => p.machineId == machineId && p.agentId == agentId,
+ )) {
+ return false;
+ }
+ // Reuse the generic package viewer path, including a late viewerUrl/error.
+ final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
+ if (agent != null) {
+ _dismissedViewers.remove(_viewerKey(machineId, agentId));
+ _syncViewerPane(machine, agent);
+ activeSwarm.zoomedPaneId = null;
+ _persistLayout();
+ notifyListeners();
+ }
+ return true;
+ }
+
/// 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.
@@ -9728,6 +9786,33 @@ class AppNotifier extends ChangeNotifier {
unawaited(_deskFetch());
}
break;
+ case 'device_prepare_open':
+ final operationId = payload['operationId'];
+ final prepareAgentId = payload['agentId'];
+ final prepareMachineId = payload['machineId'];
+ if (operationId is String &&
+ RegExp(r'^[a-f0-9]{64}$').hasMatch(operationId) &&
+ prepareAgentId is String &&
+ prepareAgentId.isNotEmpty &&
+ prepareMachineId == machineId) {
+ unawaited(() async {
+ try {
+ if (await revealPreparedAgent(
+ machineId,
+ prepareAgentId,
+ operationId,
+ )) {
+ await _pool?[machineId]?.sendTerminalFrame(
+ 'device_prepare_opened',
+ {'operationId': operationId, 'agentId': prepareAgentId},
+ );
+ }
+ } catch (error) {
+ appLog.warn('device', 'Could not reveal prepared agent: $error');
+ }
+ }());
+ }
+ break;
case 'dial_open':
// A notification was tapped on the dial. Unlike `dial_focus` this asks for a tile of its own —
// see openAgentFromDial for why a finished turn is not a replacement for what is on screen.
diff --git a/desktop/test/dial_desk_test.dart b/desktop/test/dial_desk_test.dart
index c592fe84c..ee729d697 100644
--- a/desktop/test/dial_desk_test.dart
+++ b/desktop/test/dial_desk_test.dart
@@ -64,6 +64,59 @@ Future<AppNotifier> _withTiles(List<String> agentIds) async {
}
void main() {
+ test(
+ 'preparation retries share one tab and attach its package viewer',
+ () async {
+ final app = _notifier();
+ final machine = _machine(app, 'm1', ['a1']);
+ machine.agents = [
+ Agent.fromJson({
+ 'id': 'a1',
+ 'name': 'a1',
+ 'engine': 'claude',
+ 'viewerUrl': 'http://127.0.0.1:12345',
+ 'terminal': {
+ 'runtimes': [
+ {'backend': 'tmux', 'paneId': '%1'},
+ ],
+ },
+ }),
+ ];
+ try {
+ final results = await Future.wait([
+ app.revealPreparedAgent('m1', 'a1', 'operation1'),
+ app.revealPreparedAgent('m1', 'a1', 'operation1'),
+ app.revealPreparedAgent('m1', 'a1', 'operation2'),
+ ]);
+ expect(results, everyElement(isTrue));
+ expect(app.allPanes.where((p) => p.agentId == 'a1'), hasLength(1));
+ expect(
+ app.allPanes.where((p) => p.isWeb && p.ownerAgentId == 'a1'),
+ hasLength(1),
+ );
+ final tabs = app.swarms.length;
+ await app.revealPreparedAgent('m1', 'a1', 'operation1');
+ expect(app.swarms, hasLength(tabs));
+ } finally {
+ app.dispose();
+ }
+ },
+ );
+ test(
+ 'preparation reveals an existing agent tab without duplicating it',
+ () async {
+ final app = await _withTiles(['a1']);
+ try {
+ final tabs = app.swarms.length;
+ expect(await app.revealPreparedAgent('m1', 'a1', 'operation'), isTrue);
+ expect(app.swarms, hasLength(tabs));
+ expect(app.allPanes.where((p) => p.agentId == 'a1'), hasLength(1));
+ } finally {
+ app.dispose();
+ }
+ },
+ );
+
test('the roster the daemon builds its ring from is in tile order', () {
// The section in the rail, the tile order on screen and the dial's carousel
// are one list. This is the end of it the window owns: what it reports is
diff --git a/docs/autonomous-device-store.md b/docs/autonomous-device-store.md
index f4db40171..3167bd08e 100644
--- a/docs/autonomous-device-store.md
+++ b/docs/autonomous-device-store.md
@@ -89,7 +89,9 @@ Installation done elsewhere may only be reflected when its installed index chang
`runtime` is `starting`, `ready`, or `unavailable`. `workspace` is a canonical absolute directory where
available. `agents.list` also gains optional `packageId`, `workspace`, and `runtime` fields. An absent/
null package identity is unknown, never inferred from recap. Runtime ready requires a live terminal,
-engine process and bound native conversation (plain terminal tiles are a special case). Authentication
+engine process confirmed by the existing launch watcher (`launch.state=ready`), or a bound native
+conversation for discovered agents. A native session ID is NOT required for a freshly launched agent:
+some engines create it only after the first task. Plain terminal tiles are a special case. Authentication
is not independently verified. Caller decides whether a candidate belongs to the user's intended
project; explicit use of that agent goes straight to existing `turn.send` without prepare.
@@ -162,7 +164,7 @@ Poll about every 2 seconds, back off on rate limiting. There is **no new progres
|---|---|
| `accepted` | Intent persisted; nothing should be inferred about install/create yet |
| `running` | Work or engine startup in progress; keep polling the same operation |
-| `ready` | Package preparation completed and the returned agent's runtime/conversation is available; task has NOT been sent |
+| `ready` | Package preparation completed and the returned agent's terminal and engine launch are available; task has NOT been sent |
| `failed` | Definite failure such as package not found; inspect error before a deliberate new attempt |
| `needs_user_action` | Show `error.message` and `guidance`; may mean dependency/login/workspace repair or uncertain side effects; never blindly create again |
@@ -173,7 +175,7 @@ present before ready or alongside an action-needed error: open that agent, do no
No task is dispatched in any state; `taskDispatched` is always false.
Ready is a **preparation** result, not an airplane, tool output, login certification, or model success.
-`engineAuthentication:"unknown"` is explicit. If launch/binding is absent for ten minutes, polling
+`engineAuthentication:"unknown"` is explicit. If engine launch is absent for ten minutes, polling
reports `ENGINE_ACTION_REQUIRED`; a known launch failure reports it sooner. Complete engine prompts
in the returned agent and poll again: the same operation can become ready, without creating again.
If an agent disappears/changes workspace, a previously ready operation can require action again.
@@ -274,3 +276,29 @@ npx tsx scripts/device-store-contract.ts
npx tsx scripts/device-store-contract.ts --check
npx vitest run src/lib/autonomous-device --maxWorkers=1
```
+
+## Desktop reveal after preparation (additive behavior)
+
+As soon as creation yields an `agentId`, before waiting for readiness, the CLI durably requests
+that one local Desktop reveal it. Desktop reuses the existing agent tab or opens one, then uses its
+normal package viewer synchronization (including a viewer URL/error arriving later). Engine login
+and trust prompts remain interactive in that terminal; opening UI neither answers them nor bypasses
+permissions. This is generic for all Store packages.
+
+The internal loopback event is `device_prepare_open` with
+`{operationId,machineId,agentId}`; Desktop acknowledges `device_prepare_opened` with
+`{operationId,agentId}` only after a terminal pane exists. These are NOT device operations or new
+LAN capabilities. The CLI retries every two seconds until acknowledgement, persists that acknowledgement
+in the preparation journal, and restores pending delivery after daemon restart. Concurrent opens are
+joined by machine/agent; repeated operation IDs do not open another tab or repeatedly steal focus.
+A lost acknowledgement may reveal an existing tab again after Desktop restart, but never creates a
+second terminal for that agent. Closing an acknowledged tab does not automatically reopen it.
+
+A compatible Desktop must be running and signed in; while absent, old, or reconnecting, UI delivery
+stays pending. This does not launch/install the Desktop application. Readiness and UI acknowledgement
+are independent: neither proves engine authentication or task success. OS must keep handling login/
+trust requirements honestly. Request/response JSON schemas and capability names are unchanged.
+
+**OS handoff update:** `ready` now accepts confirmed engine launch without waiting for a native
+session ID. Do not send a bootstrap prompt to obtain that ID. Continue sending the user's task only
+once via `turn.send`, with its separate task idempotency key. No UI event dispatches a task.
diff --git a/docs/contracts/autonomous-device-store-v1/VALIDATION.md b/docs/contracts/autonomous-device-store-v1/VALIDATION.md
index d9f72bcc2..f54b20395 100644
--- a/docs/contracts/autonomous-device-store-v1/VALIDATION.md
+++ b/docs/contracts/autonomous-device-store-v1/VALIDATION.md
@@ -44,3 +44,19 @@ verify existing LAN connectivity, confirm all four capabilities in a real Lamp h
discover → inspect → prepare/poll → separate turn.send against Blender. Record actual engine
login/permission prompts and generated artifacts. OS must not report a rendered airplane from
this validation or from preparation reaching ready.
+
+
+## Desktop reveal and first-turn readiness follow-up
+
+- Reproduced the reported Blender block on a real running agent: its terminal displayed the Claude
+ input prompt, the registry had `active=true`, `launch.state=ready`, and `sessionId=""`; preparation
+ remained `running/launch`. No test prompt was sent to force a native session into existence.
+- Runtime readiness now reuses confirmed launch state, with explicit `engineAuthentication=unknown`.
+- Follow-up CLI device/local WebSocket selection: 135 tests passed in 9 files; TypeScript typecheck,
+ CLI build and generated schema check passed.
+- Desktop dial/preparation selection: 21 tests passed. Targeted Flutter analysis passed.
+- UI tests use a fake machine/terminal and assert concurrent opens, existing-tab reuse and one viewer;
+ durable delivery tests use temporary journals and simulated disconnect/restart/acknowledgement.
+ They do not establish a physical robot-to-Desktop end-to-end acceptance run or a rendered airplane.
+- This follow-up changes readiness semantics, but does not change OS JSON schemas or capability names.
+ OS integrators must read the handoff update in both language versions of the contract.
diff --git a/docs/vi/autonomous-device-store_vi.md b/docs/vi/autonomous-device-store_vi.md
index e44ae36f8..213bb7d03 100644
--- a/docs/vi/autonomous-device-store_vi.md
+++ b/docs/vi/autonomous-device-store_vi.md
@@ -75,8 +75,9 @@ hay task cụ thể đều sẵn sàng. Install từ luồng khác được ph
Agent candidate có `{agentId,machineId,packageId,engine,workspace,state,runtime,error?}`.
`runtime` là `starting / ready / unavailable`; workspace là đường dẫn tuyệt đối canonical nếu biết.
`agents.list` cũng thêm các field tùy chọn `packageId,workspace,runtime`. Package null/absent nghĩa là
-không biết, không được suy từ recap. Runtime ready cần terminal sống, engine process và native
-conversation đã bind (terminal thường là ngoại lệ). Xác thực engine chưa được kiểm chứng độc lập.
+không biết, không được suy từ recap. Runtime ready cần terminal sống và engine process được launch watcher xác nhận (`launch.state=ready`),
+hoặc native conversation đã bind đối với agent được discovery. Agent mới không bắt buộc có native
+session ID: một số engine chỉ tạo ID sau task đầu tiên. Terminal thường là ngoại lệ. Xác thực engine chưa được kiểm chứng độc lập.
## 2. Chuẩn bị agent, không giao task
@@ -134,7 +135,7 @@ serverInstanceId hiện có vẫn áp dụng cho task/turn.
|---|---|
| `accepted` | Đã lưu ý định, chưa kết luận install/create xảy ra |
| `running` | Tiếp tục poll operation hiện tại |
-| `ready` | Đã chuẩn bị package và agent runtime/conversation; **chưa giao task** |
+| `ready` | Đã chuẩn bị package và terminal và engine launch; **chưa giao task** |
| `failed` | Lỗi xác định như không có package; kiểm tra trước khi tạo ý định mới |
| `needs_user_action` | Hiển thị error.message + guidance; có thể cần dependency/login/workspace hoặc kết quả thực thi chưa rõ |
@@ -143,7 +144,7 @@ Có thể bỏ qua hoặc lặp các phase khi package đã cài/shared dependen
ready hoặc đang cần thao tác: mở agent đó để xử lý, không tạo thêm.
Ready chỉ xác nhận bước chuẩn bị. Không chứng minh đã dựng máy bay, đã đăng nhập hay model thành công.
-Nếu engine/conversation chưa bind sau 10 phút, polling trả `ENGINE_ACTION_REQUIRED`; lỗi launch đã
+Nếu engine chưa launch thành công sau 10 phút, polling trả `ENGINE_ACTION_REQUIRED`; lỗi launch đã
biết báo sớm hơn. Hoàn tất prompt engine rồi poll lại có thể đưa cùng operation về ready. Agent biến
mất/đổi workspace khiến operation previously-ready trở thành cần thao tác.
@@ -228,3 +229,27 @@ cd cli
npx tsx scripts/device-store-contract.ts --check
npx vitest run src/lib/autonomous-device --maxWorkers=1
```
+
+## Tự mở Desktop sau khi chuẩn bị agent
+
+Ngay khi có `agentId`, trước readiness, CLI lưu yêu cầu mở/reveal agent trên một Desktop local.
+Desktop tái sử dụng tab đã có hoặc mở một tab, rồi dùng cơ chế viewer chung của package, kể cả khi
+viewer URL/lỗi đến sau. Terminal cho phép người dùng xử lý login/trust; mở UI không tự trả lời,
+không bypass quyền và không gửi task. Áp dụng mọi Store package.
+
+Event loopback nội bộ `device_prepare_open` mang `{operationId,machineId,agentId}`. Desktop xác nhận
+bằng `device_prepare_opened` với `{operationId,agentId}` khi đã có terminal pane. Đây không phải
+operation device hay capability LAN mới. CLI retry mỗi hai giây đến khi nhận xác nhận, lưu xác nhận
+vào journal và khôi phục yêu cầu còn chờ sau daemon restart. Các lần mở đồng thời được gộp theo
+machine/agent; cùng operation không tạo tab trùng hoặc liên tục giành focus. Nếu mất xác nhận rồi
+Desktop restart, có thể reveal lại tab cũ nhưng không tạo terminal thứ hai. Tab đã xác nhận rồi
+được người dùng đóng sẽ không tự mở lại.
+
+Desktop tương thích phải đang chạy và đăng nhập. Nếu app chưa mở, quá cũ hoặc đang reconnect,
+yêu cầu UI tiếp tục chờ; cơ chế này không cài hay khởi chạy ứng dụng Desktop. Readiness độc lập với
+xác nhận mở UI; cả hai không chứng minh engine đã login hoặc task thành công. JSON schemas và tên
+capability/operation phía OS không đổi.
+
+**Cập nhật bàn giao OS:** `ready` chấp nhận engine launch đã xác nhận mà không chờ native session ID.
+Không gửi prompt mồi để lấy ID. OS vẫn gửi task thật đúng một lần qua `turn.send`, với idempotency key
+riêng. Event mở UI không giao task.