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.

feat(notify): tell phones turn tiers and agent questions over relay

tonye6f31dc33c6d
diff --git a/cli/e2e/questionsPhone.e2e.ts b/cli/e2e/questionsPhone.e2e.ts
new file mode 100644
index 000000000..d240d9e50
--- /dev/null
+++ b/cli/e2e/questionsPhone.e2e.ts
@@ -0,0 +1,100 @@
+/**
+ * An agent's question reaches the owner's phone away from the desk (core/questions.ts `sendRemote`), on the
+ * real daemon signed in on the fake backend, with the phone paired and reaching it through the fake relay
+ * (harness/relayPhone.ts) and no window on the computer. The question crosses the relay sealed, as a recap
+ * does (lib/e2ee/manager.ts `SEALED_FOR_WEB`); the phone's answer is the one the agent gets, and the close
+ * that follows reaches the phone too. A phone that connects while a question is open is told it again, and
+ * then which questions are open at all, so one that was here before lets go of what was answered meanwhile.
+ *
+ * Nothing here reaches beyond this machine: the daemon's every server setting is the fake backend's.
+ */
+import { mkdirSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient } from './harness/client.js'
+import { until } from './harness/daemon.js'
+import { startPhoneMachine, type PhoneMachine } from './harness/fleet.js'
+import { RelayPhone, type PhoneFrame } from './harness/relayPhone.js'
+
+const QUESTION = 'Which drink would you like?'
+
+const row = async (client: LocalClient, agentId: string) =>
+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)
+ .find((agent) => agent.id === agentId)
+
+describe('an agent asks a question, and the phone away from the desk hears it', () => {
+ let world: PhoneMachine | undefined
+ let phone: RelayPhone | undefined
+ afterEach(async () => {
+ phone?.close()
+ await world?.close()
+ world = undefined; phone = undefined
+ })
+
+ it('sealed over the relay with no window here; the phone\'s answer is the one the agent gets, and the close follows', async () => {
+ const w = await startPhoneMachine()
+ world = w
+ const { backend, machine } = w
+ onTestFailed(() => {
+ console.log(`---- daemon log\n${machine.daemon.log().split('\n').slice(-150).join('\n')}`)
+ console.log(`---- fake backend saw\n${backend.seen.slice(-40).join('\n')}`)
+ })
+ // A window makes the agent, then goes: from here only the phone can answer, which is what has the daemon
+ // watch the pane for a question at all (core/main.ts `someoneCanAnswer`).
+ const desk = await LocalClient.connect(machine.daemon, { machineId: machine.machineId })
+ const cwd = join(machine.daemon.projectsDir, 'ask-phone')
+ mkdirSync(cwd, { recursive: true })
+ const created = await desk.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 60_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agentId: string = created.agent.id
+ const agent = await until('the agent to bind its conversation', async () => {
+ const found = await row(desk, agentId)
+ return found?.sessionId ? found : null
+ }, 45_000, 500)
+ desk.close()
+
+ phone = new RelayPhone({ backend, machineId: machine.machineId, identity: w.phone.identity, machinePub: machine.identity.pub, token: w.phone.token })
+ await until('the machine to be on the relay', () => backend.nodeUp(machine.machineId) || null, 30_000)
+ await phone.open(30_000)
+ const isQuestion = (frame: PhoneFrame) => frame.type === 'commander_question' && frame.agentId === agentId
+ const asked = phone.next(isQuestion, 45_000, 'commander_question')
+ expect(phone.send('message', { agentId, content: '!ask' })).toBe(true)
+ const question = await asked
+ const shaped = question.payload?.questions?.[0]
+ expect(shaped?.q).toBe(QUESTION)
+ expect(shaped?.options).toEqual(expect.arrayContaining(['Tea', 'Coffee']))
+ const requestId: string = question.payload?.requestId
+ expect(question.payload?.notification).toEqual({ id: requestId, kind: 'needsYou' })
+
+ // On the wire the relay carried ciphertext: the question and its options are nowhere in it.
+ const relayed = backend.webReceived.get(phone.connId!) ?? []
+ const wire = relayed.find((frame) => frame.type === 'commander_question' && frame.agentId === agentId)
+ expect(wire?.payload).toHaveProperty('__e2e')
+ expect(JSON.stringify(relayed)).not.toContain(QUESTION)
+
+ // A phone connecting while it is open is told it again, the same request, then which are open at all.
+ const sessionBefore = phone.frames.length
+ await phone.open(30_000)
+ const again = await phone.waitFor(isQuestion, 30_000, 'the question again', sessionBefore)
+ expect(again.payload?.requestId).toBe(requestId)
+ const open = await phone.waitFor((frame) => frame.type === 'commander_questions_open', 30_000, 'commander_questions_open', sessionBefore)
+ expect(open.payload?.requestIds).toEqual([requestId])
+
+ // The phone answers; the agent gets that answer, and the phone hears the question close.
+ // An answer goes back under the question's own request id (not a request's of its own), as in questions.e2e.ts.
+ const closed = phone.next((frame) => frame.type === 'commander_question_close' && frame.agentId === agentId, 45_000, 'commander_question_close')
+ const answered = phone.next((frame) => frame.type === 'question_response_result' && frame.payload?.requestId === requestId, 45_000, 'question_response_result')
+ expect(phone.send('question_response', { requestId, agentId, answers: { [QUESTION]: 'Coffee' } })).toBe(true)
+ const result = (await answered).payload ?? {}
+ expect(result.error, JSON.stringify(result)).toBeUndefined()
+ expect((await closed).payload?.requestId).toBe(requestId)
+ await until('the agent to get the answer', async () => (await machine.daemon.capture(agent.tmuxPane)).includes('you chose Coffee') || null, 30_000, 500)
+
+ // Asked of nobody now: a phone connecting is told no question is open.
+ const sessionAfter = phone.frames.length
+ await phone.open(30_000)
+ const none = await phone.waitFor((frame) => frame.type === 'commander_questions_open', 30_000, 'commander_questions_open', sessionAfter)
+ expect(none.payload?.requestIds).toEqual([])
+ expect(phone.frames.slice(sessionAfter).some(isQuestion)).toBe(false)
+ })
+})
diff --git a/cli/e2e/recapsCompat.e2e.ts b/cli/e2e/recapsCompat.e2e.ts
index 5375ad9b4..b7d6d319a 100644
--- a/cli/e2e/recapsCompat.e2e.ts
+++ b/cli/e2e/recapsCompat.e2e.ts
@@ -25,7 +25,11 @@ import { FakeDial, type DialMessage } from './harness/fakeDial.js'
const FROM = process.env.COMPAT_FROM
/** Differences on purpose, by key, each with why. */
-const CHANGED: Record<string, string> = {}
+const CHANGED: Record<string, string> = {
+ // A device watches in this scenario, so the recaps decide each news turn's tier and the windows' recap
+ // carries it as `payload.tier`, which the phone announces by (services/recaps.ts).
+ 'window turn_summary': 'carries the tier the recaps decide once for every screen',
+}
/** Types that one run may hear and the other not, by timing alone, each with why. */
const TIMING: Record<string, string> = {
diff --git a/cli/src/backendSocket.guest.spec.ts b/cli/src/backendSocket.guest.spec.ts
index 3a5189306..b250fb334 100644
--- a/cli/src/backendSocket.guest.spec.ts
+++ b/cli/src/backendSocket.guest.spec.ts
@@ -130,4 +130,14 @@ describe('a guest session', () => {
['agent_synced', undefined], ['machines_changed', undefined],
])
})
+
+ it('hears a question about its own harness sent to the apps away from this desk; the owner\'s goes to the group only', () => {
+ const { socket, gw } = session('[email protected]')
+ socket.agentGuest = (agentId) => (agentId === 'mine' ? '[email protected]' : null)
+ const broadcast = vi.spyOn(gw, 'broadcast')
+ socket.sendRemote({ type: 'commander_question', agentId: 'mine', payload: { requestId: 'q1' } })
+ socket.sendRemote({ type: 'commander_question', agentId: 'owners', payload: { requestId: 'q2' } })
+ expect(broadcast.mock.calls.map(([frame, guest]) => [(frame.payload as { requestId?: unknown }).requestId, guest]))
+ .toEqual([['q1', '[email protected]'], ['q2', undefined]])
+ })
})
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index c8b262422..f55061aed 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -2580,6 +2580,68 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('re-announces to an app that joins: once per web session, never for a device, and a failing replay costs only itself', async () => {
+ const socket = relaySocket('token')
+ const joined = vi.fn()
+ socket.fromGateway.client('r0', { role: 'web', label: null, identity: 'PUB', direct: false })
+ socket.onRemoteAppJoined = joined
+ socket.fromGateway.client('d1', { role: 'device', label: null, identity: 'DEV', direct: false })
+ expect(joined).not.toHaveBeenCalled()
+ socket.fromGateway.client('r1', { role: 'web', label: null, identity: 'PUB', direct: false })
+ // The same session said again (a label it was paired under, learned later) is not a second arrival.
+ socket.fromGateway.client('r1', { role: 'web', label: 'Phone', identity: 'PUB', direct: false })
+ expect(joined).toHaveBeenCalledTimes(1)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ socket.onRemoteAppJoined = () => { throw new Error('replay broke') }
+ socket.fromGateway.client('r2', { role: 'web', label: null, identity: 'PUB2', direct: false })
+ socket.onRemoteAppJoined = () => { throw 'not an error' }
+ socket.fromGateway.client('r3', { role: 'web', label: null, identity: 'PUB3', direct: false })
+ expect(warn.mock.calls.map(([line]) => line)).toEqual([
+ '[backend] re-announcing to a remote app failed: replay broke',
+ '[backend] re-announcing to a remote app failed: not an error',
+ ])
+ expect(socket.remoteClient('r2')?.role).toBe('web')
+ expect(socket.remoteClient('r3')?.role).toBe('web')
+ warn.mockRestore()
+ await socket.stop()
+ })
+
+ it('sends a frame for the apps away from this desk to the relay alone: never a window here, nothing while serving this computer only', async () => {
+ const socket = relaySocket('token')
+ const broadcast = vi.spyOn(gatewayOf(socket), 'broadcast')
+ const frames: Record<string, unknown>[] = []
+ socket.registerLocalClient('local:window', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })
+ const asked = { type: 'commander_question', agentId: 'a1', dbSessionId: 's1', payload: { requestId: 'q1', questions: [] } }
+ socket.sendRemote(asked)
+ expect(broadcast).toHaveBeenCalledExactlyOnceWith(asked, undefined)
+ expect(frames.filter((frame) => frame.type === 'commander_question')).toEqual([])
+ // Said in the frame log like any frame for the web audience, when it is on.
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const wasOn = env.LOG_FRAMES
+ env.LOG_FRAMES = true
+ try { socket.sendRemote(asked) } finally { env.LOG_FRAMES = wasOn }
+ expect(log.mock.calls.map(([line]) => line)).toContain('[frame] → web commander_question · requestId=q1')
+ log.mockRestore()
+ broadcast.mockClear()
+ socket.serveThisComputerOnly()
+ socket.sendRemote(asked)
+ expect(broadcast).not.toHaveBeenCalled()
+ await socket.unregisterLocalClient('local:window')
+ await socket.stop()
+ })
+
+ it('says whether an app away from this desk holds a session: a web one, never a device', async () => {
+ const socket = relaySocket('token')
+ expect(socket.hasRemoteApp()).toBe(false)
+ socket.fromGateway.client('d1', { role: 'device', label: null, identity: 'DEV', direct: false })
+ expect(socket.hasRemoteApp()).toBe(false)
+ socket.fromGateway.client('r1', { role: 'web', label: null, identity: 'PUB', direct: false })
+ expect(socket.hasRemoteApp()).toBe(true)
+ socket.fromGateway.client('r1', null)
+ expect(socket.hasRemoteApp()).toBe(false)
+ await socket.stop()
+ })
+
it('drops the device E2EE session when OUR backend link dies, not just when the backend says so', async () => {
vi.useFakeTimers()
const socket = relaySocket('token')
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 9bd7c5eb1..22c0af52b 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -119,6 +119,9 @@ export class BackendSocket {
onCommanderJoin: (() => void) | null = null
/** Called only when commander presence crosses zero; drives the disposable recap-worker grace. */
onCommanderPresenceChanged: ((connected: boolean) => void) | null = null
+ /** An app away from this desk (the phone, a browser) gained an E2EE session: it is told again what is still
+ * being asked (core/questions.ts), as a window on this computer is when it attaches (localWsServer.ts). */
+ onRemoteAppJoined: (() => void) | null = null
/** Cancels an agent's turn, for the orchestrator (cli.ts binds core/turns/cancel.ts). */
onCancel: ((sessionId: string) => void) | null = null
/** Takes a `cancel` frame, a turn interrupted with C-c (cli.ts binds core/turns/cancel.ts). */
@@ -335,6 +338,12 @@ export class BackendSocket {
return [...this.remoteClients.values()].some((client) => client.role === 'device')
}
+ /** True while an app away from this desk (the phone, a browser) holds an E2EE session over the relay: someone
+ * who hears how loudly a turn ends, with no device in sight (services/recaps.ts). */
+ hasRemoteApp(): boolean {
+ return [...this.remoteClients.values()].some((client) => client.role === 'web')
+ }
+
/** Live backend link state (`/api/status`), as the gateway last said. */
isConnected(): boolean {
return this.linkUp
@@ -370,7 +379,17 @@ export class BackendSocket {
binary: (connId, clear) => this.enqueueTerminalBinary(connId, clear),
client: (connId, client) => {
this.wifi?.session(connId, client)
- if (client) { this.remoteClients.set(connId, client); return }
+ if (client) {
+ const joined = client.role === 'web' && this.remoteClients.get(connId)?.role !== 'web'
+ this.remoteClients.set(connId, client)
+ // The client is registered whatever its replay does: a re-announce that throws costs only itself.
+ if (joined) {
+ try { this.onRemoteAppJoined?.() } catch (error) {
+ console.warn(`[backend] re-announcing to a remote app failed: ${error instanceof Error ? error.message : String(error)}`)
+ }
+ }
+ return
+ }
if (!this.remoteClients.delete(connId)) return
this.viewerStreams?.closed(connId); this.ownerCommands.closeConnection(connId); this.onConnectionClosed?.(connId)
},
@@ -532,10 +551,21 @@ export class BackendSocket {
for (const [connId, sink] of this.localClients) {
if (!sink.sendFrame(frame)) void this.unregisterLocalClient(connId)
}
- if (!this.thisComputerOnly) {
- const guest = this.frameGuest(frame)
- this.toGateway('web', (gateway) => gateway.broadcast(frame, guest ?? undefined))
- }
+ this.toRemoteApps(frame)
+ }
+
+ /** An up-frame for the owner's apps away from this desk alone — the relay's web audience, sealed by the
+ * gateway when it carries content — and never the windows here, which are told through `sendLocal`. An
+ * agent's question goes both ways (core/questions.ts): `send` would add the tool connections too. */
+ sendRemote(frame: Frame): void {
+ if (env.LOG_FRAMES) logFrame('→', 'web', frame)
+ this.toRemoteApps(frame)
+ }
+
+ private toRemoteApps(frame: Frame): void {
+ if (this.thisComputerOnly) return
+ const guest = this.frameGuest(frame)
+ this.toGateway('web', (gateway) => gateway.broadcast(frame, guest ?? undefined))
}
/** The guest whose harness a frame is about (registry `guest`, through `agentGuest`), or null for the
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.ts
index 87bfcad07..18187f021 100644
--- a/cli/src/cable/cableHost.spec.ts
+++ b/cli/src/cable/cableHost.spec.ts
@@ -707,6 +707,15 @@ describe('cableEventFor', () => {
expect(cableEventFor({ ...base, payload: { ...base.payload, restored: true } })?.subagent).toBe(true)
expect(cableEventFor({ ...base, payload: { kind: 'tool', text: 'Bash' } })).toBeNull()
})
+
+ it('carries a summary\'s tier, decided by the recaps, and no word that is not one', () => {
+ const base = { type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'body', recap: 'recap' } }
+ for (const tier of ['alert', 'list', 'silent'] as const) {
+ expect(cableEventFor({ ...base, payload: { ...base.payload, tier } })?.tier).toBe(tier)
+ }
+ expect(cableEventFor({ ...base, payload: { ...base.payload, tier: 'loud' } })).not.toHaveProperty('tier')
+ expect(cableEventFor({ ...base, payload: { kind: 'done', text: 'done', tier: 'alert' } })).not.toHaveProperty('tier')
+ })
})
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index 57449a4e9..0c4792ff1 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -36,6 +36,7 @@ import type { FormCommand, FormResult } from './windowForm.js'
import type { PetStore } from './pets/store.js'
import type { MachineFleet } from './machineFleet.js'
import type { ReviewedAnswer, AnswerReceipt } from './questionInbox.js'
+import { isTier, type Tier } from '../lib/notifyTier.js'
/** One completed turn's recap, as the mirror keeps them. */
@@ -901,8 +902,8 @@ export function cableStepFor(
* kind reaches the cable the day it reaches the socket.
*/
export function cableEventFor(
- frame: { type?: string; agentId?: string; payload?: { kind?: string; text?: string; recap?: string; subagent?: unknown; restored?: unknown; update?: unknown; fullText?: unknown; failed?: unknown } },
-): { kind: 'processing' | 'done' | 'summary' | 'error'; agentId: string; text: string; recap: string; subagent: boolean; update?: string; fullText?: string; failed?: boolean } | null {
+ frame: { type?: string; agentId?: string; payload?: { kind?: string; text?: string; recap?: string; subagent?: unknown; restored?: unknown; update?: unknown; fullText?: unknown; failed?: unknown; tier?: unknown } },
+): { kind: 'processing' | 'done' | 'summary' | 'error'; agentId: string; text: string; recap: string; subagent: boolean; update?: string; fullText?: string; failed?: boolean; tier?: Tier } | null {
if (frame.type !== 'commander_event' || !frame.agentId) return null
const kind = frame.payload?.kind
if (kind !== 'processing' && kind !== 'done' && kind !== 'summary' && kind !== 'error') return null
@@ -911,10 +912,13 @@ export function cableEventFor(
const silent = frame.payload?.subagent === true || frame.payload?.restored === true
const update = frame.payload?.update
const fullText = frame.payload?.fullText
+ // `tier`: how loudly the turn tells, decided once by the recaps (services/recaps.ts) for every screen.
+ const tier = frame.payload?.tier
return { kind, agentId: frame.agentId, text: frame.payload?.text ?? '', recap: frame.payload?.recap ?? '', subagent: silent,
...(kind === 'processing' && typeof update === 'string' ? { update } : {}),
...(kind === 'summary' && frame.payload?.failed === true ? { failed: true } : {}),
- ...(kind === 'summary' && typeof fullText === 'string' && fullText ? { fullText } : {}) }
+ ...(kind === 'summary' && typeof fullText === 'string' && fullText ? { fullText } : {}),
+ ...(kind === 'summary' && isTier(tier) ? { tier } : {}) }
}
/**
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 5e7e755cd..629b8c71e 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -902,6 +902,8 @@ export interface RecapSession {
agentId: string
/** Its display name, which a summary card carries for a machine whose tile is not loaded. */
name?: string
+ /** Its engine (`claude`, `codex`, …): what a finished turn's tier is decided with (lib/notifyTier.ts). */
+ engine?: string
/** Its transcript: a Claude sub-agent writes its own beside it, which a held turn end watches. */
transcriptPath?: string
/** An Orchestrator specialist's turn, or its director's while specialists are out: nobody's news. Said
@@ -911,8 +913,9 @@ export interface RecapSession {
}
/** Who watches this machine's turn cards: a device at all (through the backend or on the cable), and one
- * rendering this machine right now. */
-export interface RecapWatchers { device: boolean; active: boolean }
+ * rendering this machine right now. `remote`: an app away from this desk (the phone, a browser) holds a session
+ * over the relay, and hears how loudly each turn ends (`turn_summary`'s `tier`); absent from an older core. */
+export interface RecapWatchers { device: boolean; active: boolean; remote?: boolean }
/** The turn lifecycle, as the core tells the recaps. */
export type TurnLifecycle =
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 05f12b5f1..62cd59fc7 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -190,6 +190,7 @@ import { createGuestCreate } from './agents/guestCreate.js'
import { createStoreLink } from './storeLink.js'
import { createModelsLink } from './modelsLink.js'
import { createRecapsLink } from './recapsLink.js'
+import { HOSTED_JEV_PATH } from '../lib/jev/jevClient.js'
import { createAgentCleanupLink } from './agentCleanupLink.js'
import { AGENT_CLEANUP_FALLBACKS, RECAPS_FALLBACKS, TERMINALS_OFF } from './api.js'
import { answerAgentQuery } from './agentQueries.js'
@@ -1066,8 +1067,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const cableWatchingLocal = (): boolean => dialWatching
const deviceIsWatching = (): boolean => backend.hasCommander() || cableWatchingLocal() || wifiCore.connected()
- /** Anyone who can DRAW a question: a device, a cabled dial, or a desktop window on this computer. */
- const someoneCanAnswer = (): boolean => deviceIsWatching() || backend.hasLocalClient()
+ /** Anyone who can DRAW a question: a device, a cabled dial, a desktop window on this computer, or an app away
+ * from this desk (the phone), which is sent it over the relay (core/questions.ts). */
+ const someoneCanAnswer = (): boolean => deviceIsWatching() || backend.hasLocalClient() || backend.hasRemoteApp()
// A page a program in a harness's pane opens (Claude Code's `/login`) goes to the phone typing there, and the
// sign-in the phone catches comes back to the program (core/terminals/browser.ts, lib/browserShim.ts).
const browser = createBrowser({
@@ -1300,6 +1302,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
cloudAgents = createCloudAgents({ port: () => ports.cloud, clients: backend, openQuestions: asking.openQuestions, deviceInput })
const cloud = cloudAgents
backend.questionProvider = createQuestionResponse((payload) => cloud.answer(payload) ?? asking.answer(payload))
+ // An app away from this desk is told what is still being asked as it connects (core/questions.ts).
+ backend.onRemoteAppJoined = () => asking.reannounceRemote()
const openQuestions = asking.openQuestions
// The agents on this machine (core/agents/list.ts), in the socket's frames, with its monitor readings.
backend.agentsProvider = createAgentList({
@@ -1323,6 +1327,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Recaps: turn cards, notifications, cut by the recaps (services/recaps.ts) from the lifecycle the core tells (core/turns/recaps.ts).
const recaps = createRecaps({
port: () => ports.recaps, turnActivity, clients: backend, deviceIsWatching, cableWatchingLocal, sessionTurnOpen,
+ remoteApp: () => backend.hasRemoteApp(),
bySession: (sessionId) => registry.bySession(sessionId), resolve: (id) => registry.resolve(id), live: () => registry.list(),
stopped: (agentId) => stoppedAgents.get(agentId),
orchestratorRoleOf: (agentId) => ports.orchestrator?.roleOf(agentId) ?? null,
@@ -1432,7 +1437,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (outOfProcess.has('wifi')) ports.wifi = wifiLink.port
// What the core tells the recaps in their own process, and reads back from what they said (core/recapsLink.ts).
const recapsLink = createRecapsLink({ notify: (frame, opts) => serviceLinks.notify('recaps', frame, opts), buffered: () => serviceLinks.buffered('recaps'),
- call: (type, payload) => serviceLinks.call('recaps', type, payload), clients: coreApi.clients, lastTurn: coreApi.transcripts.lastTurn })
+ call: (type, payload) => serviceLinks.call('recaps', type, payload), clients: coreApi.clients, lastTurn: coreApi.transcripts.lastTurn,
+ jev: (body) => proxyBackend('POST', HOSTED_JEV_PATH, body) })
// What the core tells the agent cleanup in its own process, and answers it (core/agentCleanupLink.ts).
const agentCleanupLink = createAgentCleanupLink(coreApi, (frame, opts) => serviceLinks.notify('agentCleanup', frame, opts))
const usageLink = createUsageLink({ call: payload => ports.usage?.read(payload.target as AgentUsageTarget) ?? Promise.resolve({}), changed: agentEvents.onTokenUsageChanged })
diff --git a/cli/src/core/questions.spec.ts b/cli/src/core/questions.spec.ts
index b4dd750ff..6beae3e0b 100644
--- a/cli/src/core/questions.spec.ts
+++ b/cli/src/core/questions.spec.ts
@@ -19,7 +19,7 @@ function setup(over: Partial<QuestionDeps> = {}) {
keyTerminal: vi.fn(async () => true),
},
acquireTerminalControl: vi.fn(() => () => {}),
- clients: { sendCommander: vi.fn(), sendLocal: vi.fn() },
+ clients: { sendCommander: vi.fn(), sendLocal: vi.fn(), sendRemote: vi.fn() },
agentIdFor: (sessionId) => agents.get(sessionId)?.agentId ?? sessionId,
sessionTurnOpen: (sessionId) => sessionId === 'busy',
someoneCanAnswer: () => true,
@@ -96,6 +96,8 @@ describe('questions', () => {
// A question is always news: the person is needed.
expect(asked.payload.notification).toEqual({ id: 'r1', kind: 'needsYou' })
expect(vi.mocked(deps.clients.sendCommander).mock.calls).toEqual([[waiting('s1', 'a1')], [asked]])
+ // The owner's apps away from this desk hear the same question, over the relay.
+ expect(vi.mocked(deps.clients.sendRemote).mock.calls.at(-1)).toEqual([asked])
expect(asking.openQuestions.get('s1')).toBe(asked)
expect(log.mock.calls[0][0]).toContain('asking the user · "Ship it?" · req=r1')
// A question with nothing shaped still goes out, and still says so.
@@ -130,9 +132,33 @@ describe('questions', () => {
expect(deps.deviceInput.setUserAction).toHaveBeenCalledWith('a1', false)
expect(deps.clients.sendCommander).toHaveBeenCalledWith(closed)
expect(deps.clients.sendLocal).toHaveBeenCalledWith(closed)
+ expect(deps.clients.sendRemote).toHaveBeenCalledWith(closed)
expect(asking.openQuestions.has('s1')).toBe(false)
expect(log.mock.calls[0][0]).toContain('answered elsewhere · closing on every client · req=r1')
})
+
+ it('tells an app that connects every question still open, then which are open at all', () => {
+ const { deps, asking } = setup()
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const remote = vi.mocked(deps.clients.sendRemote)
+ // Nothing open: only the list, empty, so an app that was here before lets go of what it held.
+ asking.reannounceRemote()
+ expect(remote.mock.calls).toEqual([[{ type: 'commander_questions_open', payload: { requestIds: [] } }]])
+ given(asking.questionWatcher).onQuestion('s1', 'r1', [{ q: 'Ship it?', options: [] }])
+ given(asking.questionWatcher).onQuestion('s2', 'r2', [{ q: 'Which branch?', options: [] }])
+ given(asking.questionWatcher).onQuestionGone('s2', 'r2')
+ const asked = asking.openQuestions.get('s1')
+ remote.mockClear()
+ asking.reannounceRemote()
+ expect(remote.mock.calls).toEqual([[asked], [{ type: 'commander_questions_open', payload: { requestIds: ['r1'] } }]])
+ })
+
+ it('never tells the relay a question it did not ask: a cloud agent\'s shares the open list, not the relay', () => {
+ const { deps, asking } = setup()
+ asking.openQuestions.set('cloud-a', { type: 'commander_question', agentId: 'cloud-a', payload: { requestId: 'cloud_q_1' } })
+ asking.reannounceRemote()
+ expect(vi.mocked(deps.clients.sendRemote).mock.calls).toEqual([[{ type: 'commander_questions_open', payload: { requestIds: [] } }]])
+ })
})
describe('question_response', () => {
diff --git a/cli/src/core/questions.ts b/cli/src/core/questions.ts
index 6e6af89ef..96eeb40a6 100644
--- a/cli/src/core/questions.ts
+++ b/cli/src/core/questions.ts
@@ -22,11 +22,12 @@ export interface QuestionDeps {
terminal: Pick<TerminalControl, 'captureTerminal' | 'submitTerminal' | 'keyTerminal'>
/** Holds a pane, queue and terminal both, for the whole multi-step answer (Input.acquireTerminalControl). */
acquireTerminalControl: (id: string, opts?: { forAnswer?: boolean }) => (() => void) | null
- /** The dial (`sendCommander`) and the window on this computer (`sendLocal`). */
- clients: { sendCommander(frame: Frame): void; sendLocal(frame: Frame): void }
+ /** The dial (`sendCommander`), the windows on this computer (`sendLocal`) and the owner's apps away from
+ * this desk, over the relay (`sendRemote`). */
+ clients: { sendCommander(frame: Frame): void; sendLocal(frame: Frame): void; sendRemote(frame: Frame): void }
agentIdFor: (sessionId: string) => string
sessionTurnOpen: (sessionId: string) => boolean
- /** Whether anyone could answer right now: a device watching, or a window on this computer. */
+ /** Whether anyone could answer right now: a device watching, a window on this computer, or an app away. */
someoneCanAnswer: () => boolean
deviceInput: Pick<AutonomousDeviceInput, 'setUserAction'>
}
@@ -70,6 +71,9 @@ export function createQuestions({
}
// What is still being asked, by session — handed to a window that connects later (openQuestions below).
const openQuestions = new Map<string, Record<string, unknown>>()
+ // The same, of the questions this module asked, for an app away from this desk that connects later: the
+ // cloud agents' questions share `openQuestions` (core/agents/cloud.ts) and never go over the relay.
+ const askedRemotely = new Map<string, Frame>()
const monitorActivity = (sessionId: string): 'needsInput' | 'working' | 'idle' => openQuestions.has(sessionId)
? 'needsInput' : sessionTurnOpen(sessionId) ? 'working' : 'idle'
// Who hears that a question was asked or answered: the recaps, which do not announce a turn waiting on
@@ -101,17 +105,17 @@ export function createQuestions({
clients.sendCommander(asked)
// ...and to the window on this computer. `sendCommander` is `webEligible: false`, so until this
// second call the app could not learn that an agent was blocked even though the question had
- // already been shaped for the dial.
- //
- // `sendLocal`, not `send`: the question and its option labels are user content, and the only
- // audience `send` would add beyond loopback is the cloud leg, where this frame would travel
- // PLAINTEXT — `commander_question` is deliberately absent from ENCRYPTED_UP_TYPES, and putting it
- // there means re-deriving an interop hash pinned by the browser client and the device firmware in
- // two other repositories. Loopback needs no envelope, and it costs nothing that is reachable
- // today: a remote machine's watcher is gated on ITS OWN audience, which a window attached over
- // here is not part of either way.
+ // already been shaped for the dial. Loopback needs no envelope. `sendLocal`, not `send`: the tool
+ // connections (`hn`, scripts) were never sent a question, and still are not.
clients.sendLocal(asked)
+ // ...and to the owner's apps away from this desk, over the relay (2026-10-21), so a phone hears an
+ // agent waiting on it. Sealed all the same: the gateway seals `commander_question` for the web
+ // audience as it does for the devices (lib/e2ee/manager.ts `SEALED_FOR_WEB`), without core.ts and
+ // its pinned hash, since every app opens by the envelope. Only the owner's apps, and a guest's for the
+ // guest's own harness (gateway.ts `broadcast`), can open it.
+ clients.sendRemote(asked)
openQuestions.set(sessionId, asked)
+ askedRemotely.set(sessionId, asked)
console.log(`[question] ${sid(sessionId)} asking the user · "${preview(shaped[0]?.q ?? '')}" · req=${requestId}`)
},
// Answered somewhere else — the app, or the pane by hand. Every client drawing it is told to stop
@@ -131,12 +135,25 @@ export function createQuestions({
// one already answered. This is the mechanism behind "answer anywhere": the dial is cabled to
// this very computer, so the dial and this window are always the same machine's audience.
clients.sendLocal(closed)
+ clients.sendRemote(closed)
openQuestions.delete(sessionId)
+ askedRemotely.delete(sessionId)
console.log(`[question] ${sid(sessionId)} answered elsewhere · closing on every client · req=${requestId}`)
},
})
+ /**
+ * An app away from this desk gained a session: it is told every question still open, then which are open
+ * at all, so one that was here before lets go of a question answered while it was away — as a window on
+ * this computer is when it attaches (localWsServer.ts). Over the relay this reaches every app connected,
+ * and each takes a question it already holds as the same wait continuing, never as news.
+ */
+ const reannounceRemote = (): void => {
+ for (const asked of askedRemotely.values()) clients.sendRemote(asked)
+ const requestIds = [...askedRemotely.values()].map((asked) => (asked.payload as { requestId: string }).requestId)
+ clients.sendRemote({ type: 'commander_questions_open', payload: { requestIds } })
+ }
const questionResponse = createQuestionResponse(answer)
- return { questions, showAwaitingAnswer, answer, questionResponse, openQuestions, monitorActivity, hearQuestions, questionWatcher }
+ return { questions, showAwaitingAnswer, answer, questionResponse, openQuestions, monitorActivity, hearQuestions, questionWatcher, reannounceRemote }
}
/**
diff --git a/cli/src/core/recapsLink.spec.ts b/cli/src/core/recapsLink.spec.ts
index 0d7b944f4..c0f6e5cf3 100644
--- a/cli/src/core/recapsLink.spec.ts
+++ b/cli/src/core/recapsLink.spec.ts
@@ -13,6 +13,7 @@ function setup() {
call: vi.fn(async (_type: string, _payload: Record<string, unknown>): Promise<Record<string, unknown>> => ({ cards: [] })),
clients: { turnCard: vi.fn(), turnSummary: vi.fn() },
lastTurn: vi.fn(async (sessionId: string) => (sessionId === 's1' ? { assistantText: 'done', userMessage: 'go' } : null)),
+ jev: vi.fn(async (_body: unknown): Promise<{ status: number; body: Record<string, unknown> }> => ({ status: 200, body: { data: { answers: {} } } })),
log: vi.fn(),
now: () => clock,
}
@@ -85,6 +86,15 @@ describe('the recaps in their own process, as the core sees them', () => {
expect(await link.answer('agents', {})).toEqual({ error: 'UNKNOWN_QUERY' })
})
+ it('asks Harness\'s Jev for the process, signed by the core, and answers as the backend did', async () => {
+ const { deps, link } = setup()
+ const body = { state: { recap: 'Deployed' }, questions: {} }
+ expect(await link.answer('jev', { body })).toEqual({ status: 200, body: { data: { answers: {} } } })
+ expect(deps.jev).toHaveBeenCalledWith(body)
+ deps.jev.mockResolvedValueOnce({ status: 402, body: { error: { code: 'JEV_CREDITS' } } })
+ expect(await link.answer('jev', { body })).toEqual({ status: 402, body: { error: { code: 'JEV_CREDITS' } } })
+ })
+
it('asks the process for the cards of every turn still at work, and takes none it cannot read', async () => {
const { deps, link } = setup()
const card = { type: 'commander_event', agentId: 'a1', dbSessionId: 's1', payload: { kind: 'processing', text: 'Processing' } }
@@ -107,7 +117,7 @@ describe('the recaps in their own process, as the core sees them', () => {
it('says it to the daemon\'s log unless told otherwise', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const link = createRecapsLink({ notify: vi.fn(() => true), buffered: () => RECAPS_BUFFER_LIMIT + 1, call: vi.fn(), clients: { turnCard: vi.fn(), turnSummary: vi.fn() }, lastTurn: vi.fn() })
+ const link = createRecapsLink({ notify: vi.fn(() => true), buffered: () => RECAPS_BUFFER_LIMIT + 1, call: vi.fn(), clients: { turnCard: vi.fn(), turnSummary: vi.fn() }, lastTurn: vi.fn(), jev: vi.fn() })
link.port.lifecycle({ kind: 'stopped', sessionId: 's1' }, watchers)
expect(warn).toHaveBeenCalledTimes(1)
warn.mockRestore()
diff --git a/cli/src/core/recapsLink.ts b/cli/src/core/recapsLink.ts
index c8746191f..615243cc6 100644
--- a/cli/src/core/recapsLink.ts
+++ b/cli/src/core/recapsLink.ts
@@ -35,6 +35,9 @@ export interface RecapsLinkDeps {
/** Where its cards and recaps go: the core API checks each frame's type. */
clients: Pick<CoreApi['clients'], 'turnCard' | 'turnSummary'>
lastTurn: CoreApi['transcripts']['lastTurn']
+ /** Harness's Jev, asked for how loudly a turn ends (lib/notifyTier.ts): the process holds no credential, so
+ * this one route is all of the account's backend it may reach, signed by the core. */
+ jev: (body: unknown) => Promise<{ status: number; body: Record<string, unknown> }>
log?: (line: string) => void
now?: () => number
}
@@ -100,6 +103,7 @@ export function createRecapsLink(deps: RecapsLinkDeps) {
/** The core's answers to the process's questions (core/serviceLinks.ts `answer`, for `recaps`). */
async answer(query: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {
if (query === 'lastTurn' && typeof payload.sessionId === 'string') return { turn: await deps.lastTurn(payload.sessionId) }
+ if (query === 'jev') return { ...await deps.jev(payload.body) }
return { error: 'UNKNOWN_QUERY' }
},
/** The process went: no card of it is busy any more, and the core's heartbeats stop with their turns. */
diff --git a/cli/src/core/turns/recaps.spec.ts b/cli/src/core/turns/recaps.spec.ts
index 6c5434e5e..4595a3d4d 100644
--- a/cli/src/core/turns/recaps.spec.ts
+++ b/cli/src/core/turns/recaps.spec.ts
@@ -20,6 +20,7 @@ function setup(over: Partial<RecapDeps> = {}) {
clients: { hasActiveCommander: vi.fn(() => false) },
deviceIsWatching: vi.fn(() => true),
cableWatchingLocal: vi.fn(() => false),
+ remoteApp: vi.fn(() => false),
bySession: (sessionId) => sessions.get(sessionId),
resolve: (id) => id === 'a1' ? live : undefined,
stopped: (agentId) => agentId === 'gone' ? ({ agentId: 'gone', sessionId: 'old-s' } as RegisteredSession) : null,
@@ -32,7 +33,7 @@ function setup(over: Partial<RecapDeps> = {}) {
return { deps, recaps, port, held, live, off: () => { on = null } }
}
-const watching = { device: true, active: false }
+const watching = { device: true, active: false, remote: false }
const started = { type: 'turn_started', payload: { userMessage: 'hi' } } as LiveEvent
const ended = { type: 'turn_ended', payload: {} } as LiveEvent
@@ -66,11 +67,11 @@ describe('recaps, as the core keeps them', () => {
recaps.mirror.ingest([ended], 's1', { replay: true })
recaps.mirror.ingest([started], 's2')
recaps.mirror.ingest([started], 'unbound')
- const session = { sessionId: 's1', agentId: 'a1', name: projectDisplayName(live), transcriptPath: '/t/s1.jsonl' }
+ const session = { sessionId: 's1', agentId: 'a1', name: projectDisplayName(live), engine: 'claude', transcriptPath: '/t/s1.jsonl' }
expect(port.lifecycle.mock.calls).toEqual([
[{ kind: 'events', session, events: [started], replay: false }, watching],
[{ kind: 'events', session: { ...session, subagent: true }, events: [ended], replay: true }, watching],
- [{ kind: 'events', session: { sessionId: 's2', agentId: 'a2', name: projectDisplayName({ agentId: 'a2', sessionId: 's2', engine: 'claude', cwd: '/work/other' } as RegisteredSession) }, events: [started], replay: false }, watching],
+ [{ kind: 'events', session: { sessionId: 's2', agentId: 'a2', name: projectDisplayName({ agentId: 'a2', sessionId: 's2', engine: 'claude', cwd: '/work/other' } as RegisteredSession), engine: 'claude' }, events: [started], replay: false }, watching],
// A session the core no longer has is addressed by its own id, as the cards always were.
[{ kind: 'events', session: { sessionId: 'unbound', agentId: 'unbound' }, events: [started], replay: false }, watching],
])
@@ -86,7 +87,19 @@ describe('recaps, as the core keeps them', () => {
vi.mocked(deps.clients.hasActiveCommander).mockReturnValueOnce(true)
recaps.mirror.noteEngineStopped('s1')
expect(port.lifecycle.mock.calls.map(([, seen]) => seen)).toEqual([
- { device: false, active: false }, { device: false, active: true }, { device: false, active: true },
+ { device: false, active: false, remote: false }, { device: false, active: true, remote: false },
+ { device: false, active: true, remote: false },
+ ])
+ })
+
+ it('says whether an app away from this desk holds a session, which is who hears a turn\'s tier with no device', () => {
+ const { deps, recaps, port } = setup()
+ vi.mocked(deps.deviceIsWatching).mockReturnValue(false)
+ vi.mocked(deps.remoteApp).mockReturnValueOnce(true)
+ recaps.mirror.noteEngineStopped('s1')
+ recaps.mirror.noteEngineStopped('s1')
+ expect(port.lifecycle.mock.calls.map(([, seen]) => seen)).toEqual([
+ { device: false, active: false, remote: true }, { device: false, active: false, remote: false },
])
})
diff --git a/cli/src/core/turns/recaps.ts b/cli/src/core/turns/recaps.ts
index a18e9e537..94b2de36c 100644
--- a/cli/src/core/turns/recaps.ts
+++ b/cli/src/core/turns/recaps.ts
@@ -25,6 +25,8 @@ export interface RecapDeps {
clients: { hasActiveCommander(): boolean }
deviceIsWatching: () => boolean
cableWatchingLocal: () => boolean
+ /** Whether an app away from this desk (the phone, a browser) holds a session over the relay. */
+ remoteApp: () => boolean
bySession: (sessionId: string) => RegisteredSession | undefined
resolve: (id: string) => RegisteredSession | undefined
/** A stopped agent's archived record (stoppedAgents.get). */
@@ -61,7 +63,7 @@ export interface TurnRecaps {
}
export function createRecaps({
- port, turnActivity, clients, deviceIsWatching, cableWatchingLocal, bySession, resolve, stopped, live, sessionTurnOpen,
+ port, turnActivity, clients, deviceIsWatching, cableWatchingLocal, remoteApp, bySession, resolve, stopped, live, sessionTurnOpen,
orchestratorRoleOf,
}: RecapDeps) {
/**
@@ -83,7 +85,9 @@ export function createRecaps({
return role?.role === 'worker' || (role?.role === 'director' && role.busy)
}
/** Who watches the cards now: the recaps read it as they emit one. A plugged-in dial is always watching. */
- const watchers = (): RecapWatchers => ({ device: deviceIsWatching(), active: clients.hasActiveCommander() || cableWatchingLocal() })
+ const watchers = (): RecapWatchers => ({
+ device: deviceIsWatching(), active: clients.hasActiveCommander() || cableWatchingLocal(), remote: remoteApp(),
+ })
/** A session as the recaps address its cards. Whether it is a sub-agent's is asked only where a turn
* ends (it reads the orchestrator); elsewhere the recaps keep what they were last told. */
const session = (sessionId: string, subagent?: boolean): RecapSession => {
@@ -92,6 +96,7 @@ export function createRecaps({
sessionId,
agentId: known?.agentId ?? sessionId,
...(known ? { name: projectDisplayName(known) } : {}),
+ ...(known?.engine ? { engine: known.engine } : {}),
...(known?.transcriptPath ? { transcriptPath: known.transcriptPath } : {}),
...(subagent === undefined ? {} : { subagent }),
}
diff --git a/cli/src/lib/commander.spec.ts b/cli/src/lib/commander.spec.ts
index 26f1f29e3..d1b8f3db3 100644
--- a/cli/src/lib/commander.spec.ts
+++ b/cli/src/lib/commander.spec.ts
@@ -2,7 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdtempSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
-import { CommanderMirror, type CommanderFrame } from './commander.js'
+import { CommanderMirror, type CommanderFrame, type CommanderMirrorOpts, type TierTurn } from './commander.js'
+import type { Tier } from './notifyTier.js'
import { isLocalOnly, withoutUpdate } from './cardUpdate.js'
import type { LiveEvent } from './normalize.js'
import { BODY_MAX_CHARS, RECAP_MAX_CHARS, deriveTurnSummary } from './deviceRecap.js'
@@ -978,3 +979,118 @@ it('isLocalOnly marks only the shell result card', () => {
expect(isLocalOnly({ type: 'commander_event' })).toBe(false)
expect(isLocalOnly({ type: 'agent_deleted', payload: { kind: 'tool_end' } })).toBe(false)
})
+
+describe('CommanderMirror decides each finished turn\'s tier once, for every screen', () => {
+ let dir = ''
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(0)
+ dir = mkdtempSync(join(tmpdir(), 'adapter-commander-tier-'))
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ rmSync(dir, { recursive: true, force: true })
+ })
+
+ const make = (decideTier: (turn: TierTurn) => Promise<Tier | null>, over: Partial<CommanderMirrorOpts> = {}) => {
+ const cards: CommanderFrame[] = []
+ const web: Record<string, unknown>[] = []
+ const mirror = new CommanderMirror({ send: (f) => cards.push(f), sendWeb: (f) => web.push(f), hasDevice: () => true,
+ summarize: async () => 'Deployed\n\nThe site is live.', summarizeIsLocal: true, dataDir: dir, decideTier, ...over })
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const summaries = () => cards.filter((f) => f.payload.kind === 'summary').map((f) => f.payload)
+ const recaps = () => web.filter((f) => f.type === 'turn_summary').map((f) => f.payload as Record<string, unknown>)
+ return { mirror, cards, summaries, recaps }
+ }
+ const turnOf = (...events: Array<Record<string, unknown>>) => events as unknown as LiveEvent[]
+ const started = { type: 'turn_started', payload: { userMessage: 'ship it' } }
+ const reply = { type: 'text_delta', payload: { content: 'The site is live.' } }
+ const ended = { type: 'turn_ended', payload: {} }
+
+ it('carries the tier on the summary card and the apps\' recap, told the turn\'s duration, tests and commits', async () => {
+ const decideTier = vi.fn(async (_turn: TierTurn): Promise<Tier | null> => 'alert')
+ const { mirror, cards, summaries, recaps } = make(decideTier)
+ mirror.ingest(turnOf(started), 's')
+ vi.setSystemTime(125_000)
+ mirror.ingest(turnOf(
+ { type: 'tool_start', payload: { id: 't1', tool: 'Bash', input: { command: 'npm test' } } },
+ { type: 'tool_end', payload: { id: 't1', tool: 'Bash', output: '', outputTail: ' Tests 3 passed (3)', isError: false, summary: '' } },
+ { type: 'tool_start', payload: { id: 'c1', tool: 'Bash', input: { command: 'git commit -m ship' } } },
+ { type: 'tool_end', payload: { id: 'c1', tool: 'Bash', output: '', outputTail: '[main 1a2b] ship', isError: false, summary: '' } },
+ reply, ended,
+ ), 's')
+ await vi.runAllTimersAsync()
+ expect(decideTier).toHaveBeenCalledExactlyOnceWith({ sessionId: 's', recap: 'Deployed', durationS: 125,
+ stats: { testsPassed: 3, testsFailed: 0, commits: 1 } })
+ expect(cards.map((f) => f.payload.kind).slice(-2)).toEqual(['done', 'summary'])
+ expect(summaries()).toEqual([{ kind: 'summary', text: 'The site is live.', recap: 'Deployed',
+ notification: { id: expect.any(String), kind: 'done' }, tier: 'alert' }])
+ expect(recaps()).toEqual([{ summary: 'Deployed\n\nThe site is live.', sessionId: 's',
+ notification: { id: expect.any(String), kind: 'done' }, tier: 'alert' }])
+ })
+
+ it('tells the decider the recap, or the body when the recap is empty; the card the body, or the recap', async () => {
+ const decideTier = vi.fn(async (_turn: TierTurn): Promise<Tier | null> => 'list')
+ // A recap with an empty body after it, then a body with no recap before it.
+ let summary = 'Deployed\n\n'
+ const { mirror, summaries } = make(decideTier, { summarize: async () => summary })
+ mirror.ingest(turnOf(started, reply, ended), 's')
+ await vi.runAllTimersAsync()
+ summary = '\n\nThe site is live.'
+ mirror.ingest(turnOf(started, reply, ended), 's')
+ await vi.runAllTimersAsync()
+ expect(decideTier.mock.calls.map(([turn]) => turn.recap)).toEqual(['Deployed', 'The site is live.'])
+ expect(summaries().map((card) => [card.text, card.recap])).toEqual([['Deployed', 'Deployed'], ['The site is live.', '']])
+ })
+
+ it('asks nobody about a turn that is not news: a sub-agent\'s is silent', async () => {
+ const decideTier = vi.fn(async (): Promise<Tier | null> => 'alert')
+ const { mirror, summaries, recaps } = make(decideTier, { isSubagent: () => true })
+ mirror.ingest(turnOf(started, reply, ended), 's')
+ await vi.runAllTimersAsync()
+ expect(decideTier).not.toHaveBeenCalled()
+ expect(summaries()).toEqual([expect.objectContaining({ subagent: true, notification: null, tier: 'silent' })])
+ expect(recaps()).toEqual([expect.objectContaining({ notification: null, tier: 'silent' })])
+ })
+
+ it('puts no tier on either frame when nobody is there to tell', async () => {
+ const { mirror, summaries, recaps } = make(async () => null)
+ mirror.ingest(turnOf(started, reply, ended), 's')
+ await vi.runAllTimersAsync()
+ expect(summaries()).toHaveLength(1)
+ expect(summaries()[0]).not.toHaveProperty('tier')
+ expect(recaps()[0]).not.toHaveProperty('tier')
+ })
+
+ it('does not hold a recap for a newer turn: it goes out at the fallback\'s tier before that turn\'s first card', async () => {
+ let answer: (tier: Tier | null) => void = () => {}
+ const decideTier = vi.fn(() => new Promise<Tier | null>((resolve) => { answer = resolve }))
+ const { mirror, cards, summaries, recaps } = make(decideTier)
+ mirror.ingest(turnOf(started), 's')
+ vi.setSystemTime(130_000)
+ mirror.ingest(turnOf(reply, ended), 's')
+ await vi.runAllTimersAsync()
+ expect(decideTier).toHaveBeenCalledTimes(1)
+ expect(summaries()).toEqual([])
+ mirror.ingest(turnOf(started), 's')
+ expect(cards.map((f) => f.payload.kind).slice(-4)).toEqual(['done', 'summary', 'turn_started', 'processing'])
+ expect(summaries()).toEqual([expect.objectContaining({ tier: 'list' })])
+ // The decision that arrives afterwards changes nothing: the recap was told once.
+ answer('alert')
+ await vi.runAllTimersAsync()
+ expect(summaries()).toHaveLength(1)
+ expect(recaps()).toEqual([expect.objectContaining({ tier: 'list' })])
+ })
+
+ it('falls back to the rule when the decider fails, and knows no duration for a turn picked up mid-way', async () => {
+ const decideTier = vi.fn(async (_turn: TierTurn): Promise<Tier | null> => { throw new Error('no decision') })
+ const { mirror, summaries } = make(decideTier)
+ // Attached mid-turn: its start is a replay, the rest of it is live and still news.
+ mirror.ingest(turnOf(started), 's', { replay: true })
+ vi.setSystemTime(600_000)
+ mirror.ingest(turnOf(reply, ended), 's')
+ await vi.runAllTimersAsync()
+ expect(decideTier.mock.calls[0][0]).toMatchObject({ durationS: null, stats: {} })
+ expect(summaries()).toEqual([expect.objectContaining({ tier: 'silent' })])
+ })
+})
diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.ts
index 6527d4335..0c71c6de0 100644
--- a/cli/src/lib/commander.ts
+++ b/cli/src/lib/commander.ts
@@ -25,6 +25,8 @@ import { AgentNotifications } from './agentNotifications.js'
import { deriveTurnSummary } from './deviceRecap.js'
import { RECENT_TURNS, lastFullText, recentAsks, recentRecaps, splitSummary, type RecentRecap, type SessionRecaps } from './recapReads.js'
import { atomicWriteJson } from './registry.js'
+import { fallbackTier, type Tier, type TierInput } from './notifyTier.js'
+import { TurnStats } from '../cable/turnStats.js'
export type CommanderFrame = {
type: 'commander_event'
@@ -33,6 +35,15 @@ export type CommanderFrame = {
payload: Record<string, unknown>
}
+/** A finished turn that is news, as the recaps hand it to `decideTier`. */
+export interface TierTurn {
+ sessionId: string
+ recap: string
+ /** From its live `turn_started`; null for one picked back up at attach, whose start was not seen. */
+ durationS: number | null
+ stats: TierInput['stats']
+}
+
export interface CommanderMirrorOpts {
/** Presentation lease only. Unverified work stays open for its real completion. */
verifiedWorking?: (sessionId: string) => boolean
@@ -92,6 +103,12 @@ export interface CommanderMirrorOpts {
* tells the core what it now holds (services/recapsProcess.ts), which answers from it in line.
*/
changed?: (sessionId: string) => void
+ /**
+ * How loudly a finished turn that is news tells (lib/notifyTier.ts), decided once here for every screen: the
+ * `summary` card and the apps' `turn_summary` both wait for it and carry it as `tier`. Null: nobody to tell
+ * (services/recaps.ts), and the frames carry none. Absent: no tier at all, and nothing waits.
+ */
+ decideTier?: (turn: TierTurn) => Promise<Tier | null>
}
interface SessionState {
@@ -111,6 +128,8 @@ interface SessionState {
lastTodos: Array<{ c: string; s: string }> | null
/** Top-level shell commands awaiting their result, by tool id: the turn stats' input (kind 'tool_end'). */
commands: Map<string, { tool: string; command: string }>
+ /** When the live turn started, for its duration; null when its start was a replay. */
+ startedAt: number | null
/** Sub-agents this turn spawned, in the order they started — the device's list above "Working…". */
agents: Array<{ id: string; desc: string; startedAt: number; doneMs: number | null; carried?: true }>
/** A turn_ended is being HELD because sub-agents this turn spawned are still running (see below). */
@@ -323,6 +342,8 @@ export class CommanderMirror {
*/
private asks = new Map<string, string[]>()
private revisions = new Map<string, number>()
+ /** Each session's turn's tests and commits, read off its shell results: what `decideTier` is told. */
+ private readonly turnStats = new TurnStats()
private file: string
private historyFile: string
private fullTextFile: string
@@ -341,7 +362,7 @@ export class CommanderMirror {
private stateFor(sessionId: string): SessionState {
let st = this.states.get(sessionId)
if (!st) {
- st = { lastAssistantText: '', playerUpdate: '', playerTextContinues: false, lastUserMessage: '', turnOpen: false, everOpened: false, summarizing: false, lastTool: null, lastTodos: null, commands: new Map(), agents: [], endPending: false, abandoned: false, endSettle: null, endDeadline: null, abort: null }
+ st = { lastAssistantText: '', playerUpdate: '', playerTextContinues: false, lastUserMessage: '', turnOpen: false, everOpened: false, summarizing: false, lastTool: null, lastTodos: null, commands: new Map(), startedAt: null, agents: [], endPending: false, abandoned: false, endSettle: null, endDeadline: null, abort: null }
this.states.set(sessionId, st)
}
return st
@@ -415,6 +436,8 @@ export class CommanderMirror {
st.lastTool = null
st.lastTodos = null
st.commands.clear()
+ st.startedAt = options?.replay ? null : Date.now()
+ this.turnStats.take(sessionId)
this.emit(sessionId, { kind: 'turn_started' }) // local-only: the devices drop the last turn's stats
// Drop the previous turn's finished rows, KEEP the ones still running. Two reasons, both
// measured: cursor's tool-start HOOK beats its transcript-derived turn_started by ~60ms, so a
@@ -509,6 +532,7 @@ export class CommanderMirror {
const ran = st.commands.get(String(e.payload.id))
if (ran) {
st.commands.delete(String(e.payload.id))
+ this.turnStats.toolResult(sessionId, ran.command, e.payload.isError, e.payload.outputTail ?? '')
this.emit(sessionId, { kind: 'tool_end', id: String(e.payload.id), ...ran, isError: e.payload.isError, ...(e.payload.outputTail !== undefined ? { outputTail: e.payload.outputTail } : {}) })
}
const done = st.agents.find((a) => a.id === String(e.payload.id))
@@ -692,6 +716,31 @@ export class CommanderMirror {
})
}
+ /**
+ * [tell] once `decideTier` answers (it waits at most its own budget, 1 s). A newer turn, a cancel or a forget
+ * waits for nothing: the recap goes out at once at the fallback's tier, from inside the abort, so it still
+ * lands before the next turn's first card — the dial would otherwise draw the old recap over "Working…".
+ */
+ private tellOnceDecided(
+ decide: (turn: TierTurn) => Promise<Tier | null>,
+ ac: AbortController,
+ turn: TierTurn,
+ tell: (tier: Tier | null) => void,
+ ): void {
+ const { sessionId } = turn
+ let told = false
+ const once = (tier: Tier | null, why: string): void => {
+ if (told) return
+ told = true
+ ac.signal.removeEventListener('abort', early)
+ this.trace(sessionId, `${sessionId.slice(0, 8)} tier ${tier ?? 'none'} · ${why}`)
+ tell(tier)
+ }
+ const early = (): void => once(fallbackTier(turn.durationS), 'superseded before it was decided')
+ ac.signal.addEventListener('abort', early, { once: true })
+ decide(turn).then((tier) => once(tier, 'decided'), () => once(fallbackTier(turn.durationS), 'decider failed'))
+ }
+
private async resolveTurnText(
sessionId: string,
fallbackText: string,
@@ -776,10 +825,20 @@ export class CommanderMirror {
this.emit(sessionId, { kind: 'done', text: 'done' })
// One decision feeds both clients. A silent recap still updates the
// device's tile; only real completed results create inbox entries.
- this.emit(sessionId, { kind: 'summary', text: body || recap, recap,
- notification, ...(!notification ? { subagent: true } : {}) })
- this.opts.sendWeb({ type: 'turn_summary', agentId: this.opts.agentIdFor?.(sessionId) ?? sessionId,
- dbSessionId: sessionId, payload: { summary, sessionId, notification } })
+ const tell = (tier: Tier | null): void => {
+ this.emit(sessionId, { kind: 'summary', text: body || recap, recap,
+ notification, ...(!notification ? { subagent: true } : {}), ...(tier ? { tier } : {}) })
+ this.opts.sendWeb({ type: 'turn_summary', agentId: this.opts.agentIdFor?.(sessionId) ?? sessionId,
+ dbSessionId: sessionId, payload: { summary, sessionId, notification, ...(tier ? { tier } : {}) } })
+ }
+ const durationS = st.startedAt === null ? null : Math.round((Date.now() - st.startedAt) / 1000)
+ const stats = this.turnStats.take(sessionId)
+ const decide = this.opts.decideTier
+ if (!decide) tell(null)
+ // Not news (a sub-agent's, a replay, a turn waiting on an answer): silent, and nobody is asked.
+ else if (!notification) tell('silent')
+ // The recap first, as the dial's decision always read it (services/devices.ts): Jev keeps 600 characters.
+ else this.tellOnceDecided(decide, ac, { sessionId, recap: recap || body, durationS, stats }, tell)
} else {
this.opts.changed?.(sessionId)
this.trace(sessionId, `${sid} summarizer returned NULL after ${ms}ms → done`)
diff --git a/cli/src/lib/e2ee/manager.test.ts b/cli/src/lib/e2ee/manager.test.ts
index e0d5cc828..1f8a3a510 100644
--- a/cli/src/lib/e2ee/manager.test.ts
+++ b/cli/src/lib/e2ee/manager.test.ts
@@ -840,6 +840,22 @@ describe('E2eeManager guests', () => {
// Nothing to seal: as wrapUp passes it.
expect(h.mgr.wrapFor('g', { type: 'node_status', payload: { online: true } })).toEqual({ type: 'node_status', payload: { online: true } })
+ // An agent's question goes to the apps over the relay (core/questions.ts): sealed for the group, which the
+ // guest cannot open, and for the guest's own session, though core.ts's ENCRYPTED_UP_TYPES does not name it.
+ const ask = { requestId: 'q1', questions: [{ q: 'Ship it?', options: ['Yes', 'No'] }] }
+ const asked = h.mgr.wrapUp({ type: 'commander_question', agentId: 'a1', dbSessionId: 's', payload: ask })
+ expect(asked.agentId).toBe('a1')
+ expect(JSON.stringify(asked.payload)).not.toContain('Ship it?')
+ expect(C.unwrapPayload(owner.session!.groupKey, (asked.payload as Wrapped).__e2e, 'commander_question', 's')).toEqual(ask)
+ expect(C.unwrapPayload(guest.session!.groupKey, (asked.payload as Wrapped).__e2e, 'commander_question', 's')).toBeNull()
+ const askedMine = h.mgr.wrapFor('g', { type: 'commander_question', dbSessionId: 's', payload: ask })!
+ expect(C.unwrapPayload(guest.session!.s2c, (askedMine.payload as Wrapped).__e2e, 'commander_question', 's')).toEqual(ask)
+ // Its close carries only a request id, and goes in the clear, as the devices are sent it.
+ const close = { type: 'commander_question_close', agentId: 'a1', dbSessionId: 's', payload: { requestId: 'q1' } }
+ expect(h.mgr.wrapUp(close)).toEqual(close)
+ expect(h.mgr.wrapFor('g', close)).toEqual(close)
+ expect(h.mgr.wrapUp({ payload: {} })).toEqual({ payload: {} })
+
// Sharing with lee ends: the key turns over, and the guest that stays is still handed a throwaway one.
h.mgr.untrustPeer(C.b64e(other.identity.pub))
owner.onRekey(h.lastFor('o', 'e2e_rekey')!)
diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.ts
index c86413be5..823b09b16 100644
--- a/cli/src/lib/e2ee/manager.ts
+++ b/cli/src/lib/e2ee/manager.ts
@@ -24,6 +24,18 @@ import { ReplayWindow } from './replayWindow.js'
type Frame = Record<string, unknown>
+/**
+ * `up` frames the web audience is sent sealed although core.ts's `ENCRYPTED_UP_TYPES` does not name them.
+ * `commander_question` carries the question and its option labels — user content, as a recap is — and since
+ * 2026-10-21 it goes to the owner's apps over the relay too (core/questions.ts), so a phone hears an agent
+ * waiting on it. Kept here rather than in core.ts, as `wrapCommander` keeps it for the devices: core.ts is
+ * hashed and pinned, while every reader opens by the envelope (any `payload.__e2e`: the phone's and the
+ * desktop's relay_session_crypto.dart `unwrapIncoming`), so none of them changes. Its close carries only a
+ * request id, and goes as the devices are sent it: in the clear.
+ */
+const SEALED_FOR_WEB: ReadonlySet<string> = new Set(['commander_question'])
+const sealsForWeb = (type: string | undefined): type is string => !!type && (C.isEncryptedUpType(type) || SEALED_FOR_WEB.has(type))
+
export type PairResult =
| { ok: true; label: string; fingerprint: string }
| { ok: false; error: 'NO_INTENT' | 'EXPIRED' | 'CODE_MISMATCH' | 'BACKEND_DOWN' | 'RATE_LIMITED' | 'BUSY' | 'TIMEOUT' | 'CANCELLED' }
@@ -373,7 +385,7 @@ export class E2eeManager {
const s = this.sessions.get(connId)
if (!s) return null
const type = frame.type as string | undefined
- if (!type || !C.isEncryptedUpType(type)) return frame
+ if (!sealsForWeb(type)) return frame
return { ...frame, payload: C.wrapPayload(s.s2c, 'p', s.s2cCounter++, type, frame.dbSessionId as string | undefined, frame.payload) }
}
@@ -382,7 +394,7 @@ export class E2eeManager {
/** Encrypt a broadcast `up` event under the group key if it carries user content; else pass through. */
wrapUp(frame: Frame): Frame {
const type = frame.type as string | undefined
- if (!type || !C.isEncryptedUpType(type)) return frame
+ if (!sealsForWeb(type)) return frame
const wrapped = C.wrapPayload(this.groupKey, 'g', this.groupCounter++, type, frame.dbSessionId as string | undefined, frame.payload, this.epoch)
return { ...frame, payload: wrapped }
}
diff --git a/cli/src/lib/notifyTier.spec.ts b/cli/src/lib/notifyTier.spec.ts
index 09d467750..015bf5532 100644
--- a/cli/src/lib/notifyTier.spec.ts
+++ b/cli/src/lib/notifyTier.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { JevUnavailable } from './jev/jevClient.js'
-import { createTierDecider, type TierInput } from './notifyTier.js'
+import { createTierDecider, fallbackTier, isTier, type TierInput } from './notifyTier.js'
const base: TierInput = {
agent: 'lamp', engine: 'codex', recap: 'Shipped the thing.', durationS: 300,
@@ -13,6 +13,17 @@ const make = (jev: any, extra: object = {}) => {
}
describe('notifyTier', () => {
+ it('reads only the three tiers as one', () => {
+ for (const tier of ['alert', 'list', 'silent']) expect(isTier(tier)).toBe(true)
+ for (const value of [undefined, null, '', 'ALERT', 'loud', 1, {}]) expect(isTier(value)).toBe(false)
+ })
+
+ it('falls back to a list entry for a turn of two minutes or more, silence for a shorter or unknown one', () => {
+ expect(fallbackTier(120)).toBe('list')
+ expect(fallbackTier(119)).toBe('silent')
+ expect(fallbackTier(null)).toBe('silent')
+ })
+
it('failed → alert by rule, Jev never asked', async () => {
const jev = vi.fn()
const { decide } = make(jev)
@@ -55,6 +66,9 @@ describe('notifyTier', () => {
expect(await slow.decide(base)).toMatchObject({ tier: 'list', by: 'fallback:timeout' })
const bad = make(vi.fn(async () => ({})))
expect(await bad.decide({ ...base, durationS: 10 })).toMatchObject({ tier: 'silent', by: 'fallback:no-answer' })
+ // Anything else it throws is not Jev saying why: the rule all the same, said as an error.
+ const broken = make(vi.fn(async () => { throw new Error('socket hang up') }))
+ expect(await broken.decide(base)).toMatchObject({ tier: 'list', by: 'fallback:error' })
})
it('jev null → fallback without calling anything', async () => {
diff --git a/cli/src/lib/notifyTier.ts b/cli/src/lib/notifyTier.ts
index 6ded53f29..bc84bab54 100644
--- a/cli/src/lib/notifyTier.ts
+++ b/cli/src/lib/notifyTier.ts
@@ -18,6 +18,12 @@ const WINDOW_MS = 30 * 60_000
const RECAP_MAX = 600
const LONG_TURN_S = 120
+/** Whether a frame's `tier` is one: anything else is read as no tier at all. */
+export const isTier = (value: unknown): value is Tier => value === 'alert' || value === 'list' || value === 'silent'
+
+/** The rule when Jev cannot say: a turn that ran 120 s or more is worth a glance later, a shorter one is not. */
+export const fallbackTier = (durationS: number | null): Tier => (durationS !== null && durationS >= LONG_TURN_S ? 'list' : 'silent')
+
const QUESTIONS: Record<string, JevChoice> = {
tier: {
type: 'choice',
@@ -72,10 +78,8 @@ export function createTierDecider(opts: {
if (input.onScreen) return rule('silent', 'onScreen')
if (!input.recap.trim()) return rule('silent', 'empty')
- const fallback = (reason: string) => {
- const long = input.durationS !== null && input.durationS >= LONG_TURN_S
- return finish(long ? 'list' : 'silent', `fallback:${reason}`, input.durationS === null ? 'duration unknown' : `${input.durationS}s`)
- }
+ const fallback = (reason: string) =>
+ finish(fallbackTier(input.durationS), `fallback:${reason}`, input.durationS === null ? 'duration unknown' : `${input.durationS}s`)
if (!opts.jev) return fallback('off')
const state = {
diff --git a/cli/src/services/devices.spec.ts b/cli/src/services/devices.spec.ts
index ffa0a92a9..72555f1c9 100644
--- a/cli/src/services/devices.spec.ts
+++ b/cli/src/services/devices.spec.ts
@@ -470,6 +470,19 @@ describe('what the windows say, reaching the dial', () => {
expect(decideTier.mock.calls.map(([i]) => i.durationS)).toEqual([60, 10])
})
+ it('follows a tier the recaps already decided, asking nobody again, and still silences the agent on screen', () => {
+ const decideTier = vi.fn()
+ const { port } = start({ decideTier })
+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'done', recap: 'Deployed', tier: 'list' } })
+ expect(calls('summary')).toEqual([['a1', 'Deployed', 'done', 'list', undefined, false]])
+ expect(decideTier).not.toHaveBeenCalled()
+ expect(logs).toContainEqual(expect.stringMatching(/^\[cable\] notify · .* · list · recaps · decided upstream · 0ms$/))
+ port.desk(['a2'], true)
+ port.card({ type: 'commander_event', agentId: 'a2', payload: { kind: 'summary', text: 'done', tier: 'alert' } })
+ expect(calls('summary').at(-1)).toEqual(['a2', 'done', 'done', 'silent', undefined, false])
+ expect(decideTier).not.toHaveBeenCalled()
+ })
+
const summaryCalls = () => calls('summary')
it('is silent without asking Jev when the agent is on screen or the turn was a sub-agent\'s', () => {
const decideTier = vi.fn()
diff --git a/cli/src/services/devices.ts b/cli/src/services/devices.ts
index c5cc40e49..e6d3bdda6 100644
--- a/cli/src/services/devices.ts
+++ b/cli/src/services/devices.ts
@@ -312,6 +312,13 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
const turn = ended.get(agentId) // a sub-agent's summary leaves the main turn's numbers alone
ended.delete(agentId)
const who = cableHost.describe(agentId)
+ // Decided once already, by the recaps (services/recaps.ts), for the phone as well: the dial follows it and
+ // nobody is asked again. A card without one (a cloud agent's, a recaps from before) is decided here.
+ if (event.tier) {
+ tally(who?.name ?? '', event.tier, 'recaps', 'decided upstream', 0)
+ void cable.summary(agentId, recap, event.text, event.tier, event.fullText, false)
+ return
+ }
// Returned, so the agent's next card waits behind this one (inOrder): a late recap must not follow turn.started.
return tierOf({ agent: who?.name ?? '', engine: who?.engine ?? '', recap, durationS: turn?.durationS ?? null,
stats: turn?.stats ?? {}, subagent: false, onScreen: false, failed: event.failed === true })
diff --git a/cli/src/services/recaps.spec.ts b/cli/src/services/recaps.spec.ts
index 7f473de76..5ba0e377e 100644
--- a/cli/src/services/recaps.spec.ts
+++ b/cli/src/services/recaps.spec.ts
@@ -6,8 +6,23 @@ import { emptyPorts, type RecapSession, type TurnLifecycle } from '../core/api.j
import { SUBAGENT_IDLE_MS, type CommanderMirrorOpts } from '../lib/commander.js'
import { deriveTurnSummary } from '../lib/deviceRecap.js'
import type { LiveEvent } from '../lib/normalize.js'
+import type { TierDecision, TierInput } from '../lib/notifyTier.js'
import { fakeCore } from '../testing/fakeCore.js'
-import { createRecaps, startRecaps } from './recaps.js'
+
+const jevMade = vi.hoisted(() => vi.fn())
+vi.mock('../lib/jev/jevClient.js', async (orig) => {
+ const actual = await orig<typeof import('../lib/jev/jevClient.js')>()
+ return {
+ ...actual,
+ createJevDecide: (options: Parameters<typeof actual.createJevDecide>[0]) => {
+ jevMade(options)
+ // The real hosted request and answer parsing, without discovering a key on this computer or calling OpenRouter.
+ return actual.createJevDecide({ ...options, key: async () => null })
+ },
+ }
+})
+
+const { createRecaps, startRecaps } = await import('./recaps.js')
const dirs: string[] = []
const temp = () => { const dir = mkdtempSync(join(tmpdir(), 'recaps-')); dirs.push(dir); return dir }
@@ -18,10 +33,11 @@ const started = (userMessage = 'what is the fix?') => ({ type: 'turn_started', p
const ended = { type: 'turn_ended', payload: {} } as LiveEvent
const flush = () => new Promise((done) => setTimeout(done, 0))
-function setup(over: Parameters<typeof createRecaps>[1] = {}) {
- const core = fakeCore({ dataDir: temp() })
+const decided = (tier: TierDecision['tier']): TierDecision => ({ tier, by: 'test', detail: '', ms: 0 })
+
+function setup(over: Parameters<typeof createRecaps>[1] = {}, core = fakeCore({ dataDir: temp() })) {
vi.mocked(core.transcripts.lastTurn).mockResolvedValue({ assistantText: 'The fix is in. Tests pass.', userMessage: 'what is the fix?' } as never)
- const recaps = createRecaps(core, { recapForce: false, recapWithoutDevice: () => true, ...over })
+ const recaps = createRecaps(core, { recapForce: false, recapWithoutDevice: () => true, decideTier: async () => decided('list'), ...over })
const opts = (recaps.mirror as unknown as { opts: CommanderMirrorOpts }).opts
const tell = (event: TurnLifecycle, seen = watching) => recaps.port.lifecycle(event, seen)
return { core, recaps, opts, tell }
@@ -240,4 +256,69 @@ describe('the recaps', () => {
expect(core.clients.turnSummary).not.toHaveBeenCalled()
expect(vi.mocked(core.clients.turnCard).mock.calls.at(-1)?.[0].payload).toEqual({ kind: 'done', text: 'done' })
})
+
+ describe('a finished turn\'s tier', () => {
+ afterEach(() => { delete process.env.HARNESS_NOTIFY_SMART })
+ const turn = async (tell: (event: TurnLifecycle, seen?: typeof watching) => void, seen: typeof watching & { remote?: boolean }) => {
+ // The core says the engine with every event (core/turns/recaps.ts `session`).
+ tell({ kind: 'events', session: { ...s1, engine: 'codex' }, events: [started()], replay: false }, seen)
+ tell({ kind: 'events', session: { ...s1, engine: 'codex' }, events: [ended], replay: false }, seen)
+ }
+
+ it('is decided once, with the agent and its engine, for the dial and the apps while a device listens', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const decideTier = vi.fn(async (_input: TierInput) => decided('alert'))
+ const { core, tell } = setup({ decideTier })
+ await turn(tell, watching)
+ await vi.waitFor(() => expect(core.clients.turnSummary).toHaveBeenCalled())
+ expect(decideTier).toHaveBeenCalledExactlyOnceWith({ agent: 'app', engine: 'codex', recap: expect.any(String),
+ durationS: 0, stats: {}, subagent: false, onScreen: false, failed: false })
+ expect(vi.mocked(core.clients.turnSummary).mock.calls[0][0]).toMatchObject({ payload: { tier: 'alert' } })
+ expect(vi.mocked(core.clients.turnCard).mock.calls.at(-1)?.[0].payload).toMatchObject({ kind: 'summary', tier: 'alert' })
+ })
+
+ it('is decided for an app away from this desk with no device, and for nobody when neither listens', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const decideTier = vi.fn(async () => decided('list'))
+ const away = setup({ decideTier })
+ await turn(away.tell, { device: false, active: false, remote: true })
+ await vi.waitFor(() => expect(away.core.clients.turnSummary).toHaveBeenCalled())
+ expect(vi.mocked(away.core.clients.turnSummary).mock.calls[0][0]).toMatchObject({ payload: { tier: 'list' } })
+ expect(decideTier).toHaveBeenCalledTimes(1)
+ const alone = setup({ decideTier })
+ await turn(alone.tell, { ...nobody, remote: false })
+ await vi.waitFor(() => expect(alone.core.clients.turnSummary).toHaveBeenCalled())
+ expect(decideTier).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(alone.core.clients.turnSummary).mock.calls[0][0].payload).not.toHaveProperty('tier')
+ })
+
+ it('builds the default decider without Jev when HARNESS_NOTIFY_SMART is 0, and with it otherwise', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ jevMade.mockClear()
+ process.env.HARNESS_NOTIFY_SMART = '0'
+ const off = setup({ decideTier: undefined })
+ expect(jevMade).not.toHaveBeenCalled()
+ await turn(off.tell, watching)
+ await vi.waitFor(() => expect(off.core.clients.turnSummary).toHaveBeenCalled())
+ // A turn under two minutes, with nobody to ask: the rule's silence.
+ expect(vi.mocked(off.core.clients.turnSummary).mock.calls[0][0]).toMatchObject({ payload: { tier: 'silent' } })
+ expect(log).toHaveBeenCalledWith(expect.stringMatching(/^\[recap\] notify · app · silent · fallback:off · 0s · \d+ms$/))
+ delete process.env.HARNESS_NOTIFY_SMART
+ setup({ decideTier: undefined })
+ expect(jevMade).toHaveBeenCalledTimes(1)
+ })
+
+ it('asks Harness\'s Jev through the core\'s signed-in backend, and sends what it chose', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const backend = vi.fn(async () => ({ status: 200, body: { data: { answers: {
+ tier: { choice: 'alert', probabilities: { alert: 0.7, list: 0.2, silent: 0.1 } },
+ } } } }))
+ const { core, tell } = setup({ decideTier: undefined }, fakeCore({ dataDir: temp(), account: { backend } }))
+ await turn(tell, watching)
+ await vi.waitFor(() => expect(core.clients.turnSummary).toHaveBeenCalled())
+ expect(backend).toHaveBeenCalledExactlyOnceWith('POST', '/api/route/jev', expect.objectContaining({
+ state: expect.objectContaining({ agent: 'app', engine: 'codex', duration_s: 0 }) }))
+ expect(vi.mocked(core.clients.turnSummary).mock.calls[0][0]).toMatchObject({ payload: { tier: 'alert' } })
+ })
+ })
})
diff --git a/cli/src/services/recaps.ts b/cli/src/services/recaps.ts
index 21beff9d7..85853285c 100644
--- a/cli/src/services/recaps.ts
+++ b/cli/src/services/recaps.ts
@@ -21,6 +21,8 @@ import type { CoreApi, CorePorts, RecapSession, RecapsPort, RecapWatchers, TurnC
import { AgentNotifications } from '../lib/agentNotifications.js'
import { CommanderMirror, SUBAGENT_IDLE_MS } from '../lib/commander.js'
import { deriveTurnSummary } from '../lib/deviceRecap.js'
+import { createJevDecide } from '../lib/jev/jevClient.js'
+import { createTierDecider, type TierDecision, type TierInput } from '../lib/notifyTier.js'
export interface RecapsOptions {
/** What a session's recaps hold, or whether its card is busy, may have changed: the recaps' own process
@@ -30,6 +32,8 @@ export interface RecapsOptions {
recapForce?: boolean
/** Whether a recap is cut for every turn, a device watching or not (`RECAP_WITHOUT_DEVICE`). */
recapWithoutDevice?: () => boolean
+ /** How loudly a finished turn tells. Defaults to rules plus Jev (off with `HARNESS_NOTIFY_SMART=0`). */
+ decideTier?: (input: TierInput) => Promise<TierDecision>
}
/** The service: its port, and the mirror itself for its process's own reads (services/recapsProcess.ts). */
@@ -52,6 +56,12 @@ export function createRecaps(core: CoreApi, options: RecapsOptions = {}): Recaps
// Shared by the turns' ends and the questions put to the person: a turn waiting on an answer is not
// announced as done (lib/agentNotifications.ts). The core tells this service both.
const notifications = new AgentNotifications()
+ // How loudly each finished turn tells (lib/notifyTier.ts), decided here once for the dial, the phone and the
+ // window: the `summary` card and the apps' `turn_summary` both carry it, so the devices ask nobody again.
+ const tierOf = options.decideTier ?? createTierDecider({
+ jev: process.env.HARNESS_NOTIFY_SMART === '0' ? null : createJevDecide({ backend: (method, path, body) => core.account.backend(method, path, body) }),
+ log: (line) => console.log(`[recap] ${line}`),
+ })
const mirror = new CommanderMirror({
notifications,
notifyWithoutDevice: true,
@@ -90,6 +100,15 @@ export function createRecaps(core: CoreApi, options: RecapsOptions = {}): Recaps
recapForce: options.recapForce ?? env.RECAP_FORCE,
alwaysGenerate: () => options.recapWithoutDevice?.() ?? env.RECAP_WITHOUT_DEVICE,
changed: options.changed,
+ // Asked only while someone away from this desk can hear it — a device, or an app over the relay. The window
+ // here does not read a tier, so with neither there is nothing to decide and no Jev decision to pay for.
+ decideTier: async (turn) => {
+ if (!watchers.device && !watchers.remote) return null
+ const session = sessions.get(turn.sessionId)
+ const decision = await tierOf({ agent: session?.name ?? '', engine: session?.engine ?? '', recap: turn.recap,
+ durationS: turn.durationS, stats: turn.stats, subagent: false, onScreen: false, failed: false })
+ return decision.tier
+ },
})
const know = (session: RecapSession): string => {
diff --git a/cli/src/services/recapsProcess.spec.ts b/cli/src/services/recapsProcess.spec.ts
index 8b2ce3db1..4ed9862b9 100644
--- a/cli/src/services/recapsProcess.spec.ts
+++ b/cli/src/services/recapsProcess.spec.ts
@@ -41,7 +41,9 @@ describe('the recaps in their own process', () => {
const handle = runRecapsService({
dataDir: temp(), socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',
run: (given) => { options = given; return service },
- create: (core, opts) => { api = core; return createRecaps(core, { recapForce: false, recapWithoutDevice: () => true, ...opts }) },
+ // Never Jev: a test reaches no network, and a key on this computer must not change what it sees.
+ create: (core, opts) => { api = core; return createRecaps(core, { recapForce: false, recapWithoutDevice: () => true,
+ decideTier: async () => ({ tier: 'list', by: 'test', detail: '', ms: 0 }), ...opts }) },
...over,
})
return { options: options!, api: api!, service, handle }
@@ -64,7 +66,7 @@ describe('the recaps in their own process', () => {
options.onEvent!(lifecycle({ kind: 'events', session: s1, events: [ended], replay: false }))
await vi.waitFor(() => expect(core.said('summary')).toHaveLength(1))
expect(core.query).toHaveBeenCalledWith('lastTurn', { sessionId: 's1' })
- expect(core.said('summary')[0]).toMatchObject({ frame: { type: 'turn_summary', agentId: 'a1', dbSessionId: 's1' } })
+ expect(core.said('summary')[0]).toMatchObject({ frame: { type: 'turn_summary', agentId: 'a1', dbSessionId: 's1', payload: { tier: 'list' } } })
expect(core.said('card').map(({ frame }) => frame.payload.kind)).toEqual(['turn_started', 'processing', 'done', 'summary'])
expect(core.said('recaps').at(-1)).toMatchObject({ sessionId: 's1', recaps: { busy: false, history: [expect.any(String)] } })
// A change is said once: a beat that changes nothing says nothing more.
@@ -120,14 +122,38 @@ describe('the recaps in their own process', () => {
expect(() => api.clients.turnSummary({ type: 'turn_summary' })).not.toThrow()
})
- it('runs on a core API that reaches the core only through these three ways, and holds no credential', async () => {
- const ways = { turnCard: vi.fn(), turnSummary: vi.fn(), lastTurn: vi.fn(async () => null) }
+ it('runs on a core API that reaches the core only through these four ways, and holds no credential', async () => {
+ const jev = vi.fn(async () => ({ status: 200, body: { data: {} } }))
+ const ways = { turnCard: vi.fn(), turnSummary: vi.fn(), lastTurn: vi.fn(async () => null), jev }
const api = recapsCoreApi('/data', ways)
expect(api.dataDir).toBe('/data')
expect(api.transcripts.lastTurn).toBe(ways.lastTurn)
expect(api.clients.turnCard).toBe(ways.turnCard)
expect(api.clients.turnSummary).toBe(ways.turnSummary)
await expect(api.account.accessToken()).rejects.toThrow('recaps holds no credential')
+ // Of the account's backend, Jev's route alone: anything else answers as no core to ask.
+ expect(await api.account.backend('POST', '/api/route/jev', { state: {} })).toEqual({ status: 200, body: { data: {} } })
+ expect(jev).toHaveBeenCalledWith({ state: {} })
+ expect(await api.account.backend('GET', '/api/route/jev')).toMatchObject({ status: 503 })
+ expect(await api.account.backend('POST', '/api/machines', {})).toMatchObject({ status: 503 })
+ expect(jev).toHaveBeenCalledTimes(1)
+ })
+
+ it('asks the core for Jev, and reads any answer that is not the backend\'s as unavailable', async () => {
+ const { options, api } = setup()
+ const unavailable = { status: 503, body: { error: 'SERVICE_UNAVAILABLE' } }
+ expect(await api.account.backend('POST', '/api/route/jev', { state: 1 })).toEqual(unavailable)
+ const core = connection()
+ options.onConnected!(core.core)
+ core.query.mockResolvedValueOnce({ status: 200, body: { data: { answers: {} } } })
+ expect(await api.account.backend('POST', '/api/route/jev', { state: 1 })).toEqual({ status: 200, body: { data: { answers: {} } } })
+ expect(core.query).toHaveBeenLastCalledWith('jev', { body: { state: 1 } })
+ core.query.mockResolvedValueOnce({ error: 'UNKNOWN_QUERY' })
+ expect(await api.account.backend('POST', '/api/route/jev', {})).toEqual(unavailable)
+ core.query.mockResolvedValueOnce({ status: 200, body: 'not an object' })
+ expect(await api.account.backend('POST', '/api/route/jev', {})).toEqual(unavailable)
+ core.query.mockRejectedValueOnce(new Error('the core went away'))
+ expect(await api.account.backend('POST', '/api/route/jev', {})).toEqual(unavailable)
})
it('runs on the real service process unless told otherwise', async () => {
diff --git a/cli/src/services/recapsProcess.ts b/cli/src/services/recapsProcess.ts
index 5f75bfcd9..b9e0d444f 100644
--- a/cli/src/services/recapsProcess.ts
+++ b/cli/src/services/recapsProcess.ts
@@ -14,6 +14,7 @@
* them each time it connects: a core that restarted holds nothing until then (core/recapsLink.ts).
*/
import type { CoreApi, TurnCardFrame, TurnLifecycle, TurnSummaryFrame, RecapWatchers } from '../core/api.js'
+import { HOSTED_JEV_PATH } from '../lib/jev/jevClient.js'
import type { LastTurnText } from '../lib/normalize.js'
import { processCoreApi } from './processCoreApi.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
@@ -35,19 +36,32 @@ export interface RecapsCoreWays {
turnCard(frame: TurnCardFrame): void
turnSummary(frame: TurnSummaryFrame): void
lastTurn(sessionId: string): Promise<LastTurnText | null>
+ /** Harness's Jev, for how loudly a turn ends: asked of the core, which signs it (core/recapsLink.ts). */
+ jev(body: unknown): Promise<{ status: number; body: Record<string, unknown> }>
}
/** The core API the recaps run on in their own process: the light services' (processCoreApi.ts), with
- * the three ways the recaps reach the core. */
+ * the ways the recaps reach the core. Of the account's backend, only Jev's route: the rest answers as
+ * every light service's does. */
export function recapsCoreApi(dataDir: string, ways: RecapsCoreWays): CoreApi {
const api = processCoreApi(dataDir, 'recaps')
return {
...api,
+ account: {
+ ...api.account,
+ backend: (method, path, body) => (method === 'POST' && path === HOSTED_JEV_PATH ? ways.jev(body) : api.account.backend(method, path, body)),
+ },
transcripts: { ...api.transcripts, lastTurn: ways.lastTurn },
clients: { ...api.clients, turnCard: ways.turnCard, turnSummary: ways.turnSummary },
}
}
+/** The core's answer to `jev`, as the backend's: a status and an object, or unavailable. */
+const backendAnswer = (answer: Record<string, unknown> | null): { status: number; body: Record<string, unknown> } =>
+ answer && typeof answer.status === 'number' && answer.body && typeof answer.body === 'object'
+ ? { status: answer.status, body: answer.body as Record<string, unknown> }
+ : { status: 503, body: { error: 'SERVICE_UNAVAILABLE' } }
+
/** Whether what the core sent reads as a lifecycle event: its kind, and the watchers beside it. */
const isLifecycle = (payload: Record<string, unknown>): payload is { event: TurnLifecycle; watchers: RecapWatchers } =>
!!payload.event && typeof payload.event === 'object' && typeof (payload.event as { kind?: unknown }).kind === 'string'
@@ -77,6 +91,8 @@ export function runRecapsService(options: RecapsServiceOptions): ServiceProcess
const answer = await core.query('lastTurn', { sessionId })
return answer.turn && typeof answer.turn === 'object' ? answer.turn as LastTurnText : null
},
+ // Unavailable with no core: the tier then falls back to its rule (lib/notifyTier.ts).
+ jev: async (body) => backendAnswer(core ? await core.query('jev', { body }).catch(() => null) : null),
}), { changed: tell })
const run = options.run ?? runServiceProcess
diff --git a/mobile/lib/demo/sample_runtime.dart b/mobile/lib/demo/sample_runtime.dart
index 5ce6cf4d1..51598146b 100644
--- a/mobile/lib/demo/sample_runtime.dart
+++ b/mobile/lib/demo/sample_runtime.dart
@@ -234,7 +234,13 @@ class SampleRuntime implements SampleHarnessHost {
name: harness.agent['name'] as String? ?? 'harness',
machine: machine.machine.displayName,
),
- (aborted: false, replay: false, subagent: false, reply: reply),
+ (
+ aborted: false,
+ replay: false,
+ subagent: false,
+ reply: reply,
+ tier: null,
+ ),
watching: () => _watching(ref),
);
}
diff --git a/mobile/lib/notify/agent_announcer.dart b/mobile/lib/notify/agent_announcer.dart
index 9a125cc46..ee59387c1 100644
--- a/mobile/lib/notify/agent_announcer.dart
+++ b/mobile/lib/notify/agent_announcer.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
@@ -12,6 +14,14 @@ import 'system_notices.dart';
/// Who the news is about, in the words the notice uses.
typedef NoticeAgent = ({AgentRef ref, String name, String machine});
+/// A turn that ended as news, waiting for the daemon to say how loudly.
+typedef _AwaitingTier = ({
+ NoticeAgent agent,
+ TurnEnd end,
+ bool Function() watching,
+ Timer timer,
+});
+
/// Carries out the dial's two rules — [decideDoneNotice] and
/// [decideQuestionNotice]: the chime, the unread mark, the system notice. The
/// notifier says what happened; this decides what it is worth and does it, so
@@ -21,6 +31,7 @@ class AgentAnnouncer {
required this.system,
Future<void> Function()? chime,
bool Function()? inFront,
+ this.tierWait = const Duration(seconds: 4),
}) : _chime = chime ?? _haptic,
_inFront = inFront ?? _appInFront;
@@ -28,6 +39,16 @@ class AgentAnnouncer {
final unread = AgentUnread();
final _asked = AskedQuestions();
+ /// How long a turn's end waits for the daemon's tier. It follows
+ /// `turn_ended` by the daemon's decision — at most a second of Jev — and the
+ /// relay; an older daemon's `turn_summary`, with none, comes at once. A
+ /// recap held for a sub-agent comes later than this, and its turn is told by
+ /// the old rule rather than not at all.
+ final Duration tierWait;
+
+ /// Turns that ended as news and wait for their tier: the newest per agent.
+ final _awaitingTier = <AgentRef, _AwaitingTier>{};
+
/// Agents with a notice up in the OS centre right now. What lets going to
/// an agent take its notice down — a notice about news already read is a
/// second thing to dismiss by hand — without asking the OS for one that was
@@ -70,6 +91,55 @@ class AgentAnnouncer {
// Whatever it was asking, the turn it asked in is over — and a turn that
// ends with nothing to say must not leave the question's mark standing.
questionClosed(agent.ref);
+ return _announceEnd(agent, end, watching: watching);
+ }
+
+ /// One turn ended, and the daemon says how loudly on the `turn_summary`
+ /// after it ([tierDecided]). The notice waits for that, at most [tierWait];
+ /// an end that is not news waits for nothing. Where the person is, is read
+ /// when it goes.
+ void turnEndedAwaitingTier(
+ NoticeAgent agent,
+ TurnEnd end, {
+ required bool Function() watching,
+ }) {
+ questionClosed(agent.ref);
+ _awaitingTier.remove(agent.ref)?.timer.cancel();
+ if (!isNewsEnd(end)) return;
+ _awaitingTier[agent.ref] = (
+ agent: agent,
+ end: end,
+ watching: watching,
+ timer: Timer(tierWait, () => tierDecided(agent.ref, null)),
+ );
+ }
+
+ /// The daemon said how loudly [ref]'s turn tells — or nothing ([tier] null:
+ /// an older daemon, or not in time). What was done, or null when no turn of
+ /// [ref]'s was waiting.
+ AgentNotice? tierDecided(AgentRef ref, NoticeTier? tier) {
+ final waiting = _awaitingTier.remove(ref);
+ if (waiting == null) return null;
+ waiting.timer.cancel();
+ // A question asked since — Command Code asks AFTER its turn — is what the
+ // person has to act on, and the daemon says no "done" over one either
+ // (cli `lib/agentNotifications.ts`).
+ if (_asked.asking(ref)) return AgentNotice.none;
+ final end = waiting.end;
+ return _announceEnd(waiting.agent, (
+ aborted: end.aborted,
+ replay: end.replay,
+ subagent: end.subagent,
+ reply: end.reply,
+ tier: tier,
+ ), watching: waiting.watching);
+ }
+
+ AgentNotice _announceEnd(
+ NoticeAgent agent,
+ TurnEnd end, {
+ required bool Function() watching,
+ }) {
final front = inFront;
final notice = decideDoneNotice(
end,
@@ -108,10 +178,25 @@ class AgentAnnouncer {
_withdraw(ref);
}
+ /// [machineId] said which of its questions are open at all — as an app
+ /// connects, after each one still open (cli `core/questions.ts`
+ /// `reannounceRemote`). One announced here and not among them was answered
+ /// while the phone was away: its mark and its notice go, as on a close.
+ void questionsOpen(String machineId, Set<String> requestIds) {
+ for (final MapEntry(key: ref, value: requestId)
+ in _asked.askedOn(machineId).entries) {
+ if (!requestIds.contains(requestId)) {
+ questionClosed(ref, requestId: requestId);
+ }
+ }
+ }
+
/// The person went to the agent — tapped its row, its notice, or came back
/// to the app on it. Whatever it was carrying has been read: the mark AND
- /// the notice still sitting in the OS centre come down together.
+ /// the notice still sitting in the OS centre come down together, and a
+ /// finished turn still waiting for its tier is not announced after.
void seen(AgentRef ref) {
+ _awaitingTier.remove(ref)?.timer.cancel();
unread.clear(ref);
_withdraw(ref);
}
@@ -125,11 +210,19 @@ class AgentAnnouncer {
/// Signed out: nothing any of it was about is this person's any more.
void reset() {
+ _cancelAwaiting();
unread.clearAll();
_asked.clear();
_posted.toList().forEach(_withdraw);
}
+ void _cancelAwaiting() {
+ for (final waiting in _awaitingTier.values) {
+ waiting.timer.cancel();
+ }
+ _awaitingTier.clear();
+ }
+
void _withdraw(AgentRef ref) {
if (_posted.remove(ref)) system.cancel(ref);
}
@@ -155,7 +248,10 @@ class AgentAnnouncer {
/// [system] is left alone: the shell may still be letting go of its
/// [SystemNotices.opened] after the notifier has gone.
- void dispose() => unread.dispose();
+ void dispose() {
+ _cancelAwaiting();
+ unread.dispose();
+ }
}
/// The text, cut to what a lock screen shows: its last paragraph — where an
diff --git a/mobile/lib/notify/agent_notice.dart b/mobile/lib/notify/agent_notice.dart
index ef8a932b2..5a12a7b4e 100644
--- a/mobile/lib/notify/agent_notice.dart
+++ b/mobile/lib/notify/agent_notice.dart
@@ -8,15 +8,20 @@ library;
/// showing — the desktop's `AgentUnread` rule.
enum NoticeKind { done, question }
-/// How far one piece of news goes — escalating, each step doing everything the
-/// one before it does.
+/// How far one piece of news goes. [chime], [mark] and [alert] escalate, each
+/// doing everything the one before it does; [filed] is a mark on its own.
enum AgentNotice {
/// Not news. Nothing at all.
none,
+ /// Worth a glance later, not now — the daemon's `list` tier. The agent is
+ /// marked, with no tap and no system notice: the dial files a drawer row
+ /// without a beep or a wake.
+ filed,
+
/// The person is looking straight at this agent. The tap still comes — the
- /// dial's beep ALWAYS sounds — but nothing is filed for later: they are
- /// already where the news is.
+ /// dial's beep ALWAYS sounded before the daemon sent a tier — but nothing is
+ /// filed for later: they are already where the news is.
chime,
/// The app is in front of the person, on something else. Chime, and mark the
@@ -27,8 +32,8 @@ enum AgentNotice {
/// notification — the dial waking its dark panel.
alert;
- bool get chimes => this != none;
- bool get marks => this == mark || this == alert;
+ bool get chimes => this == chime || this == mark || this == alert;
+ bool get marks => this == filed || this == mark || this == alert;
bool get alerts => this == alert;
}
diff --git a/mobile/lib/notify/done_notice.dart b/mobile/lib/notify/done_notice.dart
index 8e058bcb4..2abf8d55c 100644
--- a/mobile/lib/notify/done_notice.dart
+++ b/mobile/lib/notify/done_notice.dart
@@ -8,6 +8,31 @@ library;
import 'agent_notice.dart';
+/// How loudly the daemon says one finished turn should be told — decided once
+/// for every screen (`cli/src/lib/notifyTier.ts`: rules first, Jev for the
+/// rest, "list if it ran 120 s or more" when Jev cannot answer). It rides the
+/// `turn_summary` that follows `turn_ended`, as its payload's `tier`.
+enum NoticeTier {
+ /// News now: the dial beeps, wakes and files a drawer row.
+ alert,
+
+ /// Worth a glance later: a drawer row, no beep, no wake.
+ list,
+
+ /// Not news: nothing is filed.
+ silent,
+}
+
+/// Reads the wire's `"alert" | "list" | "silent"`. Null when absent or a word
+/// this build does not know — the old rule applies, as the dial's
+/// `ui_notify_summary` falls back to its flags.
+NoticeTier? noticeTierFrom(Object? raw) => switch (raw) {
+ 'alert' => NoticeTier.alert,
+ 'list' => NoticeTier.list,
+ 'silent' => NoticeTier.silent,
+ _ => null,
+};
+
/// One turn's end, as the machine socket reported it.
///
/// The flags come straight off the `turn_ended` frame. Every one of them is
@@ -32,10 +57,17 @@ typedef TurnEnd = ({
/// SUMMARY, never on the bare `done`: a tools-only or phantom turn has no
/// summary, stays silent, and the notification always has words in it.
String? reply,
+
+ /// The daemon's [NoticeTier] for this turn, from the `turn_summary` after
+ /// it — never on `turn_ended` itself, which leaves before it is decided.
+ /// Null from a daemon that does not decide one, or did not say in time:
+ /// every end that is news escalates as it always did.
+ NoticeTier? tier,
});
/// Reads a [TurnEnd] off one `turn_ended` frame. [reply] is what the phone saw
-/// the turn say (`SessionPreview.turnReply`), which the frame does not carry.
+/// the turn say (`SessionPreview.turnReply`), which the frame does not carry;
+/// nor its tier, which the `turn_summary` after it does.
TurnEnd turnEndFrom(
Map<String, dynamic> event,
Map<String, dynamic> payload, {
@@ -45,19 +77,38 @@ TurnEnd turnEndFrom(
replay: event['replay'] == true,
subagent: event['subagent'] == true,
reply: reply,
+ tier: null,
);
+/// Whether a turn's end is news at all — what no tier can change: not killed,
+/// not a replay, not a sub-agent's, and it said something.
+bool isNewsEnd(TurnEnd end) {
+ if (end.aborted || end.replay || end.subagent) return false;
+ final reply = end.reply;
+ return reply != null && reply.trim().isNotEmpty;
+}
+
/// Decides what one turn's end is worth.
///
/// [inFront] is whether the app is on screen at all; [watching] whether the
/// agent it is showing is the one that finished — only meaningful in front.
+///
+/// The [TurnEnd] flags say whether the end is news at all; its tier, when
+/// the daemon sends one, says how loud. As on the dial
+/// (`ui_notify_summary`, 2026-10-19): the agent on screen already shows its
+/// own news and gets nothing, a `list` turn is a mark with no tap and no
+/// notice, and only an `alert` goes as far as the phone's place allows.
AgentNotice decideDoneNotice(
TurnEnd end, {
required bool inFront,
required bool watching,
}) {
- if (end.aborted || end.replay || end.subagent) return AgentNotice.none;
- final reply = end.reply;
- if (reply == null || reply.trim().isEmpty) return AgentNotice.none;
- return escalate(inFront: inFront, watching: watching);
+ if (!isNewsEnd(end)) return AgentNotice.none;
+ final tier = end.tier;
+ if (tier == null) return escalate(inFront: inFront, watching: watching);
+ if (tier == NoticeTier.silent || (inFront && watching)) {
+ return AgentNotice.none;
+ }
+ if (tier == NoticeTier.list) return AgentNotice.filed;
+ return escalate(inFront: inFront, watching: false);
}
diff --git a/mobile/lib/notify/question_notice.dart b/mobile/lib/notify/question_notice.dart
index a816e8ccc..37de72b54 100644
--- a/mobile/lib/notify/question_notice.dart
+++ b/mobile/lib/notify/question_notice.dart
@@ -39,6 +39,9 @@ class AskedQuestions {
return true;
}
+ /// Whether a question is open on [ref] right now.
+ bool asking(AgentRef ref) => _asked.containsKey(_key(ref));
+
/// The question stopped being on screen — answered, or its turn ended. An
/// empty or null [requestId] means whichever one was open; a different one
/// is a stale close for a question already replaced, and is ignored.
@@ -55,6 +58,16 @@ class AskedQuestions {
return true;
}
+ /// The question each of [machineId]'s agents was last announced for.
+ Map<AgentRef, String> askedOn(String machineId) {
+ final prefix = '$machineId/';
+ return {
+ for (final MapEntry(:key, :value) in _asked.entries)
+ if (key.startsWith(prefix))
+ (machineId: machineId, agentId: key.substring(prefix.length)): value,
+ };
+ }
+
void clear() => _asked.clear();
}
diff --git a/mobile/lib/notify/system_notices.dart b/mobile/lib/notify/system_notices.dart
index 551192eb2..12cfdc961 100644
--- a/mobile/lib/notify/system_notices.dart
+++ b/mobile/lib/notify/system_notices.dart
@@ -80,12 +80,11 @@ Future<bool?> noticesEnabled(SystemNotices notices) =>
/// What the phone's notices are about, in the words Settings ▸ Notifications and Focus's tips use —
/// one source, so the two never promise different things.
///
-/// ⚠️ **Not "when a harness needs you"** (2026-10-14). That notice ([NoticeKind.question]) is fed
-/// by `commander_question`, which the daemon sends only to the dial and to its own computer
-/// (`cli/src/core/questions.ts`: `sendCommander`, `sendLocal`) — never to a phone over the relay.
-/// What does reach one is a turn's end and a device joining the account. Say questions again here
-/// once that frame is carried to phones.
-const noticesWhen = 'a harness finishes, or a new device joins your account';
+/// "Needs you" since 2026-10-21: `commander_question` ([NoticeKind.question]) reaches a phone over the
+/// relay (`cli/src/core/questions.ts` `sendRemote`). From 2026-10-14 until then the daemon sent it only
+/// to the dial and its own computer, and this did not promise it.
+const noticesWhen =
+ 'a harness finishes or needs you, or a new device joins your account';
/// What a device notice's payload starts with; the device's key follows. An agent notice's payload
/// is `machine\nagent`, so the two never read as each other.
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 2c386fd8b..6056795c4 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -10286,10 +10286,10 @@ class AppNotifier extends ChangeNotifier {
unawaited(_loadMachineData(machine, force: true));
}
break;
- // An agent stopped and is waiting on the person. Ignored by this window
- // until now, even though the daemon had already shaped the question for
- // the dial — `sendCommander` is device-only, so it never came down this
- // wire at all.
+ // An agent stopped and is waiting on the person. Over the relay since
+ // 2026-10-21 (cli core/questions.ts `sendRemote`); a daemon from before
+ // shaped it for the dial and its own computer only, so it never came
+ // down this wire.
case 'commander_question':
final agentId = _eventAgentId(machine, event, payload);
if (agentId != null) {
@@ -10339,6 +10339,18 @@ class AppNotifier extends ChangeNotifier {
), requestId: requestId is String ? requestId : null);
}
break;
+ // Which questions the machine has open at all, said as an app connects,
+ // after each one still open (cli core/questions.ts `reannounceRemote`).
+ // One held here and not among them was answered while the phone was away.
+ case 'commander_questions_open':
+ final requestIds = payload['requestIds'];
+ if (requestIds is! List) return;
+ final open = requestIds.whereType<String>().toSet();
+ machine.blockedAgents.removeWhere(
+ (_, asked) => !open.contains(asked.requestId),
+ );
+ agentNotices.questionsOpen(machine.machine.machineId, open);
+ break;
case 'turn_started':
case 'turn_heartbeat':
var changed = false;
@@ -10384,6 +10396,11 @@ class AppNotifier extends ChangeNotifier {
}
}
break;
+ // The recap that follows a turn's end. Nothing here draws it: it says
+ // how loudly that end tells.
+ case 'turn_summary':
+ _announceTurnTier(machine, event, payload);
+ return;
// A program in a harness's pane opened a page (Claude Code's `/login`) while this phone was the one
// typing there (cli core/terminals/browser.ts): it opens on this phone. Nothing here to redraw.
case 'browser_open':
@@ -10503,7 +10520,8 @@ class AppNotifier extends ChangeNotifier {
machine.agents.where((a) => a.id == agentId).firstOrNull;
/// One agent's turn ended: tell the person as the dial would — see
- /// `notify/done_notice.dart` for when that is a tap, a mark or a notice.
+ /// `notify/done_notice.dart` for when that is a tap, a mark or a notice —
+ /// once the daemon's `turn_summary` says how loudly ([_announceTurnTier]).
void _announceTurnEnd(
MachineState machine,
String agentId,
@@ -10513,7 +10531,7 @@ class AppNotifier extends ChangeNotifier {
final agent = _knownAgent(machine, agentId);
if (agent == null) return;
final who = _noticeAgent(machine, agent);
- agentNotices.turnEnded(
+ agentNotices.turnEndedAwaitingTier(
who,
turnEndFrom(
event,
@@ -10526,6 +10544,23 @@ class AppNotifier extends ChangeNotifier {
);
}
+ /// The recap after a turn's end, with how loudly the daemon says it tells
+ /// (`tier`, cli `services/recaps.ts`): the turn waiting for it is announced
+ /// now. A daemon that decides none sends its recap without one, and the old
+ /// rule goes at once.
+ void _announceTurnTier(
+ MachineState machine,
+ Map<String, dynamic> event,
+ Map<String, dynamic> payload,
+ ) {
+ final agentId = _eventAgentId(machine, event, payload);
+ if (agentId == null) return;
+ agentNotices.tierDecided((
+ machineId: machine.machine.machineId,
+ agentId: agentId,
+ ), noticeTierFrom(payload['tier']));
+ }
+
/// An agent stopped to ask the person something — see
/// `notify/question_notice.dart`.
void _announceQuestion(MachineState machine, PendingQuestion asked) {
diff --git a/mobile/lib/terminal/question_pane.dart b/mobile/lib/terminal/question_pane.dart
index f69c43b85..1c022769b 100644
--- a/mobile/lib/terminal/question_pane.dart
+++ b/mobile/lib/terminal/question_pane.dart
@@ -1,12 +1,12 @@
/// Read an open question dialog straight off the terminal's own buffer.
///
/// ⚠️ **Why this exists at all.** The daemon already watches the pane and
-/// shapes the question — but it publishes it on `commander_question`, which
-/// goes out over `sendCommander` (`webEligible: false`) and `sendLocal`
-/// (loopback only). A phone attached over the relay is in neither audience, so
-/// that frame never arrives here. Until `commander_question` is carried over an
-/// encrypted up-type, the buffer this app already holds is the only source it
-/// has.
+/// shapes the question on `commander_question`, which reaches a phone over the
+/// relay, sealed, since 2026-10-21 (cli core/questions.ts `sendRemote`). A
+/// daemon from before sent it only over `sendCommander` (`webEligible: false`)
+/// and `sendLocal` (loopback only), so from one of those the buffer this app
+/// already holds is the only source it has; and the keyboard on this page reads
+/// the dialog as this very buffer draws it either way.
///
/// ⚠️ **This does NOT feed `blockedAgents`.** The amber ring on a tile, and the
/// Needs input picker, still read the daemon's frames — an agent this window is
diff --git a/mobile/lib/terminal/question_pane_watcher.dart b/mobile/lib/terminal/question_pane_watcher.dart
index f8f2eb3d5..80f0d6292 100644
--- a/mobile/lib/terminal/question_pane_watcher.dart
+++ b/mobile/lib/terminal/question_pane_watcher.dart
@@ -11,8 +11,8 @@ import 'question_pane.dart';
/// ⚠️ **A local read, not a second source of truth.** The daemon's own watcher
/// still runs, still drives `blockedAgents`, and still answers from wherever a
/// person actually answers. This only tells the page it is attached to whether
-/// the pane in front of it is showing a dialog, because the daemon's frame
-/// cannot reach a phone on the relay — see [readQuestionPane].
+/// the pane in front of it is showing a dialog, which a daemon from before
+/// 2026-10-21 never sends a phone on the relay — see [readQuestionPane].
///
/// ⚠️ **Debounced on both edges, and the two are not symmetric.** A redraw
/// arrives as a burst of writes and a capture taken mid-repaint parses as
diff --git a/mobile/test/notify/agent_announcer_test.dart b/mobile/test/notify/agent_announcer_test.dart
index 7e2a01669..e3f09b4b6 100644
--- a/mobile/test/notify/agent_announcer_test.dart
+++ b/mobile/test/notify/agent_announcer_test.dart
@@ -1,9 +1,11 @@
+import 'package:fake_async/fake_async.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/core/last_opened_agent.dart';
import 'package:harness_mobile/notify/agent_announcer.dart';
import 'package:harness_mobile/notify/agent_notice.dart';
+import 'package:harness_mobile/notify/done_notice.dart';
import 'package:harness_mobile/notify/system_notices.dart';
class _RecordingNotices implements SystemNotices {
@@ -37,6 +39,7 @@ void main() {
replay: false,
subagent: false,
reply: 'Looked at the form.\n\nFixed the login screen and pushed.',
+ tier: null,
);
late _RecordingNotices system;
@@ -97,6 +100,7 @@ void main() {
replay: false,
subagent: true,
reply: 'x',
+ tier: null,
), watching: () => false);
expect(chimes, 0);
@@ -104,6 +108,230 @@ void main() {
expect(system.shown, isEmpty);
});
+ group('with the daemon\'s tier', () {
+ TurnEnd tiered(NoticeTier tier) => (
+ aborted: news.aborted,
+ replay: news.replay,
+ subagent: news.subagent,
+ reply: news.reply,
+ tier: tier,
+ );
+
+ test('list, away: the agent is marked, no notice is posted', () {
+ front = false;
+ final notice = announcer.turnEnded(
+ agent,
+ tiered(NoticeTier.list),
+ watching: () => false,
+ );
+
+ expect(notice, AgentNotice.filed);
+ expect(chimes, 0);
+ expect(announcer.unread.kindFor(ref), NoticeKind.done);
+ expect(system.shown, isEmpty);
+ });
+
+ test('list, elsewhere in the app: a mark with no tap', () {
+ announcer.turnEnded(agent, tiered(NoticeTier.list), watching: () => false);
+
+ expect(chimes, 0);
+ expect(announcer.unread.contains(ref), isTrue);
+ expect(system.shown, isEmpty);
+ });
+
+ test('alert, away: a mark and the notice', () {
+ front = false;
+ announcer.turnEnded(agent, tiered(NoticeTier.alert), watching: () => false);
+
+ expect(announcer.unread.contains(ref), isTrue);
+ expect(system.shown, hasLength(1));
+ expect(system.shown.single.body, 'Fixed the login screen and pushed.');
+ });
+
+ test('alert, on the agent being watched: nothing at all', () {
+ announcer.turnEnded(agent, tiered(NoticeTier.alert), watching: () => true);
+
+ expect(chimes, 0);
+ expect(announcer.unread.count, 0);
+ expect(system.shown, isEmpty);
+ });
+
+ test('silent, away: nothing at all', () {
+ front = false;
+ announcer.turnEnded(agent, tiered(NoticeTier.silent), watching: () => false);
+
+ expect(chimes, 0);
+ expect(announcer.unread.count, 0);
+ expect(system.shown, isEmpty);
+ });
+
+ test('a list turn still takes down the question its turn asked', () {
+ announcer.questionAsked(
+ agent,
+ requestId: 'q1',
+ prompt: 'Which branch?',
+ watching: () => false,
+ );
+ announcer.turnEnded(agent, tiered(NoticeTier.list), watching: () => false);
+
+ expect(announcer.unread.kindFor(ref), NoticeKind.done);
+ });
+ });
+
+ group('waiting for the daemon\'s tier', () {
+ const wait = Duration(seconds: 4);
+
+ /// The announcer under fake time, so the wait for a tier runs out on
+ /// command. Built inside [body]'s zone, as its timer must be.
+ void inFakeTime(void Function(FakeAsync time, AgentAnnouncer a) body) {
+ fakeAsync((time) {
+ final a = AgentAnnouncer(
+ system: system,
+ chime: () async => chimes++,
+ inFront: () => front,
+ tierWait: wait,
+ );
+ body(time, a);
+ a.dispose();
+ });
+ }
+
+ test('a turn\'s end waits for its tier, and goes by it', () {
+ inFakeTime((time, a) {
+ front = false;
+ a.turnEndedAwaitingTier(agent, news, watching: () => false);
+ expect(a.unread.count, 0);
+ expect(system.shown, isEmpty);
+ expect(a.tierDecided(ref, NoticeTier.list), AgentNotice.filed);
+ expect(a.unread.kindFor(ref), NoticeKind.done);
+ expect(system.shown, isEmpty, reason: 'a list entry is no notice');
+ time.elapse(wait * 2);
+ expect(system.shown, isEmpty, reason: 'told once');
+ });
+ });
+
+ test('an older daemon\'s recap, with no tier, goes by the old rule at once', () {
+ inFakeTime((time, a) {
+ front = false;
+ a.turnEndedAwaitingTier(agent, news, watching: () => false);
+ expect(a.tierDecided(ref, null), AgentNotice.alert);
+ expect(system.shown, hasLength(1));
+ });
+ });
+
+ test('a tier that never comes: the old rule once the wait runs out', () {
+ inFakeTime((time, a) {
+ front = false;
+ a.turnEndedAwaitingTier(agent, news, watching: () => false);
+ time.elapse(wait - const Duration(milliseconds: 1));
+ expect(system.shown, isEmpty);
+ time.elapse(const Duration(milliseconds: 1));
+ expect(system.shown, hasLength(1));
+ expect(a.tierDecided(ref, NoticeTier.alert), isNull, reason: 'nothing waits any more');
+ });
+ });
+
+ test('reads where the person is when it goes, not when the turn ended', () {
+ inFakeTime((time, a) {
+ front = false;
+ a.turnEndedAwaitingTier(agent, news, watching: () => true);
+ front = true;
+ expect(a.tierDecided(ref, NoticeTier.alert), AgentNotice.none);
+ expect(chimes, 0);
+ expect(system.shown, isEmpty);
+ });
+ });
+
+ test('an end that is not news waits for nothing, and a recap for it does nothing', () {
+ inFakeTime((time, a) {
+ front = false;
+ a.turnEndedAwaitingTier(agent, (
+ aborted: false,
+ replay: false,
+ subagent: true,
+ reply: 'x',
+ tier: null,
+ ), watching: () => false);
+ expect(a.tierDecided(ref, NoticeTier.alert), isNull);
+ time.elapse(wait * 2);
+ expect(a.unread.count, 0);
+ expect(system.shown, isEmpty);
+ });
+ });
+
+ test('a question asked while it waits is what stands: no "done" over it', () {
+ inFakeTime((time, a) {
+ front = false;
+ a.turnEndedAwaitingTier(agent, news, watching: () => false);
+ a.questionAsked(
+ agent,
+ requestId: 'q1',
+ prompt: 'Which branch?',
+ watching: () => false,
+ );
+ expect(a.tierDecided(ref, NoticeTier.alert), AgentNotice.none);
+ expect(a.unread.kindFor(ref), NoticeKind.question);
+ expect(system.shown.map((m) => m.kind), [NoticeKind.question]);
+ });
+ });
+
+ test('the turn\'s end takes down the question it asked in, at once', () {
+ inFakeTime((time, a) {
+ a.questionAsked(
+ agent,
+ requestId: 'q1',
+ prompt: 'Which branch?',
+ watching: () => false,
+ );
+ a.turnEndedAwaitingTier(agent, news, watching: () => false);
+ expect(a.unread.contains(ref), isFalse);
+ });
+ });
+
+ test('going to the agent while it waits: nothing is announced after', () {
+ inFakeTime((time, a) {
+ front = false;
+ a.turnEndedAwaitingTier(agent, news, watching: () => false);
+ a.seen(ref);
+ time.elapse(wait * 2);
+ expect(a.tierDecided(ref, NoticeTier.alert), isNull);
+ expect(system.shown, isEmpty);
+ });
+ });
+
+ test('a newer end replaces the one waiting, and is told once', () {
+ inFakeTime((time, a) {
+ front = false;
+ a.turnEndedAwaitingTier(agent, news, watching: () => false);
+ time.elapse(wait ~/ 2);
+ a.turnEndedAwaitingTier(agent, (
+ aborted: false,
+ replay: false,
+ subagent: false,
+ reply: 'Second answer.',
+ tier: null,
+ ), watching: () => false);
+ time.elapse(wait ~/ 2);
+ expect(system.shown, isEmpty, reason: 'the first one\'s wait was dropped');
+ time.elapse(wait);
+ expect(system.shown.map((m) => m.body), ['Second answer.']);
+ });
+ });
+
+ test('signing out or going away drops every turn still waiting', () {
+ inFakeTime((time, a) {
+ front = false;
+ a.turnEndedAwaitingTier(agent, news, watching: () => false);
+ a.reset();
+ time.elapse(wait * 2);
+ expect(system.shown, isEmpty);
+ a.turnEndedAwaitingTier(agent, news, watching: () => false);
+ });
+ // [inFakeTime] disposed it with that turn still waiting: no timer outlives it.
+ expect(system.shown, isEmpty);
+ });
+ });
+
test('an agent is one mark however many turns it finished', () {
announcer.turnEnded(agent, news, watching: () => false);
announcer.turnEnded(agent, news, watching: () => false);
@@ -157,6 +385,38 @@ void main() {
watching: () => watching,
);
+ test('one answered while the phone was away goes, mark and notice; one still open stays', () {
+ const other = (machineId: 'm', agentId: 'b');
+ const elsewhere = (machineId: 'm2', agentId: 'a');
+ front = false;
+ ask();
+ announcer.questionAsked(
+ (ref: other, name: 'Other', machine: 'MacBook'),
+ requestId: 'q2',
+ prompt: 'Which branch?',
+ watching: () => false,
+ );
+ announcer.questionAsked(
+ (ref: elsewhere, name: 'Far', machine: 'Mini'),
+ requestId: 'q3',
+ prompt: 'Merge?',
+ watching: () => false,
+ );
+ announcer.questionsOpen('m', {'q2'});
+ expect(announcer.unread.contains(ref), isFalse);
+ expect(system.cancelled, [ref]);
+ expect(announcer.unread.kindFor(other), NoticeKind.question);
+ expect(announcer.unread.kindFor(elsewhere), NoticeKind.question, reason: 'another machine said nothing of it');
+ // Heard again later, it is news again: it is a question asked anew.
+ expect(ask(), AgentNotice.alert);
+ });
+
+ test('an open list leaves a finished turn\'s mark alone', () {
+ announcer.turnEnded(agent, news, watching: () => false);
+ announcer.questionsOpen('m', {});
+ expect(announcer.unread.kindFor(ref), NoticeKind.done);
+ });
+
test('a new question elsewhere: a chime and a question mark', () {
expect(ask(), AgentNotice.mark);
expect(chimes, 1);
@@ -218,6 +478,7 @@ void main() {
replay: false,
subagent: false,
reply: null,
+ tier: null,
), watching: () => false);
expect(announcer.unread.contains(ref), isFalse);
expect(ask(), AgentNotice.mark, reason: 'a new turn may ask it again');
diff --git a/mobile/test/notify/announcer_lifecycle_test.dart b/mobile/test/notify/announcer_lifecycle_test.dart
index ac813f9fa..b654ff14d 100644
--- a/mobile/test/notify/announcer_lifecycle_test.dart
+++ b/mobile/test/notify/announcer_lifecycle_test.dart
@@ -17,6 +17,7 @@ void main() {
replay: false,
subagent: false,
reply: 'Fixed the login screen.',
+ tier: null,
);
// First, and deliberately before any `testWidgets`: with no binding at all
diff --git a/mobile/test/notify/app_notice_test.dart b/mobile/test/notify/app_notice_test.dart
index e3e7a4e49..3f8ea7d9e 100644
--- a/mobile/test/notify/app_notice_test.dart
+++ b/mobile/test/notify/app_notice_test.dart
@@ -8,13 +8,16 @@ import '../agent_pager_fixture.dart';
/// The dial's rule, end to end: frames off the machine socket into the marks
/// the phone draws.
void main() {
- /// One whole turn of [agentId], as the machine streams it.
+ /// One whole turn of [agentId], as the machine streams it: its end, then
+ /// the recap the daemon always sends after it, with [summary] as its
+ /// payload (a `tier` from a daemon that decides one). Null: no recap.
Future<void> turn(
AppNotifier app,
String agentId, {
String? reply = 'Fixed the login screen.',
Map<String, dynamic> end = const {},
Map<String, dynamic> endPayload = const {},
+ Map<String, dynamic>? summary = const {},
}) async {
Future<void> send(String type, [Map<String, dynamic> payload = const {}]) =>
app.handleEventForTest('m', {
@@ -26,6 +29,7 @@ void main() {
await send('turn_started', {'userMessage': 'fix it'});
if (reply != null) await send('text_delta', {'content': reply});
await send('turn_ended', endPayload);
+ if (summary != null) await send('turn_summary', summary);
}
Future<void> ask(AppNotifier app, String agentId, {String id = 'q1'}) =>
@@ -83,6 +87,41 @@ void main() {
expect(app.agentNotices.unread.count, 0);
});
+ test('the daemon\'s tier on the recap after a turn decides the mark', () async {
+ await turn(app, 'b', summary: {'tier': 'silent'});
+ expect(unread(app, 'b'), isFalse);
+ await turn(app, 'b', summary: {'tier': 'list'});
+ expect(kindOf(app, 'b'), NoticeKind.done);
+ });
+
+ test('the agent on screen is not marked whatever the tier', () async {
+ await turn(app, 'a', summary: {'tier': 'alert'});
+ await turn(app, 'a', summary: {'tier': 'list'});
+ expect(unread(app, 'a'), isFalse);
+ });
+
+ test('a turn\'s mark waits for its recap, and a recap with no turn waiting marks nothing', () async {
+ await turn(app, 'b', summary: null);
+ expect(unread(app, 'b'), isFalse);
+ await app.handleEventForTest('m', {
+ 'type': 'turn_summary',
+ 'agentId': 'b',
+ 'payload': {'tier': 'list'},
+ });
+ expect(unread(app, 'b'), isTrue);
+ app.agentNotices.unread.clearAll();
+ await app.handleEventForTest('m', {
+ 'type': 'turn_summary',
+ 'agentId': 'b',
+ 'payload': {'tier': 'alert'},
+ });
+ await app.handleEventForTest('m', {
+ 'type': 'turn_summary',
+ 'payload': {'tier': 'alert'},
+ });
+ expect(app.agentNotices.unread.count, 0);
+ });
+
test('a turn with nothing to say does not borrow the last one', () async {
await turn(app, 'b');
app.agentNotices.unread.clearAll();
@@ -140,6 +179,33 @@ void main() {
expect(unread(app, 'b'), isFalse);
});
+ Future<void> openOnes(AppNotifier app, Object? requestIds) =>
+ app.handleEventForTest('m', {
+ 'type': 'commander_questions_open',
+ 'payload': {'requestIds': requestIds},
+ });
+
+ test('the machine\'s open list takes down one answered while away, and keeps the rest', () async {
+ await ask(app, 'b');
+ await ask(app, 'c', id: 'q2');
+ await openOnes(app, ['q2', 7]);
+ expect(unread(app, 'b'), isFalse);
+ expect(app.stateOf('m')!.blockedAgents.containsKey('b'), isFalse);
+ expect(kindOf(app, 'c'), NoticeKind.question);
+ expect(app.stateOf('m')!.blockedAgents['c']?.requestId, 'q2');
+ });
+
+ test('an open list that is not a list changes nothing', () async {
+ await ask(app, 'b');
+ await openOnes(app, 'q1');
+ await app.handleEventForTest('m', {
+ 'type': 'commander_questions_open',
+ 'payload': <String, dynamic>{},
+ });
+ expect(kindOf(app, 'b'), NoticeKind.question);
+ expect(app.stateOf('m')!.blockedAgents.containsKey('b'), isTrue);
+ });
+
test('a reconnect re-announcing it does not make it new', () async {
await ask(app, 'b');
app.agentNotices.unread.clearAll();
diff --git a/mobile/test/notify/done_notice_test.dart b/mobile/test/notify/done_notice_test.dart
index de98eb07f..0efca1592 100644
--- a/mobile/test/notify/done_notice_test.dart
+++ b/mobile/test/notify/done_notice_test.dart
@@ -11,7 +11,14 @@ void main() {
bool replay = false,
bool subagent = false,
String? reply = 'Fixed the login screen.',
- }) => (aborted: aborted, replay: replay, subagent: subagent, reply: reply);
+ NoticeTier? tier,
+ }) => (
+ aborted: aborted,
+ replay: replay,
+ subagent: subagent,
+ reply: reply,
+ tier: tier,
+ );
AgentNotice decide(TurnEnd e, {bool inFront = true, bool watching = false}) =>
decideDoneNotice(e, inFront: inFront, watching: watching);
@@ -58,7 +65,13 @@ void main() {
<String, dynamic>{},
reply: 'done',
);
- expect(e, (aborted: false, replay: false, subagent: false, reply: 'done'));
+ expect(e, (
+ aborted: false,
+ replay: false,
+ subagent: false,
+ reply: 'done',
+ tier: null,
+ ));
});
test('the flags are read where the daemon puts them', () {
@@ -67,6 +80,124 @@ void main() {
{'aborted': true},
reply: null,
);
- expect(e, (aborted: true, replay: true, subagent: true, reply: null));
+ expect(e, (
+ aborted: true,
+ replay: true,
+ subagent: true,
+ reply: null,
+ tier: null,
+ ));
+ });
+
+ group('the daemon\'s tier', () {
+ test('is never read off turn_ended: the turn_summary after it says it', () {
+ final e = turnEndFrom(
+ {'type': 'turn_ended', 'agentId': 'a', 'tier': 'alert'},
+ {'tier': 'alert'},
+ reply: 'done',
+ );
+ expect(e.tier, isNull);
+ });
+
+ test('reads the wire\'s three words', () {
+ expect(noticeTierFrom('alert'), NoticeTier.alert);
+ expect(noticeTierFrom('list'), NoticeTier.list);
+ expect(noticeTierFrom('silent'), NoticeTier.silent);
+ });
+
+ test('a word this build does not know reads as no tier at all', () {
+ for (final raw in [null, '', 'loud', 'ALERT', 2, true]) {
+ expect(noticeTierFrom(raw), isNull, reason: '$raw');
+ }
+ });
+
+ test('news is what no tier can change: alive, live, the main agent\'s, said something', () {
+ expect(isNewsEnd(end()), isTrue);
+ for (final e in [
+ end(aborted: true),
+ end(replay: true),
+ end(subagent: true),
+ end(reply: null),
+ end(reply: ' \n'),
+ ]) {
+ expect(isNewsEnd(e), isFalse, reason: '$e');
+ }
+ });
+
+ test('never makes news of a turn the flags say is not news', () {
+ for (final tier in NoticeTier.values) {
+ for (final e in [
+ end(aborted: true, tier: tier),
+ end(replay: true, tier: tier),
+ end(subagent: true, tier: tier),
+ end(reply: null, tier: tier),
+ end(reply: ' ', tier: tier),
+ ]) {
+ for (final inFront in [true, false]) {
+ expect(
+ decide(e, inFront: inFront),
+ AgentNotice.none,
+ reason: '$e',
+ );
+ }
+ }
+ }
+ });
+
+ test('silent: nothing, wherever the phone is', () {
+ for (final (inFront, watching) in [
+ (true, true),
+ (true, false),
+ (false, false),
+ ]) {
+ expect(
+ decide(
+ end(tier: NoticeTier.silent),
+ inFront: inFront,
+ watching: watching,
+ ),
+ AgentNotice.none,
+ );
+ }
+ });
+
+ test('list: a mark with no tap and no notice, even away', () {
+ for (final inFront in [true, false]) {
+ final notice = decide(end(tier: NoticeTier.list), inFront: inFront);
+ expect(notice, AgentNotice.filed);
+ expect(notice.marks, isTrue);
+ expect(notice.chimes, isFalse);
+ expect(notice.alerts, isFalse);
+ }
+ });
+
+ test('alert: as far as the phone\'s place allows', () {
+ expect(decide(end(tier: NoticeTier.alert)), AgentNotice.mark);
+ expect(
+ decide(end(tier: NoticeTier.alert), inFront: false),
+ AgentNotice.alert,
+ );
+ });
+
+ test('the agent on screen gets nothing — not even the tap', () {
+ for (final tier in NoticeTier.values) {
+ expect(
+ decide(end(tier: tier), watching: true),
+ AgentNotice.none,
+ reason: '$tier',
+ );
+ }
+ });
+
+ test('watching only counts in front', () {
+ expect(
+ decide(end(tier: NoticeTier.alert), inFront: false, watching: true),
+ AgentNotice.alert,
+ );
+ expect(
+ decide(end(tier: NoticeTier.list), inFront: false, watching: true),
+ AgentNotice.filed,
+ );
+ });
});
}
diff --git a/mobile/test/notify/phone_on_screen_test.dart b/mobile/test/notify/phone_on_screen_test.dart
index bee036ac7..5c71b8343 100644
--- a/mobile/test/notify/phone_on_screen_test.dart
+++ b/mobile/test/notify/phone_on_screen_test.dart
@@ -52,6 +52,8 @@ void main() {
('turn_started', {'userMessage': 'hi'}),
('text_delta', {'content': 'Hello!'}),
('turn_ended', <String, dynamic>{}),
+ // The recap the daemon sends after every turn's end, which the mark waits for.
+ ('turn_summary', <String, dynamic>{}),
]) {
await app.handleEventForTest('m', {
'type': type,
diff --git a/mobile/test/notify/question_notice_test.dart b/mobile/test/notify/question_notice_test.dart
index e79961f85..c6528b033 100644
--- a/mobile/test/notify/question_notice_test.dart
+++ b/mobile/test/notify/question_notice_test.dart
@@ -24,6 +24,21 @@ void main() {
expect(asked.hear(a, 'q2'), isTrue, reason: 'asked again after its end');
});
+ test('says what each of one machine\'s agents was asked, and no other machine\'s', () {
+ const other = (machineId: 'm2', agentId: 'a');
+ final asked = AskedQuestions()
+ ..hear(a, 'q1')
+ ..hear(b, 'q2')
+ ..hear(other, 'q3');
+ expect(asked.askedOn('m'), {a: 'q1', b: 'q2'});
+ expect(asked.askedOn('m2'), {other: 'q3'});
+ expect(asked.askedOn('nobody'), isEmpty);
+ expect(asked.asking(a), isTrue);
+ asked.forget(a);
+ expect(asked.asking(a), isFalse);
+ expect(asked.askedOn('m'), {b: 'q2'});
+ });
+
test('a repeat is silent; a new one escalates like a finished turn', () {
for (final inFront in [true, false]) {
expect(
diff --git a/mobile/test/phone_edge/settings_behavior_test.dart b/mobile/test/phone_edge/settings_behavior_test.dart
index b7b428e0a..de6b5363c 100644
--- a/mobile/test/phone_edge/settings_behavior_test.dart
+++ b/mobile/test/phone_edge/settings_behavior_test.dart
@@ -182,9 +182,9 @@ void main() {
await close(tester, app);
});
- // ⚠️ A phone over the relay never hears a question — `commander_question` goes to the dial and the
- // computer's own window only — so the row promises what does reach it, and nothing else.
- testWidgets('Notifications: a harness finishing, a new device — never "needs you"', (
+ // ⚠️ The row promises what reaches a phone over the relay, and nothing else: a question does since
+ // 2026-10-21 (`commander_question`, cli core/questions.ts `sendRemote`).
+ testWidgets('Notifications: a harness finishing or needing you, a new device', (
tester,
) async {
final app = await openSettings(tester);
@@ -200,12 +200,12 @@ void main() {
find.descendant(
of: row,
matching: find.text(
- 'When a harness finishes, or a new device joins your account.',
+ 'When a harness finishes or needs you, or a new device joins your account.',
),
),
findsOneWidget,
);
- expect(find.textContaining('needs you'), findsNothing);
+ expect(find.textContaining('needs you'), findsOneWidget);
await close(tester, app);
});
diff --git a/mobile/test/phone_edge/welcome_behavior_test.dart b/mobile/test/phone_edge/welcome_behavior_test.dart
index 50c6eb5bd..c6d8ffcda 100644
--- a/mobile/test/phone_edge/welcome_behavior_test.dart
+++ b/mobile/test/phone_edge/welcome_behavior_test.dart
@@ -316,10 +316,9 @@ void main() {
);
// ⚠️ The OS's notification prompt follows them, so they say what a notice is for — and only what
- // reaches a phone: a question never does (`commander_question` goes to the dial and the
- // computer's own window only).
+ // reaches a phone: a question does since 2026-10-21 (`commander_question` over the relay).
testWidgets(
- 'before the notification prompt: a harness finishing, a new device — never "needs you"',
+ 'before the notification prompt: a harness finishing or needing you, a new device',
(tester) async {
setPhone(tester, largePhone);
Widget hints({VoidCallback? onDone}) => phoneApp(
@@ -337,11 +336,11 @@ void main() {
expect(find.text('→ swipe right'), findsOneWidget);
expect(
find.text(
- 'Notifications tell you when a harness finishes, or a new device joins your account.',
+ 'Notifications tell you when a harness finishes or needs you, or a new device joins your account.',
),
findsOneWidget,
);
- expect(find.textContaining('needs you'), findsNothing);
+ expect(find.textContaining('needs you'), findsOneWidget);
// No prompt after them: no line about notices either.
await tester.pumpWidget(const SizedBox());