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: a person's act wakes a grid, and the app says what is happening

Kelvinbebe15558104
diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.ts
index 2032d5006..9f765c534 100644
--- a/backend/src/lib/bus.ts
+++ b/backend/src/lib/bus.ts
@@ -288,14 +288,30 @@ export async function setAgentPresence(machineId: string, managerId: string, ttl
}
export async function getAgentPresence(machineId: string): Promise<string | null> {
+ return (await presenceValue(machineId)) ?? null
+}
+
+/** The presence key's value, or undefined when the store could not be read (logged). */
+async function presenceValue(machineId: string): Promise<string | null | undefined> {
try {
return await pub.get(presenceKey(machineId))
} catch (err) {
- logger.error('[bus] getAgentPresence failed', err, { machineId })
- return null
+ logger.error('[bus] presence read failed', err, { machineId })
+ return undefined
}
}
+/**
+ * Whether the machine's daemon is connected: true present, false absent — and null when the presence store
+ * could not be READ, which [getAgentPresence] folds into "absent". A reader that turns absence into a
+ * verdict (the machine list's `offline`, which a daemon labels models "seems offline" by) must not also
+ * turn an outage of this store into one.
+ */
+export async function readAgentPresence(machineId: string): Promise<boolean | null> {
+ const value = await presenceValue(machineId)
+ return value === undefined ? null : !!value
+}
+
/** One MGET for a whole machine list (the watchers seed N machines at once). Missing/failed → null. */
export async function getAgentPresenceMany(machineIds: string[]): Promise<Map<string, string | null>> {
const out = new Map<string, string | null>()
diff --git a/backend/src/services/MachineService.list.test.ts b/backend/src/services/MachineService.list.test.ts
index 36f61557b..964d717f7 100644
--- a/backend/src/services/MachineService.list.test.ts
+++ b/backend/src/services/MachineService.list.test.ts
@@ -16,6 +16,7 @@ const groupBy = vi.hoisted(() => vi.fn())
const planFindMany = vi.hoisted(() => vi.fn())
const runCommandRaw = vi.hoisted(() => vi.fn())
const getAgentPresence = vi.hoisted(() => vi.fn())
+const readAgentPresence = vi.hoisted(() => vi.fn())
vi.mock('../lib/prisma.js', () => ({
// The REAL helper — the thing under test is whether listForUser applies it, so stubbing it would
@@ -30,6 +31,7 @@ vi.mock('../lib/prisma.js', () => ({
}))
vi.mock('../lib/bus.js', () => ({
getAgentPresence,
+ readAgentPresence,
clearAgentPresence: vi.fn(),
publishDown: vi.fn(),
publishDeviceMachineListChanged: vi.fn(),
@@ -83,6 +85,7 @@ beforeEach(() => {
planFindMany.mockResolvedValue([])
runCommandRaw.mockResolvedValue({ cursor: { firstBatch: [] } })
getAgentPresence.mockResolvedValue(null)
+ readAgentPresence.mockResolvedValue(false)
})
const listedIds = async (env?: 'prod' | 'stag') =>
@@ -116,3 +119,21 @@ describe('listForUser — what the mobile app is allowed to see', () => {
expect(where.OR).toEqual([{ deletedAt: null }, { deletedAt: { isSet: false } }])
})
})
+
+describe('listForUser — a remote machine\'s presence', () => {
+ const remote = (machineId: string): Row => ({ ...base, machineId, userId: 'u1', authMode: 'remote' })
+ const statusOf = async (): Promise<Record<string, unknown>> =>
+ Object.fromEntries((await machineService.listForUser('u1')).map((m) => [m.machineId, m.status]))
+
+ beforeEach(() => {
+ findMany.mockImplementation(async ({ where }: { where: Where }) =>
+ [remote('up'), remote('down'), remote('unreadable')].filter((r) => matches(r, where)))
+ readAgentPresence.mockImplementation(async (id: string) => id === 'up' ? true : id === 'down' ? false : null)
+ })
+
+ it('reads running when present, offline when absent, and unknown — never offline — when the read failed', async () => {
+ // A daemon labels a model "seems offline" only on `offline` (grid-reads-without-waking issue 03), so a
+ // presence store that could not be read must not say a machine is gone.
+ expect(await statusOf()).toEqual({ up: 'running', down: 'offline', unreadable: 'unknown' })
+ })
+})
diff --git a/backend/src/services/MachineService.ts b/backend/src/services/MachineService.ts
index 553824b04..db53f02f7 100644
--- a/backend/src/services/MachineService.ts
+++ b/backend/src/services/MachineService.ts
@@ -2,7 +2,7 @@ import type { Machine } from '@prisma/client'
import { prisma, machineAlive } from '../lib/prisma.js'
import { selectManagerId } from '../lib/managers.js'
import { provisionViaManager } from '../lib/provision.js'
-import { getAgentPresence, clearAgentPresence, publishDown, publishDeviceMachineListChanged, pub, consumeNewIdQuota } from '../lib/bus.js'
+import { getAgentPresence, readAgentPresence, clearAgentPresence, publishDown, publishDeviceMachineListChanged, pub, consumeNewIdQuota } from '../lib/bus.js'
import { randomUUID } from 'node:crypto'
import { generateApiKey, machineIdFromKey } from '../utils/crypto.js'
import { assertMachineId, isMachineId } from '../utils/slug.js'
@@ -236,7 +236,9 @@ async function nodeInfoByAgent(bindings: Machine[]): Promise<Map<string, { statu
}
/** Remote agents have no agent_nodes row — their liveness is the adapter's presence key
- * (`agent:{id}:mgr`, set by /api/adapter-ws while the machine is connected). Patch `info` in place. */
+ * (`agent:{id}:mgr`, set by /api/adapter-ws while the machine is connected). Patch `info` in place.
+ * A presence read that FAILED is `unknown`, never `offline`: a daemon takes `offline` as evidence and
+ * labels that computer's models "seems offline" (grid-reads-without-waking issue 03). */
async function applyRemoteStatus(
bindings: Machine[],
plans: Map<string, PlanInfo>,
@@ -245,8 +247,9 @@ async function applyRemoteStatus(
const remote = bindings.filter((b) => plans.get(b.machineId)?.authMode === 'remote')
await Promise.all(
remote.map(async (b) => {
- const online = !!(await getAgentPresence(b.machineId))
- info.set(b.machineId, { status: online ? 'running' : 'offline', engine: 'claude' })
+ const present = await readAgentPresence(b.machineId)
+ const status = present === null ? 'unknown' : present ? 'running' : 'offline'
+ info.set(b.machineId, { status, engine: 'claude' })
}),
)
}
diff --git a/cli/src/backendSocket.gridReads.spec.ts b/cli/src/backendSocket.gridReads.spec.ts
index ce6f5a0e7..3f0a1c227 100644
--- a/cli/src/backendSocket.gridReads.spec.ts
+++ b/cli/src/backendSocket.gridReads.spec.ts
@@ -14,23 +14,34 @@ import { BackendSocket } from './backendSocket.js'
import { env } from './config/env.js'
import { fakeGridAnswers, installFakeGrid, type FakeGrid, type FakeGridPlan } from './lib/__fixtures__/fakeGrid.js'
import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
-import { resetGridModels, type GridModelsService } from './lib/gridModels.js'
+import { observeMachineList, resetGridModels, type GridModelsService } from './lib/gridModels.js'
const OWN = 'mine', OWN_ID = 'net-own'
const OVERVIEW = '/relay/v1/grid/overview'
let server: Server, base: string, seen: Array<{ path: string; headers: IncomingHttpHeaders }>
let overview: { status: number; body: unknown }
+/** The relay's signed-in `/models` — what a person's act reads, held as long as a test says. */
+let modelsDelayMs: number
let root: string, gridHome: string, previousData: string, grid: FakeGrid, service: GridModelsService, clock: number
let socket: BackendSocket, frames: Array<{ type: string; payload: Record<string, unknown> }>
+const TOKEN = fakeGridAnswers().token
+
function plan(status: string | null = 'running'): FakeGridPlan {
return {
ls: { stdout: JSON.stringify([{ grid: OWN, id: OWN_ID, type: 'permissioned-public' }]) },
[`info ${OWN}`]: { stdout: JSON.stringify({ grid: OWN, status, grid_url: `${base}/g/${OWN_ID}` }) },
+ [`info ${OWN} --env`]: { stdout: `export OPENAI_BASE_URL="${base}/g/${OWN_ID}/relay/v1"\nexport OPENAI_API_KEY="${TOKEN}"\n` },
+ mcp: fakeGridAnswers().plan.mcp!,
}
}
+const modelReads = (): Array<{ path: string; headers: IncomingHttpHeaders }> => seen.filter((r) => r.path === `/g/${OWN_ID}/relay/v1/models`)
+
+/** What `GET /api/machines` answers, with `studio` offline. */
+const studioOffline = { success: true, data: { machines: [{ machineId: 'studio-id', computerId: 'studio-id', hostname: 'studio', name: 'Studio', status: 'offline' }] } }
+
async function ask(type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> {
const requestId = `${type}-${frames.length}`
socket.handleLocalFrame('local:grid-reads', { type, payload: { ...payload, requestId } })
@@ -48,11 +59,16 @@ function expectNoCredential(): void {
beforeEach(async () => {
seen = []
overview = { status: 200, body: { nodes: [{ name: 'mac', engine: 'llama.cpp', models: ['small-q4'], online: true }], models: [{ id: 'Small-Q4' }] } }
+ modelsDelayMs = 0
server = createServer((req, res) => {
seen.push({ path: req.url ?? '', headers: req.headers })
- const found = req.url === `/g/${OWN_ID}${OVERVIEW}` ? overview : { status: 404, body: {} }
- res.writeHead(found.status, { 'content-type': 'application/json' })
- res.end(JSON.stringify(found.body))
+ const models = req.url === `/g/${OWN_ID}/relay/v1/models`
+ const found = req.url === `/g/${OWN_ID}${OVERVIEW}` ? overview : models ? { status: 200, body: { data: [] } } : { status: 404, body: {} }
+ const timer = setTimeout(() => {
+ res.writeHead(found.status, { 'content-type': 'application/json' })
+ res.end(JSON.stringify(found.body))
+ }, models ? modelsDelayMs : 0)
+ res.on('close', () => clearTimeout(timer))
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
base = `http://127.0.0.1:${(server.address() as { port: number }).port}`
@@ -64,7 +80,11 @@ beforeEach(async () => {
env.ADAPTER_DATA_DIR = join(root, 'data')
clock = Date.parse('2026-09-24T10:00:00Z')
// Before the socket, which subscribes to the service it finds for its `grid_models_changed` push.
- service = resetGridModels({ now: () => clock, dataDir: () => join(root, 'data'), gridHome: () => gridHome, email: () => null })
+ service = resetGridModels({
+ now: () => clock, dataDir: () => join(root, 'data'), gridHome: () => gridHome, email: () => null,
+ // An explicit wake's 3 s pauses move the clock instead of the test.
+ sleep: async (ms) => { clock += ms },
+ })
grid = installFakeGrid(plan())
socket = new BackendSocket('token')
socket.setHarnessGridName(OWN)
@@ -141,20 +161,117 @@ describe('grid_fleet_models_list (the Model Manager) on a sleeping own grid', ()
})
})
+describe('grid_models_list — a person\'s explicit wake (issue 03)', () => {
+ it('answers "waking" at once — well inside the app\'s timeout — while its one credentialed read is still held', async () => {
+ overview = { status: 503, body: { detail: 'resting', code: 'grid_asleep' } }
+ await ask('grid_models_list')
+ // The proxy holds a signed-in read of a sleeping grid while its master boots; nothing may wait on it.
+ modelsDelayMs = 20_000
+
+ const started = Date.now()
+ const reply = await ask('grid_models_list', { wake: [OWN], rowState: true })
+
+ expect(Date.now() - started).toBeLessThan(5_000)
+ expect((reply.grids as Array<Record<string, unknown>>)[0]).toMatchObject({ name: OWN, state: 'waking' })
+ await vi.waitFor(() => expect(modelReads()).toHaveLength(1), { timeout: 5_000 })
+ expect(modelReads()[0]!.headers.authorization).toBe(`Bearer ${TOKEN}`)
+ expect(modelReads()[0]!.headers['user-agent']).toMatch(/^autonomous-harness\/\S+ \(wake\)$/)
+ // It ends, and says so to the window without being asked.
+ await service.settled()
+ await vi.waitFor(() => expect(frames.some((f) => f.type === 'grid_models_changed'
+ && (f.payload.grids as Array<Record<string, unknown>>)[0]?.wakeOutcome === 'not_started')).toBe(true), { timeout: 5_000 })
+ })
+})
+
+describe('grid_models_list — computers of mine that seem offline (issue 03)', () => {
+ async function studioServingThenAsleep(): Promise<void> {
+ overview = { status: 200, body: { nodes: [{ name: 'studio', engine: 'llama.cpp', models: ['big-model'] }], models: [] } }
+ await ask('grid_models_list')
+ clock += 125_000
+ overview = { status: 503, body: { detail: 'resting', code: 'grid_asleep' } }
+ await ask('grid_models_list')
+ await service.settled()
+ }
+ const rows = (payload: Record<string, unknown>) => (payload.grids as Array<{ models: unknown[] }>)[0]!.models
+
+ it('labels the row as `unavailable` for a window that asks for row state, and in the node text for one that does not', async () => {
+ await studioServingThenAsleep()
+ observeMachineList(studioOffline, 'computer-here')
+ clock += 60_000
+ observeMachineList(studioOffline, 'computer-here')
+
+ expect(rows(await ask('grid_models_list', { rowState: true }))).toEqual([
+ { id: 'big-model', node: 'studio', unavailable: { reason: 'offline', machine: 'Studio', since: new Date(clock - 60_000).toISOString() } },
+ ])
+ expect(rows(await ask('grid_models_list'))).toEqual([{ id: 'big-model', node: 'Studio · seems offline' }])
+ })
+
+ it('pushes each window the form it asked for', async () => {
+ await studioServingThenAsleep()
+ const old: typeof frames = []
+ socket.registerLocalClient('local:old-build', { sendFrame: (frame) => { old.push(frame as typeof frames[number]); return true }, sendBinary: () => true })
+ await ask('grid_models_list', { rowState: true })
+ frames.length = 0
+
+ observeMachineList(studioOffline, 'computer-here')
+ clock += 60_000
+ observeMachineList(studioOffline, 'computer-here')
+
+ await vi.waitFor(() => expect(frames.some((f) => f.type === 'grid_models_changed')).toBe(true), { timeout: 5_000 })
+ await vi.waitFor(() => expect(old.some((f) => f.type === 'grid_models_changed')).toBe(true), { timeout: 5_000 })
+ expect(rows(frames.find((f) => f.type === 'grid_models_changed')!.payload)).toEqual([expect.objectContaining({ node: 'studio', unavailable: expect.anything() })])
+ expect(rows(old.find((f) => f.type === 'grid_models_changed')!.payload)).toEqual([{ id: 'big-model', node: 'Studio · seems offline' }])
+ await socket.unregisterLocalClient('local:old-build')
+ })
+})
+
describe('agent_retarget', () => {
- it('reads nothing on its own: the one request is the model lookup of the move a person made', async () => {
- const answers = fakeGridAnswers()
- // The relay the grid's `info --env` names is this test's, so nothing here can reach a real host.
- const relay = `${base}/g/${OWN_ID}/relay/v1`
- grid.replan({ ...answers.plan, info: { stdout: `export OPENAI_BASE_URL="${relay}"\nexport OPENAI_API_KEY="${answers.token}"\n` } })
- socket.onRetargetAgent = vi.fn(async () => ({ ok: true as const }))
+ beforeEach(() => { socket.onRetargetAgent = vi.fn(async () => ({ ok: true as const })) })
+
+ it('onto a grid that is asleep, starts it with one credentialed read marked (prewarm) — and the move does not wait on it', async () => {
+ overview = { status: 200, body: { nodes: [{ name: 'mac', engine: 'llama.cpp', models: ['small-q4'] }], models: [{ id: 'Small-Q4' }] } }
+ await ask('grid_models_list')
+ clock += 125_000
+ overview = { status: 503, body: { detail: 'resting', code: 'grid_asleep' } }
+ await ask('grid_models_list')
+ await service.settled()
+ modelsDelayMs = 20_000
+ seen.length = 0
+
+ const started = Date.now()
+ const reply = await ask('agent_retarget', { agentId: 'agent-1', gridModel: 'Small-Q4', gridName: OWN })
- const reply = await ask('agent_retarget', { agentId: 'agent-1', gridModel: 'GLM-4.7-Flash', gridName: answers.gridName })
+ expect(reply).toMatchObject({ retargeted: true })
+ expect(Date.now() - started).toBeLessThan(5_000)
+ await vi.waitFor(() => expect(modelReads()).toHaveLength(1), { timeout: 5_000 })
+ expect(modelReads()[0]!.headers.authorization).toBe(`Bearer ${TOKEN}`)
+ expect(modelReads()[0]!.headers['user-agent']).toMatch(/^autonomous-harness\/\S+ \(prewarm\)$/)
+ })
+
+ it('onto a grid seen awake a moment ago, reads nothing at all', async () => {
+ await ask('grid_models_list')
+ await service.settled()
+ seen.length = 0
+ clock += 10_000
+
+ const reply = await ask('agent_retarget', { agentId: 'agent-1', gridModel: 'Small-Q4', gridName: OWN })
expect(reply).toMatchObject({ retargeted: true })
- // Moving an agent onto a model is a person's act, which may wake the grid (and is meant to: the
- // pane is about to use it). What must not happen is any read on the app's own schedule.
- expect(seen.map((r) => r.path)).toEqual([`/g/${OWN_ID}/relay/v1/models`])
- expect(seen.some((r) => r.path.endsWith('/grid/overview') || r.path.endsWith('/nodes/discover'))).toBe(false)
+ // The move is a person's act and may wake a grid — this one needs no waking, and the context window
+ // comes from the picture, so nothing at all reaches the grid.
+ await new Promise((resolve) => setTimeout(resolve, 200))
+ expect(seen).toEqual([])
+ })
+
+ it('a move that is refused starts nothing', async () => {
+ overview = { status: 503, body: { detail: 'resting', code: 'grid_asleep' } }
+ await ask('grid_models_list')
+ await service.settled()
+ socket.onRetargetAgent = vi.fn(async () => ({ ok: false as const, error: 'ENGINE_NOT_CAPABLE' }))
+ seen.length = 0
+
+ expect(await ask('agent_retarget', { agentId: 'agent-1', gridModel: 'Small-Q4', gridName: OWN })).toMatchObject({ error: 'ENGINE_NOT_CAPABLE' })
+ await new Promise((resolve) => setTimeout(resolve, 200))
+ expect(modelReads()).toEqual([])
})
})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index ecd505207..e9b0bc57f 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -36,7 +36,10 @@ import { GridFleetRpc, GRID_FLEET_PROTOCOL, GRID_FLEET_MAX_TIMEOUT_MS, parseGrid
import { LocalModels } from './lib/localModels.js'
import { ApiConnections, apiConnectionsRequest } from './lib/apiConnections.js'
import { gridCapableEngines, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'
-import { forgetGridModels, gridInventory, listAllGridModels, onGridModelsChanged, resolveGridTarget, type GridSection } from './lib/gridModels.js'
+import {
+ forgetGridModels, gridInventory, listAllGridModels, onGridModelsChanged, presentGridSections, retargetPrewarm, type GridSection,
+} from './lib/gridModels.js'
+import { resolveGridTarget } from './lib/gridTarget.js'
import { parseNewAgentModel, resolveNewAgentModel } from './lib/newAgentModel.js'
import { deriveHarnessGridName } from './lib/gridDerive.js'
import { AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'
@@ -365,10 +368,16 @@ async function enrichSubagentStats(events: SessionEvent[], transcriptPath: strin
}
}
+/** Sections one `grid_models_list` may ask to wake — a person presses one "Show models" at a time. */
+const MAX_WAKES_PER_ASK = 8
+
/** What `grid_models_list` answers and `grid_models_changed` pushes — one shape, so a window parses both
* with one reader. `gridName` and `models` keep naming the own grid alone, for an app that predates
- * `grids`; each section's `state`, `seenAt` and `lastKnownAge` are additive. */
-function gridModelsPayload(gridName: string | null, grids: GridSection[]): Record<string, unknown> {
+ * `grids`; each section's `state`, `seenAt`, `lastKnownAge` and `wakeOutcome` are additive, and a row's
+ * offline label is `unavailable` for a window that asked for row state, its node text for one that did
+ * not (`presentGridSections`). */
+function gridModelsPayload(gridName: string | null, sections: GridSection[], rowState: boolean): Record<string, unknown> {
+ const grids = presentGridSections(sections, { rowState })
return {
gridName,
models: grids.find((g) => g.own)?.models ?? [],
@@ -610,6 +619,9 @@ export class BackendSocket {
/** The grid listing currently out, shared by every `grid_models_list` for the same own grid
* that lands meanwhile. */
private gridModelsInFlight: { gridName: string | null; grids: ReturnType<typeof listAllGridModels> } | null = null
+ /** The windows on this computer that draw row state (`grid_models_list` with `rowState: true`) and so
+ * are pushed labels as `unavailable` rather than in the node text. */
+ private readonly rowStateWindows = new Set<string>()
/** Receives `theme_set` — the desktop's pane colours, to become this machine's tmux
* `window-style` (lib/hostTheme.ts). Wired by cli.ts; null answers with UNSUPPORTED. */
hostThemeSink: ((theme: HostTheme) => void) | null = null
@@ -810,7 +822,10 @@ export class BackendSocket {
try {
const gridName = await this.resolveGridName()
const grids = await listAllGridModels(gridName, { refresh: false })
- this.sendLocal({ type: 'grid_models_changed', payload: gridModelsPayload(gridName, grids) })
+ // Each window in the form it asked for — see `gridModelsPayload`.
+ const plain: Frame = { type: 'grid_models_changed', payload: gridModelsPayload(gridName, grids, false) }
+ const withRowState: Frame = { type: 'grid_models_changed', payload: gridModelsPayload(gridName, grids, true) }
+ this.sendLocal((connId) => this.rowStateWindows.has(connId) ? withRowState : plain)
} catch { /* the next ask answers the same thing */ }
}
@@ -1012,10 +1027,12 @@ export class BackendSocket {
* dial is a physical object on one table, and a finger moving on its glass is meaningful to the window
* in front of it and to nothing else. `send()` fans out to the web audience as well, which would scroll
* a window on a computer the user is not sitting at. */
- sendLocal(frame: Frame): void {
- if (env.LOG_FRAMES) logFrame('→', 'local', frame)
+ /** One frame to every window on this computer — or, given a function, each window its own. */
+ sendLocal(frame: Frame | ((connId: string) => Frame)): void {
for (const [connId, sink] of this.localClients) {
- if (!sink.sendFrame(frame)) void this.unregisterLocalClient(connId)
+ const sent = typeof frame === 'function' ? frame(connId) : frame
+ if (env.LOG_FRAMES) logFrame('→', 'local', sent)
+ if (!sink.sendFrame(sent)) void this.unregisterLocalClient(connId)
}
}
@@ -1142,6 +1159,7 @@ export class BackendSocket {
/** Release all connection-scoped state when the loopback WebSocket closes. */
async unregisterLocalClient(connId: string): Promise<void> {
if (!this.localClients.delete(connId)) return
+ this.rowStateWindows.delete(connId)
this.viewerForwarder.closeConnection(connId)
// The window left before any link could hear it attach: nothing happened, as far as the backend
// is concerned, and a later link must not be told otherwise.
@@ -1935,18 +1953,31 @@ export class BackendSocket {
// One computation at a time: detached, a second ask that lands while the first is still
// out (the app re-asks on every connect) would spawn another `grid ls` for the same answer.
// Later askers share the one in flight; each grid's reads are single-flight in the service.
+ //
+ // `rowState: true` — a window that draws row state gets offline labels as `unavailable` (and
+ // its pushes in that form); `wake: [name]` — a person pressed "Show models" / "Wake now", and
+ // the answer (with those sections "waking") comes back at once while the wake runs behind it
+ // (grid-reads-without-waking issue 03). A wake never joins a listing already out: that one
+ // was built before the wake began, and would not say "waking".
+ const rowState = payload.rowState === true
+ if (rowState && this.localClients.has(connId)) this.rowStateWindows.add(connId)
+ const wake = Array.isArray(payload.wake)
+ ? payload.wake.filter((name): name is string => typeof name === 'string' && !!name.trim()).map((name) => name.trim()).slice(0, MAX_WAKES_PER_ASK)
+ : []
void (async () => {
const gridName = await this.resolveGridName()
const inFlight = this.gridModelsInFlight
- const listing = inFlight && inFlight.gridName === gridName
- ? inFlight.grids
- : (this.gridModelsInFlight = {
- gridName,
- grids: listAllGridModels(gridName).finally(() => {
- if (this.gridModelsInFlight?.gridName === gridName) this.gridModelsInFlight = null
- }),
- }).grids
- reply(type, requestId, gridModelsPayload(gridName, await listing))
+ const listing = wake.length
+ ? listAllGridModels(gridName, { wake })
+ : inFlight && inFlight.gridName === gridName
+ ? inFlight.grids
+ : (this.gridModelsInFlight = {
+ gridName,
+ grids: listAllGridModels(gridName).finally(() => {
+ if (this.gridModelsInFlight?.gridName === gridName) this.gridModelsInFlight = null
+ }),
+ }).grids
+ reply(type, requestId, gridModelsPayload(gridName, await listing, rowState))
})().catch(() => reply(type, requestId, { error: 'GRID_MODELS_FAILED' }))
return
}
@@ -2377,12 +2408,17 @@ export class BackendSocket {
})
return
}
- const moved = await this.onRetargetAgent({ agentId, grid: target.state === 'ok' ? target.override : null })
+ const override = target.state === 'ok' ? target.override : null
+ const moved = await this.onRetargetAgent({ agentId, grid: override })
if (!moved.ok) {
reply(type, requestId, moved.detail ? { error: moved.error, detail: moved.detail } : { error: moved.error })
return
}
reply(type, requestId, { retargeted: true })
+ // The agent is on a grid model now and its pane is restarting: start that grid meanwhile if it
+ // sleeps, so the first message rarely waits on a boot (issue 03). Detached — the move is done
+ // and answered — and it decides for itself whether a wake is worth it.
+ if (override) void retargetPrewarm(override).catch(() => {})
return
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index e6656d24a..f1993fb15 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -68,7 +68,7 @@ import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
import { warnIfGridSignInRemains } from './lib/gridCredentials.js'
import { reconcileGridAttach, gridNamesLocal, createGridAttachRunner } from './lib/gridAttach.js'
import { signedInGridEmail, resetGridDeriveMemo } from './lib/gridDerive.js'
-import { forgetGridModels } from './lib/gridModels.js'
+import { forgetGridModels, gridAnnotation, keystrokePrewarm, observeMachineList, onGridModelsChanged, warmGridModels } from './lib/gridModels.js'
import { gridAvailable } from './lib/gridExec.js'
import { ENGINE_CLI_COMMANDS, ENGINES, PROCESS_ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'
import { isTerminalEngine, type AgentEngine } from './engines/types.js'
@@ -1938,8 +1938,34 @@ async function runForeground(session: AuthSession | null): Promise<void> {
},
streamingAvailable: tmuxBackend != null,
diagnostic: (event, fields) => console.log(`[terminal-stream] ${event}`, fields),
+ // The keystroke prewarm (grid-reads-without-waking issue 03): typing into a pane whose agent runs on
+ // a sleeping grid starts that grid while the person types. Here, in the daemon's own input path, so
+ // an older desktop and typing from a phone get it too; an agent on its own login has no `grid`.
+ onInput: (agentId) => {
+ const grid = registry.resolve(agentId)?.grid
+ if (grid) void keystrokePrewarm(grid).catch(() => {})
+ },
})
backend.setTerminalStreamManager(terminalStreams)
+ // An agent's frame says what its grid's picture says (`grid.state`, and a `grid.note` when its model
+ // will not answer). The picture changes on reads nobody waited for, so the frames of the agents whose
+ // annotation moved are pushed again — only those, and only when it moved.
+ const announcedGrid = new Map<string, string>()
+ onGridModelsChanged(() => {
+ const onGrid = registry.advertised().filter((s) => s.grid)
+ const present = new Set(onGrid.map((s) => s.agentId))
+ for (const agentId of [...announcedGrid.keys()]) if (!present.has(agentId)) announcedGrid.delete(agentId)
+ for (const s of onGrid) {
+ const said = JSON.stringify(gridAnnotation(s.grid))
+ if (announcedGrid.get(s.agentId) === said) continue
+ announcedGrid.set(s.agentId, said)
+ syncSession(s)
+ }
+ })
+ // The pictures saved before this start, back in memory with nothing read from any grid: an agent's
+ // frame carries its grid's state and note, and a keystroke can start its grid, before any window asks
+ // for the list (after a self-update, a phone may be the only one typing).
+ void warmGridModels().catch(() => {})
// `agentReconciler` is declared further down; this closure only ever runs for a frame, and no
// socket is connected until well after that declaration (backend.connect() is the last thing
// this function does).
@@ -3402,6 +3428,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Read fresh each time — a re-login swaps it under a daemon that never restarted.
() => readAuthSession()?.machineId ?? null,
)
+ // Which of the owner's other computers have been reading offline — a label on the models only they
+ // serve on a sleeping grid, never a removal (grid-reads-without-waking issue 03).
+ machineListCache.listen((body) => observeMachineList(body, computerId()))
/**
* `GET /api/machines` for local clients, answered from the last known-good list when the backend leg
diff --git a/cli/src/device/machineList.spec.ts b/cli/src/device/machineList.spec.ts
index a3d16f898..ee9f09c9f 100644
--- a/cli/src/device/machineList.spec.ts
+++ b/cli/src/device/machineList.spec.ts
@@ -39,6 +39,21 @@ describe('sameComputer', () => {
})
describe('MachineListCache', () => {
+ it('tells a listener every list it takes, and a sign-out as null — a failed read tells nothing', async () => {
+ const told: Array<Record<string, unknown> | null> = []
+ let answer: () => Promise<{ status: number; body: Record<string, unknown> }> = ok([row()])
+ const cache = new MachineListCache(() => answer(), () => 'z', () => {}, DIR())
+ cache.listen((body) => told.push(body))
+
+ await cache.refresh()
+ answer = async () => { throw new Error('offline') }
+ await cache.refresh()
+ answer = async () => ({ status: 401, body: {} })
+ await cache.refresh()
+
+ expect(told).toEqual([{ machines: [row()] }, null])
+ })
+
it('marks the row whose computerId is this computer as local', async () => {
const cache = new MachineListCache(
ok([row({ machineId: 'mine', computerId: 'AA-BB-CC-DD' }), row({ machineId: 'other', computerId: 'ffff' })]),
diff --git a/cli/src/device/machineList.ts b/cli/src/device/machineList.ts
index df7f5b4f2..a25262295 100644
--- a/cli/src/device/machineList.ts
+++ b/cli/src/device/machineList.ts
@@ -87,6 +87,7 @@ export class MachineListCache {
/** The CONTENT `saveCache` last wrote (timestamp excluded), so an unchanged list costs no disk write. */
private lastWrittenContent = ''
private lastWrittenAt = 0
+ private readonly listeners = new Set<(body: Record<string, unknown> | null) => void>()
constructor(
private readonly fetchMachines: () => Promise<{ status: number; body: Record<string, unknown> }>,
@@ -101,6 +102,21 @@ export class MachineListCache {
this.loadCache()
}
+ /**
+ * Be told of every list this cache takes as known-good (its body, as the backend answered it), and of a
+ * sign-out (null). For readers that keep their own history of it — which of the owner's computers have
+ * been reading offline, and for how long (`lib/gridPresence.ts`).
+ */
+ listen(listener: (body: Record<string, unknown> | null) => void): void {
+ this.listeners.add(listener)
+ }
+
+ private tell(body: Record<string, unknown> | null): void {
+ for (const listener of this.listeners) {
+ try { listener(body) } catch { /* a listener's failure is its own */ }
+ }
+ }
+
/** Synchronous by contract — see the file header. */
list(): { machines: ListedMachine[]; source: MachineSource } {
return { machines: this.machines, source: this.source }
@@ -165,6 +181,7 @@ export class MachineListCache {
this.bodyOwner = this.owner()
this.fetchedAt = Date.now()
this.saveCache()
+ this.tell(body)
return true
}
@@ -228,6 +245,7 @@ export class MachineListCache {
this.bodyOwner = null
this.fetchedAt = 0
this.saveCache()
+ this.tell(null)
}
/** So a daemon that starts offline still draws the list the user saw last time. */
diff --git a/cli/src/lib/__fixtures__/fakeGrid.ts b/cli/src/lib/__fixtures__/fakeGrid.ts
index 72ab25cde..36977f722 100644
--- a/cli/src/lib/__fixtures__/fakeGrid.ts
+++ b/cli/src/lib/__fixtures__/fakeGrid.ts
@@ -25,13 +25,15 @@ const verb = args[0] || ''
// read-modify-write of one JSON document lost calls and crashed a reader that caught it half written.
fs.appendFileSync(log, JSON.stringify(process.argv.slice(2)) + '\\n')
const calls = fs.readFileSync(log, 'utf8').split('\\n').filter(Boolean).map((line) => JSON.parse(line))
-// A plan may answer one grid differently from another: \`info mine\` is asked before \`info\`.
-const keyed = plan[verb + ' ' + (args[1] || '')]
+// A plan may answer one grid differently from another: \`info mine\` is asked before \`info\`, and
+// \`info mine --env\` (the credential) before \`info mine\` (its \`--json\` status and address).
+const keyedFlag = plan[verb + ' ' + (args[1] || '') + ' ' + (args[2] || '')]
+const keyed = keyedFlag || plan[verb + ' ' + (args[1] || '')]
const step = keyed || plan[verb]
if (!step) { process.exit(0) }
// A verb may answer differently on successive calls (\`ls\` before and after a create), so its
// answer can be a LIST of turns; the last turn repeats once the list runs out.
-const asked = calls.filter((c) => c.includes(verb) && (!keyed || c.includes(args[1]))).length
+const asked = calls.filter((c) => c.includes(verb) && (!keyed || c.includes(args[1])) && (!keyedFlag || c.includes(args[2]))).length
const turn = Array.isArray(step) ? (step[asked - 1] ?? step[step.length - 1]) : step
if (turn.stdout) process.stdout.write(turn.stdout)
if (turn.stderr) process.stderr.write(turn.stderr)
@@ -42,7 +44,8 @@ process.exit(turn.exit ?? 0)
export interface FakeGridTurn { stdout?: string; stderr?: string; exit?: number }
/** Keyed by the FIRST argument after `--remote` is stripped — `mcp` for `grid mcp config …` — or by that
- * and the next one, `info mine`, which wins over the verb alone. */
+ * and the next one, `info mine`, which wins over the verb alone — or by those and the one after,
+ * `info mine --env`, which wins over both. */
export type FakeGridPlan = Record<string, FakeGridTurn | FakeGridTurn[]>
export interface FakeGrid {
diff --git a/cli/src/lib/__fixtures__/fakeRelay.ts b/cli/src/lib/__fixtures__/fakeRelay.ts
new file mode 100644
index 000000000..0493a9b9c
--- /dev/null
+++ b/cli/src/lib/__fixtures__/fakeRelay.ts
@@ -0,0 +1,49 @@
+/**
+ * A fake grid relay on loopback that RECORDS every request it receives — method, path and headers — for
+ * specs that must prove what the daemon sent a grid (grid-reads-without-waking). It is the spy: a spec
+ * reads what arrived rather than recomputing what the code under test meant to send.
+ *
+ * Answers are keyed by the full request path (`/g/<grid id>/relay/v1/grid/overview`); a function answer
+ * is asked on every request, so a grid can change between one read and the next.
+ */
+import { createServer, type IncomingHttpHeaders } from 'node:http'
+
+export interface RelayRequest { method: string; path: string; headers: IncomingHttpHeaders }
+export interface RelayAnswer { status: number; body?: unknown; delayMs?: number }
+
+export interface FakeRelay {
+ /** `http://127.0.0.1:<port>` — a grid's address is `<base>/g/<grid id>`. */
+ base: string
+ /** Every request received, oldest first. */
+ seen: RelayRequest[]
+ /** Answer `path` with `value` (or with what `value()` says at the time) from now on. */
+ answer: (path: string, value: RelayAnswer | (() => RelayAnswer)) => void
+ close: () => Promise<void>
+}
+
+export async function startFakeRelay(): Promise<FakeRelay> {
+ const seen: RelayRequest[] = []
+ const answers = new Map<string, RelayAnswer | (() => RelayAnswer)>()
+ const server = createServer((req, res) => {
+ seen.push({ method: req.method ?? '', path: req.url ?? '', headers: req.headers })
+ const planned = answers.get(req.url ?? '')
+ const found = (typeof planned === 'function' ? planned() : planned) ?? { status: 404, body: { detail: 'Not Found' } }
+ const timer = setTimeout(() => {
+ res.writeHead(found.status, { 'content-type': 'application/json' })
+ res.end(JSON.stringify(found.body ?? {}))
+ }, found.delayMs ?? 0)
+ // A held answer is let go when the spec closes the relay, rather than holding the close open.
+ res.on('close', () => clearTimeout(timer))
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const base = `http://127.0.0.1:${(server.address() as { port: number }).port}`
+ return {
+ base,
+ seen,
+ answer: (path, value) => { answers.set(path, value) },
+ close: async () => {
+ server.closeAllConnections()
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ },
+ }
+}
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index 38c161c68..14291b228 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -24,6 +24,7 @@ import type { AgentTokenUsage } from './agentTokenUsage.js'
import type { AgentOutputStats } from './agentOutputStats.js'
import type { GridAssignment } from './gridAssignment.js'
import type { GridWebSearchStatus } from './gridLaunch.js'
+import { gridAnnotation, type GridAnnotation } from './gridModels.js'
import { projectDisplayName, sessionDisplayTitle, type RegisteredSession } from './registry.js'
import { engineCanFork } from './forkAgent.js'
import { resumeMode, type ResumeMode } from './resumeCapability.js'
@@ -35,7 +36,7 @@ import type { DshVerdict } from '../dsh/verdict.js'
* say: a discovered grid agent, or a row from before the daemon recorded it. The app shows nothing
* for absent and for `on`; the two degraded words each get a sentence.
*/
-export type GridFrameBlock = GridAssignment & { webSearch?: GridWebSearchStatus }
+export type GridFrameBlock = GridAssignment & { webSearch?: GridWebSearchStatus } & Partial<GridAnnotation>
/**
* One agent as it travels to every client.
@@ -185,8 +186,10 @@ export async function agentFrame(
// grid has left behind. Read off the live process by discovery; carries no credential. Null is
// a real answer ("on no grid") and must be sent as one — omitting the key would make every push
// indistinguishable from a daemon too old to know about grids. The web-search status rides on
- // the block — decided by the launch, kept on the row — so it is gone the moment the block is.
- grid: s.grid ? { ...s.grid, ...(s.gridWebSearch ? { webSearch: s.gridWebSearch } : {}) } : null,
+ // the block — decided by the launch, kept on the row — so it is gone the moment the block is. So do
+ // that grid's `state` and a `note` when the agent's model will not answer (issue 03), read from what
+ // the model list last showed — no I/O, and absent for a grid this daemon is not tracking.
+ grid: s.grid ? { ...s.grid, ...(s.gridWebSearch ? { webSearch: s.gridWebSearch } : {}), ...gridAnnotation(s.grid) } : null,
// The Codex profile folder this agent launched against, if one was chosen instead of the
// engine's own login. Codex only; null is a real answer ("uses ~/.codex") for the same reason
// `grid: null` is above.
diff --git a/cli/src/lib/gridActs.spec.ts b/cli/src/lib/gridActs.spec.ts
new file mode 100644
index 000000000..b3d4439e3
--- /dev/null
+++ b/cli/src/lib/gridActs.spec.ts
@@ -0,0 +1,516 @@
+/**
+ * A person's act wakes a grid, and nothing else does (grid-reads-without-waking issue 03) — against a fake
+ * relay that records every request it receives and a fake `grid` first on PATH.
+ *
+ * What is asserted is what leaves the seam: the sections a picker is given, the note an agent frame
+ * carries, and the requests that reached the relay (path, Authorization, User-Agent). The clock is the
+ * service's injected `now`, and the explicit wake's 3 s pauses are the injected `sleep`, which moves that
+ * clock — so 45 s of re-reads run in milliseconds and every time rule is exercised without waiting.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { installFakeGrid, type FakeGrid, type FakeGridPlan } from './__fixtures__/fakeGrid.js'
+import { startFakeRelay, type FakeRelay, type RelayAnswer, type RelayRequest } from './__fixtures__/fakeRelay.js'
+import { agentFrame } from './agentFrame.js'
+import { presentGridSections, resetGridModels, type GridModelsService, type GridSection } from './gridModels.js'
+import type { RegisteredSession } from './registry.js'
+
+const OWN = 'mine', OWN_ID = 'net-own', TEAM = 'team', TEAM_ID = 'net-team'
+const EMAIL = '[email protected]', TOKEN = 'grid-token-123'
+const OVERVIEW = '/relay/v1/grid/overview', MODELS = '/relay/v1/models'
+const HERE = 'computer-here'
+const OWN_REF = { networkId: OWN_ID, gridName: OWN }, TEAM_REF = { networkId: TEAM_ID, gridName: TEAM }
+
+let relay: FakeRelay, root: string, gridHome: string, grid: FakeGrid, service: GridModelsService, clock: number
+/** What the service asked to be called back about later (an expiry), for a test to run when it likes. */
+let later_: Array<{ ms: number; run: () => void }>
+
+const at = (gridId: string, path: string): string => `/g/${gridId}${path}`
+const answer = (gridId: string, path: string, value: RelayAnswer | (() => RelayAnswer)): void => relay.answer(at(gridId, path), value)
+const node = (name: string, models: string[], extra: Record<string, unknown> = {}) =>
+ ({ name, engine: 'llama.cpp', models, online: true, provider_email: EMAIL, ...extra })
+const awake = (nodes: unknown[]): RelayAnswer => ({ status: 200, body: { nodes, models: [] } })
+const asleep = (lastKnown?: unknown): RelayAnswer =>
+ ({ status: 503, body: { detail: 'resting', code: 'grid_asleep', ...(lastKnown === undefined ? {} : { last_known: lastKnown }) } })
+const record = (ageSeconds: number, nodes: Array<{ name: string; models: string[] }>) =>
+ ({ age_seconds: ageSeconds, nodes: nodes.map((n) => ({ engine: 'llama.cpp', ...n })), ids: [] })
+
+function plan(ownStatus: string | null = 'running'): FakeGridPlan {
+ const env = (id: string) => ({ stdout: `export OPENAI_BASE_URL="${relay.base}/g/${id}/relay/v1"\nexport OPENAI_API_KEY="${TOKEN}"\n` })
+ return {
+ ls: { stdout: JSON.stringify([{ grid: OWN, id: OWN_ID, type: 'permissioned-public' }, { grid: TEAM, id: TEAM_ID, type: 'permissioned-providers' }]) },
+ [`info ${OWN}`]: { stdout: JSON.stringify({ grid: OWN, status: ownStatus, grid_url: `${relay.base}/g/${OWN_ID}` }) },
+ [`info ${TEAM}`]: { stdout: JSON.stringify({ grid: TEAM, status: null, grid_url: `${relay.base}/g/${TEAM_ID}` }) },
+ [`info ${OWN} --env`]: env(OWN_ID),
+ [`info ${TEAM} --env`]: env(TEAM_ID),
+ }
+}
+
+const requests = (gridId: string, path: string): RelayRequest[] => relay.seen.filter((r) => r.path === at(gridId, path))
+const section = (sections: GridSection[], name: string): GridSection => sections.find((s) => s.name === name)!
+
+/** Ask as a picker does, let every read (and wake) it started land, then ask again for what they produced. */
+async function look(opts: { wake?: string[] } = {}): Promise<GridSection[]> {
+ await service.sections(OWN, opts)
+ await service.settled()
+ return service.sections(OWN, { refresh: false })
+}
+
+const later = (seconds = 125): void => { clock += seconds * 1000 }
+
+/** The service a daemon starts with — a second call is the same daemon after a restart: nothing in memory,
+ * the pictures on disk. */
+function freshService(): GridModelsService {
+ return resetGridModels({
+ now: () => clock, dataDir: () => join(root, 'data'), gridHome: () => gridHome, email: () => EMAIL,
+ sleep: async (ms) => { clock += ms },
+ after: (ms, run) => { later_.push({ ms, run }); return () => {} },
+ })
+}
+
+/** A body `GET /api/machines` answers, as this daemon proxies it. */
+const machineList = (machines: Array<{ id: string; hostname: string; name?: string; status: string }>, guest = false) => ({
+ success: true,
+ data: {
+ machines: machines.map((m) => ({ machineId: m.id, computerId: m.id, hostname: m.hostname, name: m.name ?? null, status: m.status })),
+ ...(guest ? { guest: true } : {}),
+ },
+})
+
+/** The account's computers as two lists 60 s apart say them — long enough for an offline one to be labelled. */
+function studioOfflineTwice(): void {
+ const list = machineList([{ id: HERE, hostname: 'here' }, { id: 'studio-id', hostname: 'studio', name: 'Studio' }].map((m) =>
+ ({ ...m, status: m.id === HERE ? 'running' : 'offline' })))
+ service.observeMachines(list, HERE)
+ later(60)
+ service.observeMachines(list, HERE)
+}
+
+beforeEach(async () => {
+ relay = await startFakeRelay()
+ root = mkdtempSync(join(tmpdir(), 'grid-acts-'))
+ gridHome = join(root, 'grid-home')
+ mkdirSync(gridHome, { recursive: true })
+ clock = Date.parse('2026-09-25T10:00:00Z')
+ later_ = []
+ service = freshService()
+ grid = installFakeGrid(plan())
+ answer(OWN_ID, OVERVIEW, awake([]))
+ answer(TEAM_ID, OVERVIEW, asleep())
+ answer(OWN_ID, MODELS, { status: 200, body: { data: [] } })
+ answer(TEAM_ID, MODELS, { status: 200, body: { data: [] } })
+})
+
+afterEach(async () => {
+ await service.settled()
+ grid.dispose()
+ await relay.close()
+ rmSync(root, { recursive: true, force: true })
+})
+
+describe('an explicit wake', () => {
+ it('answers "waking" at once, reads once WITH the credential, and re-reads without it until nodes are seen', async () => {
+ await look()
+ // The credentialed read is held the way the proxy holds one while a master boots.
+ answer(TEAM_ID, MODELS, { status: 200, body: { data: [] }, delayMs: 1_500 })
+ let overviews = 0
+ answer(TEAM_ID, OVERVIEW, () => ++overviews < 3 ? asleep() : awake([node('rig', ['big-model'], { provider_email: '[email protected]' })]))
+
+ const reply = await service.sections(OWN, { wake: [TEAM] })
+ expect(section(reply, TEAM).state).toBe('waking')
+ expect(requests(TEAM_ID, MODELS).length).toBeLessThanOrEqual(1)
+
+ await service.settled()
+ const after = await service.sections(OWN, { refresh: false })
+ expect(section(after, TEAM)).toMatchObject({ state: 'awake', models: [{ id: 'big-model', node: 'rig' }] })
+ expect(section(after, TEAM)).not.toHaveProperty('wakeOutcome')
+ // Exactly one credentialed read, marked as a wake; the re-reads carry nothing and stop at nodes seen.
+ const woken = requests(TEAM_ID, MODELS)
+ expect(woken).toHaveLength(1)
+ expect(woken[0]!.headers.authorization).toBe(`Bearer ${TOKEN}`)
+ expect(woken[0]!.headers['user-agent']).toMatch(/^autonomous-harness\/\S+ \(wake\)$/)
+ expect(overviews).toBe(3)
+ for (const read of relay.seen.filter((r) => r.path.endsWith(OVERVIEW))) {
+ expect(read.headers.authorization).toBeUndefined()
+ expect(read.headers['x-api-key']).toBeUndefined()
+ }
+ })
+
+ it('ends "not started" when nothing comes up within 45 s, having re-read every 3 s', async () => {
+ await look()
+ const before = requests(TEAM_ID, OVERVIEW).length
+
+ const sections = await look({ wake: [TEAM] })
+
+ expect(section(sections, TEAM)).toMatchObject({ state: 'asleep', wakeOutcome: 'not_started' })
+ expect(requests(TEAM_ID, OVERVIEW).length - before).toBe(15)
+ expect(requests(TEAM_ID, MODELS)).toHaveLength(1)
+ })
+
+ it('ends "nobody serving" when it comes up with nobody on it', async () => {
+ await look()
+ answer(TEAM_ID, OVERVIEW, awake([node('router', ['auto'], { engine: 'grid-router' })]))
+
+ expect(section(await look({ wake: [TEAM] }), TEAM)).toMatchObject({ state: 'awake', models: [], wakeOutcome: 'nobody_serving' })
+ })
+
+ it('a second ask while one is running joins it: one credentialed read', async () => {
+ await look()
+ await service.sections(OWN, { wake: [TEAM] })
+ await service.sections(OWN, { wake: [TEAM] })
+ await service.settled()
+
+ expect(requests(TEAM_ID, MODELS)).toHaveLength(1)
+ })
+
+ it('its outcome stands 10 minutes, and goes once the section is read serving a model', async () => {
+ await look()
+ await look({ wake: [TEAM] })
+ later(300)
+ expect(section(await service.sections(OWN, { refresh: false }), TEAM).wakeOutcome).toBe('not_started')
+ later(301)
+ expect(section(await service.sections(OWN, { refresh: false }), TEAM)).not.toHaveProperty('wakeOutcome')
+
+ await look({ wake: [TEAM] })
+ answer(TEAM_ID, OVERVIEW, awake([node('rig', ['big-model'])]))
+ later()
+ expect(section(await look(), TEAM)).not.toHaveProperty('wakeOutcome')
+ })
+
+ it('re-reads the own grid through its asleep episode, where an automatic look reads it only once', async () => {
+ grid.replan(plan('asleep'))
+ answer(OWN_ID, OVERVIEW, asleep())
+ await look()
+ const before = requests(OWN_ID, OVERVIEW).length
+ let overviews = 0
+ answer(OWN_ID, OVERVIEW, () => ++overviews < 2 ? asleep() : awake([node('mac', ['small-q4'])]))
+
+ expect(section(await look({ wake: [OWN] }), OWN)).toMatchObject({ state: 'awake', models: [{ id: 'small-q4', node: 'mac' }] })
+ expect(requests(OWN_ID, OVERVIEW).length - before).toBe(2)
+ })
+})
+
+describe('the retarget prewarm', () => {
+ /** The team grid seen serving `big-model`, then asleep. */
+ async function teamAsleepServing(): Promise<void> {
+ answer(TEAM_ID, OVERVIEW, awake([node('rig', ['big-model'])]))
+ await look()
+ later()
+ answer(TEAM_ID, OVERVIEW, asleep())
+ await look()
+ }
+
+ it('fires one credentialed read marked (prewarm) for a sleeping grid, and the move never waits on it', async () => {
+ await teamAsleepServing()
+ answer(TEAM_ID, MODELS, { status: 200, body: { data: [] }, delayMs: 5_000 })
+
+ const started = Date.now()
+ expect(await service.retargetPrewarm(TEAM_REF, 'big-model')).toBe('fired')
+ expect(Date.now() - started).toBeLessThan(2_000)
+
+ await expectRequest(TEAM_ID, MODELS, 1)
+ const [prewarm] = requests(TEAM_ID, MODELS)
+ expect(prewarm!.headers.authorization).toBe(`Bearer ${TOKEN}`)
+ expect(prewarm!.headers['user-agent']).toMatch(/^autonomous-harness\/\S+ \(prewarm\)$/)
+ })
+
+ it('fires once per grid per 10 minutes', async () => {
+ await teamAsleepServing()
+ expect(await service.retargetPrewarm(TEAM_REF, 'big-model')).toBe('fired')
+ later(599)
+ expect(await service.retargetPrewarm(TEAM_REF, 'big-model')).toBe('debounced')
+ later(1)
+ expect(await service.retargetPrewarm(TEAM_REF, 'big-model')).toBe('fired')
+ await expectRequest(TEAM_ID, MODELS, 2)
+ })
+
+ it('does not fire for a grid seen awake in the last 60 s, and does for one last seen longer ago', async () => {
+ answer(TEAM_ID, OVERVIEW, awake([node('rig', ['big-model'])]))
+ await look()
+ later(59)
+ expect(await service.retargetPrewarm(TEAM_REF, 'big-model')).toBe('awake')
+ later(1)
+ expect(await service.retargetPrewarm(TEAM_REF, 'big-model')).toBe('fired')
+ })
+
+ it('does not fire for a model the picture does not have', async () => {
+ await teamAsleepServing()
+ expect(await service.retargetPrewarm(TEAM_REF, 'other-model')).toBe('absent')
+ expect(requests(TEAM_ID, MODELS)).toHaveLength(0)
+ })
+
+ it('does not fire when every computer serving the model seems offline', async () => {
+ answer(OWN_ID, OVERVIEW, awake([node('studio', ['big-model'])]))
+ await look()
+ later()
+ answer(OWN_ID, OVERVIEW, asleep())
+ await look()
+ studioOfflineTwice()
+
+ expect(await service.retargetPrewarm(OWN_REF, 'big-model')).toBe('offline')
+ expect(requests(OWN_ID, MODELS)).toHaveLength(0)
+ })
+})
+
+describe('the keystroke prewarm', () => {
+ const onTeam = (model: string | null) => ({ baseUrl: `${relay.base}/g/${TEAM_ID}/relay`, model })
+
+ it('the first input for an agent on a sleeping grid fires one read marked (prewarm-key); more input within 10 min fires nothing', async () => {
+ answer(TEAM_ID, OVERVIEW, awake([node('rig', ['big-model'])]))
+ await look()
+ later()
+ answer(TEAM_ID, OVERVIEW, asleep())
+ await look()
+
+ expect(await service.keystrokePrewarm(onTeam('big-model'))).toBe('fired')
+ expect(await service.keystrokePrewarm(onTeam('big-model'))).toBe('debounced')
+ later(300)
+ expect(await service.keystrokePrewarm(onTeam('big-model'))).toBe('debounced')
+
+ await expectRequest(TEAM_ID, MODELS, 1)
+ expect(requests(TEAM_ID, MODELS)[0]!.headers['user-agent']).toMatch(/^autonomous-harness\/\S+ \(prewarm-key\)$/)
+ })
+
+ it('fires nothing for an agent on its own login, on an awake grid, or on a grid this daemon does not know', async () => {
+ answer(OWN_ID, OVERVIEW, awake([node('mac', ['small-q4'])]))
+ await look()
+
+ expect(await service.keystrokePrewarm(null)).toBe('untracked')
+ expect(await service.keystrokePrewarm({ baseUrl: `${relay.base}/g/${OWN_ID}/relay`, model: 'small-q4' })).toBe('not-asleep')
+ expect(await service.keystrokePrewarm({ baseUrl: `${relay.base}/g/net-elsewhere/relay`, model: null })).toBe('untracked')
+ expect(relay.seen.some((r) => r.path.endsWith(MODELS))).toBe(false)
+ })
+
+ it('shares the 10 minutes with the retarget prewarm', async () => {
+ answer(TEAM_ID, OVERVIEW, awake([node('rig', ['big-model'])]))
+ await look()
+ later()
+ answer(TEAM_ID, OVERVIEW, asleep())
+ await look()
+ expect(await service.retargetPrewarm(TEAM_REF, 'big-model')).toBe('fired')
+ expect(await service.keystrokePrewarm(onTeam('big-model'))).toBe('debounced')
+ })
+})
+
+describe('computers of mine that seem offline', () => {
+ /** The own grid seen with `studio` serving big-model and this computer (`here`) serving small-q4, then asleep. */
+ async function ownAsleep(nodes: unknown[] = [node('studio', ['big-model']), node('here', ['small-q4'])]): Promise<void> {
+ answer(OWN_ID, OVERVIEW, awake(nodes))
+ await look()
+ later()
+ answer(OWN_ID, OVERVIEW, asleep())
+ await look()
+ }
+ const own = async (rowState: boolean) =>
+ section(presentGridSections(await service.sections(OWN, { refresh: false }), { rowState }), OWN).models
+
+ it('labels a row whose computer read offline in two lists 60 s apart — never removes it', async () => {
+ await ownAsleep()
+ studioOfflineTwice()
+
+ expect(await own(true)).toEqual([
+ { id: 'big-model', node: 'studio', unavailable: { reason: 'offline', machine: 'Studio', since: new Date(clock - 60_000).toISOString() } },
+ { id: 'small-q4', node: 'here' },
+ ])
+ // An old build, which asks for no row state, reads it in the node text.
+ expect(await own(false)).toEqual([{ id: 'big-model', node: 'Studio · seems offline' }, { id: 'small-q4', node: 'here' }])
+ })
+
+ it.each<[string, () => Promise<void> | void]>([
+ ['a single offline read', () => {
+ service.observeMachines(machineList([{ id: 'studio-id', hostname: 'studio', status: 'offline' }]), HERE)
+ }],
+ ['two offline reads under 60 s apart', () => {
+ const list = machineList([{ id: 'studio-id', hostname: 'studio', status: 'offline' }])
+ service.observeMachines(list, HERE); later(59); service.observeMachines(list, HERE)
+ }],
+ ['a list gone stale', () => { studioOfflineTwice(); later(181) }],
+ ['the signed-out guest list', () => {
+ const list = machineList([{ id: 'studio-id', hostname: 'studio', status: 'offline' }], true)
+ service.observeMachines(list, HERE); later(60); service.observeMachines(list, HERE)
+ }],
+ ['a name two computers share', () => {
+ const list = machineList([{ id: 'a', hostname: 'studio', status: 'offline' }, { id: 'b', hostname: 'studio', status: 'offline' }])
+ service.observeMachines(list, HERE); later(60); service.observeMachines(list, HERE)
+ }],
+ ['a presence the backend could not read (`unknown`)', () => {
+ const list = machineList([{ id: 'studio-id', hostname: 'studio', status: 'unknown' }])
+ service.observeMachines(list, HERE); later(60); service.observeMachines(list, HERE)
+ }],
+ ['an online read between two offline ones', () => {
+ const offline = machineList([{ id: 'studio-id', hostname: 'studio', status: 'offline' }])
+ service.observeMachines(offline, HERE); later(40)
+ service.observeMachines(machineList([{ id: 'studio-id', hostname: 'studio', status: 'running' }]), HERE); later(40)
+ service.observeMachines(offline, HERE)
+ }],
+ ])('labels nothing for %s', async (_name, arrange) => {
+ await ownAsleep()
+ await arrange()
+ expect((await own(true)).some((row) => 'unavailable' in row)).toBe(false)
+ })
+
+ it('labels nothing while the grid is awake', async () => {
+ answer(OWN_ID, OVERVIEW, awake([node('studio', ['big-model'])]))
+ await look()
+ studioOfflineTwice()
+ expect(await own(true)).toEqual([{ id: 'big-model', node: 'studio' }])
+ })
+
+ it('labels nothing on a shared grid whose node is not marked the account\'s own', async () => {
+ answer(TEAM_ID, OVERVIEW, awake([node('studio', ['big-model'], { provider_email: '[email protected]' })]))
+ await look()
+ later()
+ answer(TEAM_ID, OVERVIEW, asleep())
+ await look()
+ studioOfflineTwice()
+ const team = section(presentGridSections(await service.sections(OWN, { refresh: false }), { rowState: true }), TEAM)
+ expect(team.models).toEqual([{ id: 'big-model', node: 'studio' }])
+ })
+
+ it('labels nothing for a model another, online computer also serves', async () => {
+ await ownAsleep([node('studio', ['big-model']), node('here', ['big-model'])])
+ studioOfflineTwice()
+ expect((await own(true)).some((row) => 'unavailable' in row)).toBe(false)
+ })
+})
+
+describe('the note on an agent already on a model', () => {
+ const onOwn = (model: string | null) => ({ baseUrl: `${relay.base}/g/${OWN_ID}/relay`, model })
+
+ it('says the computers serving its model seem offline', async () => {
+ // The overview lower-cases a node's ids; the exact spelling comes from its curated list.
+ answer(OWN_ID, OVERVIEW, { status: 200, body: { nodes: [node('studio', ['big-model'])], models: [{ id: 'Big-Model' }] } })
+ await look()
+ later()
+ answer(OWN_ID, OVERVIEW, asleep())
+ await look()
+ studioOfflineTwice()
+ await service.sections(OWN, { refresh: false })
+
+ expect(service.annotation(onOwn('big-model'))).toEqual({
+ state: 'asleep', note: { reason: 'offline', model: 'Big-Model', machine: 'Studio' },
+ })
+ })
+
+ it('says the latest record no longer lists its model, and clears on a credential-less read that lists it', async () => {
+ answer(OWN_ID, OVERVIEW, awake([node('mac', ['small-q4'])]))
+ await look()
+ later()
+ answer(OWN_ID, OVERVIEW, asleep(record(30, [{ name: 'mac', models: ['other-model'] }])))
+ await look()
+
+ expect(service.annotation(onOwn('small-q4'))).toEqual({ state: 'asleep', note: { reason: 'not_served', model: 'small-q4' } })
+
+ answer(OWN_ID, OVERVIEW, awake([node('mac', ['small-q4'])]))
+ later()
+ await look()
+ expect(service.annotation(onOwn('small-q4'))).toEqual({ state: 'awake' })
+ expect(relay.seen.every((r) => r.headers.authorization === undefined)).toBe(true)
+ })
+
+ it('rides on the agent frame every client rebuilds the agent from', async () => {
+ answer(OWN_ID, OVERVIEW, asleep(record(30, [{ name: 'mac', models: ['other-model'] }])))
+ await look()
+ const agent = { agentId: 'a1', sessionId: 's1', engine: 'claude', active: true, cwd: '/tmp', runtimes: [], registeredAt: 1,
+ grid: onOwn('small-q4') } as unknown as RegisteredSession
+
+ const frame = await agentFrame(agent, { selectedModel: null, terminalAvailable: true })
+
+ expect(frame.grid).toEqual({ ...onOwn('small-q4'), state: 'asleep', note: { reason: 'not_served', model: 'small-q4' } })
+ })
+
+ it('has no note for Auto, and no annotation for a grid this daemon does not know', async () => {
+ answer(OWN_ID, OVERVIEW, asleep(record(30, [{ name: 'mac', models: ['other-model'] }])))
+ await look()
+ expect(service.annotation(onOwn(null))).toEqual({ state: 'asleep' })
+ expect(service.annotation({ baseUrl: `${relay.base}/g/net-elsewhere/relay`, model: 'x' })).toBeNull()
+ })
+})
+
+describe('no read on the app\'s own schedule carries a credential, with the acts above in place', () => {
+ it('looks, a Model Manager inventory and a launch check send no Authorization and no x-api-key', async () => {
+ answer(OWN_ID, OVERVIEW, awake([node('mac', ['small-q4'])]))
+ studioOfflineTwice()
+ await look()
+ later(); await look()
+ await service.inventory(OWN, true)
+ await service.models(TEAM)
+
+ expect(relay.seen.length).toBeGreaterThan(0)
+ for (const request of relay.seen) {
+ expect(request.path.endsWith(MODELS)).toBe(false)
+ expect(request.headers.authorization).toBeUndefined()
+ expect(request.headers['x-api-key']).toBeUndefined()
+ }
+ })
+})
+
+/** A detached read lands on its own time; wait (in real time) for the relay to have seen it. */
+async function expectRequest(gridId: string, path: string, count: number): Promise<void> {
+ const deadline = Date.now() + 5_000
+ while (requests(gridId, path).length < count && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20))
+ expect(requests(gridId, path)).toHaveLength(count)
+}
+
+describe('after the daemon restarts', () => {
+ const onTeam = (model: string | null) => ({ baseUrl: `${relay.base}/g/${TEAM_ID}/relay`, model })
+
+ it('a keystroke and an agent frame answer from the saved pictures before any window asks for the list', async () => {
+ answer(TEAM_ID, OVERVIEW, awake([node('rig', ['big-model'])]))
+ await look()
+ later()
+ answer(TEAM_ID, OVERVIEW, asleep())
+ await look()
+ // It updated itself: nothing in memory, and nobody has opened a picker since (a phone typing, say).
+ service = freshService()
+ const reads = relay.seen.length
+
+ await service.warm()
+
+ expect(service.annotation(onTeam('big-model'))).toEqual({ state: 'asleep' })
+ expect(service.annotation(onTeam('other-model'))).toEqual({ state: 'asleep', note: { reason: 'not_served', model: 'other-model' } })
+ // Warming read the pictures on disk, not the grid.
+ expect(relay.seen.length).toBe(reads)
+ expect(await service.keystrokePrewarm(onTeam('big-model'))).toBe('fired')
+ await expectRequest(TEAM_ID, MODELS, 1)
+ })
+})
+
+describe('a credentialed read\'s answer', () => {
+ it('teaches the picture each model\'s context window, for the next move onto it', async () => {
+ answer(TEAM_ID, OVERVIEW, asleep(record(60, [{ name: 'rig', models: ['big-model'] }])))
+ await look()
+ expect(await service.contextWindow(TEAM_REF, 'Big-Model')).toBeUndefined()
+ answer(TEAM_ID, MODELS, { status: 200, body: { data: [{ id: 'Big-Model', context_window: 131072 }, { id: 'odd', context_window: 'x' }] } })
+
+ expect(await service.retargetPrewarm(TEAM_REF, 'big-model')).toBe('fired')
+
+ await vi.waitFor(async () => expect(await service.contextWindow(TEAM_REF, 'big-model')).toBe(131072))
+ expect(await service.contextWindow(TEAM_REF, 'odd')).toBeUndefined()
+ })
+})
+
+describe('what goes stale with no read to say so', () => {
+ it('a wake\'s outcome running out, and the machine list going stale, are pushed', async () => {
+ const pushed: number[] = []
+ service.onChange(() => pushed.push(clock))
+ await look()
+ await look({ wake: [TEAM] })
+ const outcome = later_.find((entry) => entry.ms >= 10 * 60_000)
+ expect(outcome).toBeDefined()
+ studioOfflineTwice()
+ const stale = later_.find((entry) => entry.ms >= 3 * 60_000 && entry.ms < 10 * 60_000)
+ expect(stale).toBeDefined()
+
+ await vi.waitFor(() => expect(pushed.length).toBeGreaterThan(0))
+ pushed.length = 0
+ later(601)
+ outcome!.run()
+ await vi.waitFor(() => expect(pushed.length).toBe(1))
+ expect(section(await service.sections(OWN, { refresh: false }), TEAM)).not.toHaveProperty('wakeOutcome')
+ stale!.run()
+ await vi.waitFor(() => expect(pushed.length).toBe(2))
+ })
+})
diff --git a/cli/src/lib/gridModels.ts b/cli/src/lib/gridModels.ts
index 3e4b52bab..fa67a13a6 100644
--- a/cli/src/lib/gridModels.ts
+++ b/cli/src/lib/gridModels.ts
@@ -13,25 +13,31 @@
* - the account's OWN grid, whose status the owner can read, is read at most once per asleep episode.
*
* The credentialed model-list read is gone from every automatic path. What still wakes a grid is a
- * person's act, and it does not go through here.
+ * person's act (issue 03): an explicit wake, moving an agent onto a sleeping grid, the first keystroke
+ * into a pane whose agent runs on one — each decided here, from the picture, and sent through
+ * `gridWake.ts`, the one module that reads a grid with its credential. Beside that, the picture says
+ * which rows only a computer of the account's that seems offline serves (`gridPresence.ts`): a label,
+ * never a removal.
*/
import { createHash, randomUUID } from 'node:crypto'
-import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
+import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { env as config } from '../config/env.js'
import { gridCredentialsPath } from './gridCredentials.js'
import { signedInGridEmail } from './gridDerive.js'
-import { gridExec, gridJson } from './gridExec.js'
-import { contextWindowHint } from './gridLaunch.js'
-import { resolveGridMcpUrl } from './gridMcpUrl.js'
+import { gridJson } from './gridExec.js'
import {
- emptyPicture, mergeAwake, idKey, parsePicture, provenStopped, sectionView, servedKey, unspelled, withAsleep,
- withSpellings, withUnknown, type GridPicture, type LocalRecord, type PictureState, type SectionView, type ServedHere,
+ emptyPicture, mergeAwake, idKey, parsePicture, provenStopped, sectionView, servedKey, servesAModel, unspelled, withAsleep,
+ withSpellings, withUnknown, withWindows, type GridPicture, type LocalRecord, type PictureState, type RowUnavailable,
+ type SectionView, type ServedHere,
} from './gridPicture.js'
+import { ComputerPresence, computersIn, MACHINE_LIST_FRESH_MS } from './gridPresence.js'
import {
OWNER_ASLEEP_STATUS, readBase, readDiscoveryIds, readGridInfo, readOverview, readViaCli, type GridInfo, type GridRead,
type ReadNode,
} from './gridReader.js'
+import type { GridLaunchOverride } from './gridLaunch.js'
+import { PrewarmDebounce, wakeRead, type RelayAccess, type WakePurpose } from './gridWake.js'
import { readRunRecords } from './localModels.js'
export interface GridModel {
@@ -39,8 +45,15 @@ export interface GridModel {
id: string
/** Which machine answers it, or empty when the grid does not say. Display only. */
node: string
+ /** Every computer serving it seems offline — sent only to a client that asked for row state
+ * ([presentGridSections]); an older one reads it in `node` instead. */
+ unavailable?: RowUnavailable
}
+/** How an explicit wake that did not show models ended: the grid did not come up in time, or came up
+ * with nobody serving anything. */
+export type WakeOutcome = 'not_started' | 'nobody_serving'
+
/** One grid this computer is signed into, with what it serves — the picker's section. */
export interface GridSection {
/** The grid's name as `grid ls` prints it. */
@@ -56,6 +69,8 @@ export interface GridSection {
state?: PictureState
seenAt?: string | null
lastKnownAge?: number | null
+ /** Additive (issue 03): the last explicit wake of this grid did not show models — while it stands. */
+ wakeOutcome?: WakeOutcome
}
/** What the Model Manager is told about the grid it runs on (`localModels.ts`'s `GridInventory`). */
@@ -86,6 +101,17 @@ const CHANGE_COALESCE_MS = 250
* (`GRID_ATTACH_WAIT_MS`, 6s) shares: a read slower than this lands behind the answer and is pushed. */
const FIRST_READ_WAIT_MS = 4_000
+/** An explicit wake re-reads the grid, without a credential, this often and for this long after its one
+ * credentialed read — long enough for a master to boot and its providers to report (issue 03). */
+const WAKE_REREAD_MS = 3_000
+const WAKE_WINDOW_MS = 45_000
+
+/** How long a wake that showed no models keeps saying so. */
+const WAKE_OUTCOME_STANDS_MS = 10 * 60_000
+
+/** A grid seen awake this recently needs no prewarm: an agent moved onto it will find it up. */
+const RECENTLY_AWAKE_MS = 60_000
+
interface GridRow { name: string; type: string; id: string }
/** The key a grid is tracked under when `grid ls` gave it no network id — its name, marked as such, so
@@ -119,8 +145,34 @@ interface Tracked {
/** The last awake overview's own node objects, for the Model Manager. Not persisted. */
rawNodes: Record<string, unknown>[]
pending: Promise<void> | null
+ /** An explicit wake running for this grid; a second ask joins it. */
+ waking: Promise<void> | null
+ /** How the last explicit wake ended when it showed no models, and when. */
+ wakeOutcome: { outcome: WakeOutcome; at: number } | null
+ /** What a picker was last told about this grid — what an agent's note is read from, with no I/O. */
+ lastView: GridView | null
}
+/** One grid's section as this service builds it: the picture's view, and the wake it may be in. */
+type GridView = Omit<SectionView, 'models'> & { models: GridModel[]; wakeOutcome?: WakeOutcome }
+
+/** What a prewarm did: `fired` one credentialed read, or why it did not. */
+export type PrewarmOutcome =
+ | 'fired' | 'debounced' | 'awake' | 'absent' | 'offline'
+ /** Keystroke only: the agent's grid is not one this daemon is tracking, or it is not asleep. */
+ | 'untracked' | 'not-asleep'
+
+/** A grid as a launch names it: its network id (what it is tracked and persisted under) and its name. */
+export interface GridRef { networkId: string; gridName: string }
+
+/** Where an agent's inference goes (`gridAssignment.ts`) — all a prewarm or a note needs of it. */
+export interface AgentGridTarget { baseUrl: string; model: string | null }
+
+/** What is said about an agent already on a grid model (issue 03): that grid's state, and a note when its
+ * model will not answer — every computer serving it seems offline, or the latest list no longer has it. */
+export interface GridNote { reason: 'offline' | 'not_served'; model: string; machine?: string }
+export interface GridAnnotation { state: PictureState; note?: GridNote }
+
export interface GridModelsDeps {
now: () => number
/** Where pictures are kept (`<data dir>/grid-pictures`). */
@@ -131,6 +183,10 @@ export interface GridModelsDeps {
email: () => string | null
/** [FIRST_READ_WAIT_MS], injectable so a test need not wait it out. */
firstReadWaitMs: number
+ /** The explicit wake's pause between re-reads — injectable, so a test's clock moves instead. */
+ sleep: (ms: number) => Promise<void>
+ /** Run `run` in `ms`, with nothing else to trigger it (an expiry); answers how to call it off. */
+ after: (ms: number, run: () => void) => () => void
}
const defaultDeps: GridModelsDeps = {
@@ -139,6 +195,12 @@ const defaultDeps: GridModelsDeps = {
gridHome: () => dirname(gridCredentialsPath()),
email: () => signedInGridEmail(),
firstReadWaitMs: FIRST_READ_WAIT_MS,
+ sleep: (ms) => new Promise((resolve) => { setTimeout(resolve, ms).unref?.() }),
+ after: (ms, run) => {
+ const timer = setTimeout(run, ms)
+ timer.unref?.()
+ return () => clearTimeout(timer)
+ },
}
/**
@@ -152,8 +214,12 @@ export class GridModelsService {
private readonly deps: GridModelsDeps
private readonly tracked = new Map<string, Tracked>()
private readonly listeners = new Set<() => void>()
+ private readonly presence = new ComputerPresence()
+ private readonly debounce = new PrewarmDebounce()
private rows: GridRow[] | null = null
private changeTimer: NodeJS.Timeout | null = null
+ /** Called off by the next machine list: fires only when none came in time, and the labels lapse. */
+ private cancelStaleList: (() => void) | null = null
constructor(deps: Partial<GridModelsDeps> = {}) {
this.deps = { ...defaultDeps, ...deps }
@@ -168,7 +234,26 @@ export class GridModelsService {
/** Resolves once every read already started has landed — for a test, and for a caller that must see
* the answer a read it triggered produced. */
async settled(): Promise<void> {
- await Promise.all([...this.tracked.values()].map((tracked) => tracked.pending?.catch(() => {})))
+ await Promise.all([...this.tracked.values()].flatMap((tracked) => [tracked.pending?.catch(() => {}), tracked.waking]))
+ }
+
+ /**
+ * Every picture this computer saved, taken back into memory with nothing read from any grid — at daemon
+ * start, so an agent's frame carries its grid's state and note, and a keystroke can start its grid, from
+ * the first moment: before any window has asked for the list, and when none ever does (a phone typing).
+ */
+ async warm(): Promise<void> {
+ const folder = join(this.deps.dataDir(), PICTURES_DIR)
+ const names = await readdir(folder).catch(() => [] as string[])
+ await Promise.all(names.filter((name) => name.endsWith('.json')).map(async (name) => {
+ try {
+ const saved = JSON.parse(await readFile(join(folder, name), 'utf8')) as SavedPicture
+ if (typeof saved.networkId !== 'string' || !saved.networkId) return
+ const gridName = typeof saved.name === 'string' ? saved.name : ''
+ const tracked = await this.track({ id: saved.networkId, name: gridName, type: '' }, saved.own === true ? true : undefined)
+ await this.view(tracked)
+ } catch { /* not a picture this module wrote; the list will read that grid when asked */ }
+ }))
}
/** Every read is due again — for a caller that has just changed what a grid serves, or which grid is
@@ -189,11 +274,14 @@ export class GridModelsService {
* has never seen is waited for, and only for [FIRST_READ_WAIT_MS]: an answer made of nothing is worse
* than a short wait, and a timed-out ask is worse than both.
*/
- async sections(ownGridName: string | null, opts: { refresh?: boolean } = {}): Promise<GridSection[]> {
+ async sections(ownGridName: string | null, opts: { refresh?: boolean; wake?: readonly string[] } = {}): Promise<GridSection[]> {
const rows = await this.gridRows(ownGridName)
const sections = await Promise.all(rows.map(async (row) => {
const tracked = await this.track(row, row.name === ownGridName)
- if (opts.refresh !== false && this.due(tracked)) {
+ // A person asked for this one to start: its wake is running before the answer is built, so the
+ // answer says "waking" — and a wake's own re-reads stand in for the refresh below.
+ if (opts.wake?.includes(row.name)) this.startWake(tracked)
+ if (opts.refresh !== false && !tracked.waking && this.due(tracked)) {
const refreshing = this.refresh(tracked)
if (!tracked.known) await this.within(refreshing, this.deps.firstReadWaitMs)
else void refreshing.catch(() => {})
@@ -254,11 +342,12 @@ export class GridModelsService {
tracked = {
id: row.id, name: row.name, own: false, picture: emptyPicture(), loaded: false, known: false, saved: '',
readAt: null, readTtl: 0, info: null, episodeRead: false, seen: new Set(), spelled: new Set(), rawNodes: [],
- pending: null,
+ pending: null, waking: null, wakeOutcome: null, lastView: null,
}
this.tracked.set(row.id, tracked)
}
- tracked.name = row.name
+ // A warmed grid may know only its id; the list's name is better than none.
+ if (row.name) tracked.name = row.name
if (own !== undefined) tracked.own = own
if (!tracked.loaded) {
tracked.loaded = true
@@ -288,29 +377,37 @@ export class GridModelsService {
/** One refresh per grid at a time; every asker shares it. */
private refresh(tracked: Tracked): Promise<void> {
- tracked.pending ??= this.read(tracked).finally(() => { tracked.pending = null })
- return tracked.pending
+ const pending = tracked.pending ?? this.read(tracked).then(() => {}).finally(() => { tracked.pending = null })
+ tracked.pending = pending
+ return pending
}
- private async read(tracked: Tracked): Promise<void> {
+ /**
+ * One credential-less read, applied. `waking`: an explicit wake's re-read, which goes to the grid even
+ * where an automatic look would not (the own grid past its one read per asleep episode). Answers the
+ * read it made, or null when the episode rule stood in for one.
+ */
+ private async read(tracked: Tracked, waking = false): Promise<GridRead | null> {
const before = JSON.stringify(await this.signature(tracked))
const info = await this.info(tracked)
const asleepByStatus = tracked.own && info?.status === OWNER_ASLEEP_STATUS
+ let made: GridRead | null = null
// The own grid, while its status says asleep, is read exactly once per asleep episode — to fetch the
// platform's record of what it served — and then left alone until the status changes.
- if (asleepByStatus && tracked.episodeRead) {
+ if (asleepByStatus && tracked.episodeRead && !waking) {
await this.apply(tracked, { kind: 'asleep', lastKnown: null }, null)
} else {
tracked.episodeRead = asleepByStatus
const base = readBase(info?.gridUrl ?? null)
- let read: GridRead = base ? await readOverview(base) : { kind: 'unreachable' }
+ made = base ? await readOverview(base) : { kind: 'unreachable' }
// Only when nothing answered at all — never to second-guess an answer the grid gave.
- if (read.kind === 'unreachable') read = await readViaCli(tracked.name)
- await this.apply(tracked, read, base)
+ if (made.kind === 'unreachable') made = await readViaCli(tracked.name)
+ await this.apply(tracked, made, base)
}
await this.save(tracked)
tracked.known = true
if (JSON.stringify(await this.signature(tracked)) !== before) this.changed()
+ return made
}
private async info(tracked: Tracked): Promise<GridInfo | null> {
@@ -341,7 +438,7 @@ export class GridModelsService {
const isMine = (node: ReadNode): boolean => !!email && node.providerEmail?.trim().toLowerCase() === email
const previous = tracked.picture
let picture = mergeAwake(previous, read.nodes, now, isMine, (name, key) => provenStopped(previous, here, name, key))
- picture = { ...picture, caseMap: withSpellings(picture.caseMap, [...read.curatedIds, ...here.records.flatMap((r) => r.ids)]) }
+ picture = withWindows({ ...picture, caseMap: withSpellings(picture.caseMap, [...read.curatedIds, ...here.records.flatMap((r) => r.ids)]) }, read.windows)
const unknownIds = unspelled(picture, read.nodes).filter((key) => !tracked.spelled.has(key))
if (unknownIds.length && base) {
unknownIds.forEach((key) => tracked.spelled.add(key))
@@ -350,6 +447,8 @@ export class GridModelsService {
tracked.picture = picture
tracked.rawNodes = read.rawNodes
tracked.readTtl = AWAKE_MEMO_MS
+ // A wake that showed nothing stops saying so once the grid is found serving.
+ if (servesAModel(read.nodes)) tracked.wakeOutcome = null
// What this computer serves is re-learnt from what is live now: the grid has just said what it serves.
tracked.seen = new Set(liveKeys(here.records))
}
@@ -365,30 +464,197 @@ export class GridModelsService {
return { records, seen: tracked.seen, own: tracked.own }
}
- private async view(tracked: Tracked): Promise<Omit<SectionView, 'models'> & { models: GridModel[] }> {
- return sectionView(tracked.picture, await this.servedHere(tracked), this.deps.now())
+ private async view(tracked: Tracked): Promise<GridView> {
+ const now = this.deps.now()
+ const view = sectionView(tracked.picture, await this.servedHere(tracked), now, (name) => this.presence.seemsOffline(name, now))
+ const outcome = tracked.wakeOutcome && now - tracked.wakeOutcome.at < WAKE_OUTCOME_STANDS_MS ? tracked.wakeOutcome.outcome : null
+ const shown: GridView = {
+ ...view,
+ // A wake in flight is the state, whatever its re-reads have found so far.
+ state: tracked.waking ? 'waking' : view.state,
+ ...(outcome && !tracked.waking ? { wakeOutcome: outcome } : {}),
+ }
+ tracked.lastView = shown
+ return shown
}
- /** What a push is about: the rows and the state — not the ages, which move every second. */
+ /** What a push is about: the rows (labels included), the state and a wake's outcome — not the ages,
+ * which move every second. */
private async signature(tracked: Tracked): Promise<unknown> {
const view = await this.view(tracked)
- return { models: view.models, state: view.state }
+ return { models: view.models, state: view.state, wakeOutcome: view.wakeOutcome }
}
+ /** Coalesced: the views are rebuilt first, so a listener reading an agent's note sees the change. */
private changed(): void {
if (this.changeTimer) return
this.changeTimer = setTimeout(() => {
this.changeTimer = null
- for (const listener of this.listeners) {
- try { listener() } catch { /* a listener's failure is its own */ }
- }
+ void Promise.all([...this.tracked.values()].map((tracked) => this.view(tracked).catch(() => null))).then(() => {
+ for (const listener of this.listeners) {
+ try { listener() } catch { /* a listener's failure is its own */ }
+ }
+ })
}, CHANGE_COALESCE_MS)
this.changeTimer.unref?.()
}
+ // ── a person's act (issue 03) ─────────────────────────────────────────────────────────────────────
+
+ /** What was read about `tracked` is stale now: a person has just acted on it. The picture stays. */
+ private dropMemo(tracked: Tracked): void {
+ tracked.readAt = null
+ tracked.info = null
+ tracked.episodeRead = false
+ }
+
+ /**
+ * An explicit wake — "Show models", the viewer's "Wake now". Returns at once (the answer being built
+ * says "waking"); behind it, ONE credentialed read marked `(wake)`, then credential-less re-reads every
+ * [WAKE_REREAD_MS] for up to [WAKE_WINDOW_MS], merged like any read, until one finds a node serving.
+ * A second ask while it runs joins it.
+ */
+ private startWake(tracked: Tracked): void {
+ if (tracked.waking) return
+ this.dropMemo(tracked)
+ tracked.wakeOutcome = null
+ // A prewarm right behind a wake would pay for the same boot twice.
+ this.debounce.mark(tracked.id, this.deps.now())
+ void this.credentialedRead(tracked, 'wake')
+ tracked.waking = this.wake(tracked).catch(() => {}).finally(() => {
+ tracked.waking = null
+ // The status said asleep when this began; whatever it says now is asked afresh.
+ tracked.info = null
+ this.changed()
+ })
+ this.changed()
+ }
+
+ private async wake(tracked: Tracked): Promise<void> {
+ let cameUp = false
+ for (let reread = 0; reread < WAKE_WINDOW_MS / WAKE_REREAD_MS; reread++) {
+ await this.deps.sleep(WAKE_REREAD_MS)
+ const read = await this.readNow(tracked)
+ if (read?.kind !== 'awake') continue
+ cameUp = true
+ if (servesAModel(read.nodes)) return
+ }
+ tracked.wakeOutcome = { outcome: cameUp ? 'nobody_serving' : 'not_started', at: this.deps.now() }
+ // It stops being said with no read to notice: tell the windows when it does.
+ this.deps.after(WAKE_OUTCOME_STANDS_MS, () => this.changed())
+ }
+
+ /** A wake's re-read: after any read already out, and never shared with the automatic path's memo. */
+ private async readNow(tracked: Tracked): Promise<GridRead | null> {
+ while (tracked.pending) await tracked.pending.catch(() => {})
+ let answered: GridRead | null = null
+ tracked.pending = this.read(tracked, true).then((read) => { answered = read }).finally(() => { tracked.pending = null })
+ await tracked.pending
+ return answered
+ }
+
+ /** One credentialed read marked `purpose`, detached — unless one went out for this grid in the last
+ * ten minutes. */
+ private sendPrewarm(tracked: Tracked, purpose: WakePurpose, now: number, access?: RelayAccess): PrewarmOutcome {
+ if (!this.debounce.allows(tracked.id, now)) return 'debounced'
+ this.debounce.mark(tracked.id, now)
+ void this.credentialedRead(tracked, purpose, access)
+ return 'fired'
+ }
+
+ /** The credentialed read itself ([wakeRead]). Its answer lists each model's context window, which the
+ * picture keeps for the next move onto that grid — the one thing it teaches that no free read did. */
+ private async credentialedRead(tracked: Tracked, purpose: WakePurpose, access?: RelayAccess): Promise<void> {
+ const name = tracked.name || (await this.gridRows(null)).find((row) => row.id === tracked.id)?.name
+ if (!name) return
+ const windows = await wakeRead(name, purpose, access)
+ if (!windows) return
+ tracked.picture = withWindows(tracked.picture, windows)
+ await this.save(tracked)
+ }
+
+ /**
+ * An agent was just moved onto `model` on `gridName`: start that grid while the pane restarts — when
+ * its picture says asleep or it was not seen awake in the last minute. Not when the model is not in the
+ * picture, and not when every computer serving it seems offline: a boot nobody can answer on is wasted.
+ * The move never waits on this, and is never refused by it.
+ */
+ async retargetPrewarm(grid: GridRef, model: string, access?: RelayAccess): Promise<PrewarmOutcome> {
+ // By the id the move already resolved: no `grid ls` of its own behind a click.
+ const tracked = await this.track({ id: grid.networkId, name: grid.gridName, type: '' })
+ const now = this.deps.now()
+ const { state, seenAt } = tracked.picture
+ const view = await this.view(tracked)
+ this.dropMemo(tracked)
+ if (state !== 'asleep' && seenAt !== null && now - seenAt < RECENTLY_AWAKE_MS) return 'awake'
+ const row = servedRow(view.models, model)
+ if (!row) return 'absent'
+ if (row.unavailable) return 'offline'
+ return this.sendPrewarm(tracked, 'prewarm', now, access)
+ }
+
+ /**
+ * Someone typed into a terminal whose agent runs on `target`: when that grid's picture says asleep,
+ * start it while they type. Asked on EVERY input, so it answers from memory — the picture and the view
+ * a picker was last given — and the ten-minute debounce is checked first.
+ */
+ async keystrokePrewarm(target: AgentGridTarget | null | undefined): Promise<PrewarmOutcome> {
+ const tracked = target ? this.trackedFor(target.baseUrl) : null
+ if (!tracked || !target) return 'untracked'
+ if (tracked.picture.state !== 'asleep' || tracked.waking) return 'not-asleep'
+ const now = this.deps.now()
+ if (!this.debounce.allows(tracked.id, now)) return 'debounced'
+ const rows = target.model ? tracked.lastView?.models : undefined
+ const row = rows && servedRow(rows, target.model!)
+ if (rows && !row) return 'absent'
+ if (row?.unavailable) return 'offline'
+ this.dropMemo(tracked)
+ return this.sendPrewarm(tracked, 'prewarm-key', now)
+ }
+
+ /** The grid an agent's inference goes to: the tracked grid whose id is a segment of its relay's path. */
+ private trackedFor(baseUrl: string): Tracked | null {
+ let segments: string[]
+ try { segments = new URL(baseUrl).pathname.split('/').filter(Boolean) } catch { return null }
+ return [...this.tracked.values()].find((tracked) => !tracked.id.startsWith(NAME_ONLY_PREFIX) && segments.includes(tracked.id)) ?? null
+ }
+
+ /**
+ * What an agent frame says about the agent's grid, from what a picker was last told — no I/O, so a
+ * frame costs nothing. Null for an agent on no grid this daemon is tracking.
+ */
+ annotation(target: AgentGridTarget | null | undefined): GridAnnotation | null {
+ const tracked = target ? this.trackedFor(target.baseUrl) : null
+ const view = tracked?.lastView
+ if (!tracked || !view || !target) return null
+ if (!target.model || view.state === 'waking') return { state: view.state }
+ const row = servedRow(view.models, target.model)
+ if (row?.unavailable) return { state: view.state, note: { reason: 'offline', model: row.id, machine: row.unavailable.machine } }
+ // "No longer lists" needs a list: a grid never read says nothing about any model.
+ if (!row && tracked.picture.listAt !== null) return { state: view.state, note: { reason: 'not_served', model: target.model } }
+ return { state: view.state }
+ }
+
+ /** A machine list this daemon just read (`GET /api/machines`, or null when signed out): which of the
+ * account's other computers seem offline. Re-tells clients only when a verdict changed. */
+ observeMachines(body: unknown, localComputerId: string): void {
+ const list = computersIn(body, localComputerId) ?? { computers: [], guest: true }
+ if (this.presence.observe(list, this.deps.now())) this.changed()
+ // A list that stops coming (this computer lost the backend) stops labelling, with no read to notice.
+ this.cancelStaleList?.()
+ this.cancelStaleList = this.deps.after(MACHINE_LIST_FRESH_MS + 1_000, () => this.changed())
+ }
+
+ /** The context window `model` was last reported with on the grid tracked as `networkId`, read without a
+ * credential — what a launch tells the engine to compact inside. */
+ async contextWindow(grid: GridRef, model: string): Promise<number | undefined> {
+ const tracked = await this.track({ id: grid.networkId, name: grid.gridName, type: '' })
+ return tracked.picture.windows[idKey(model)]
+ }
+
private file(tracked: Tracked): string {
const name = createHash('sha256').update(tracked.id).digest('hex').slice(0, 24)
- return join(this.deps.dataDir(), 'grid-pictures', `${name}.json`)
+ return join(this.deps.dataDir(), PICTURES_DIR, `${name}.json`)
}
private async load(tracked: Tracked): Promise<void> {
@@ -410,13 +676,27 @@ export class GridModelsService {
const file = this.file(tracked)
await mkdir(dirname(file), { recursive: true, mode: 0o700 })
const temp = `${file}.${randomUUID()}.tmp`
- await writeFile(temp, JSON.stringify({ networkId: tracked.id, picture: tracked.picture }), { mode: 0o600 })
+ const saved: SavedPicture = { networkId: tracked.id, name: tracked.name, own: tracked.own, picture: tracked.picture }
+ await writeFile(temp, JSON.stringify(saved), { mode: 0o600 })
await rename(temp, file)
tracked.saved = text
} catch { /* the picture is still in memory; the next read tries again */ }
}
}
+/** A picture as saved: which grid it is (its name and whether it is the account's own, so a daemon that
+ * just started can use it before `grid ls` is asked — both absent from a file written before issue 03). */
+interface SavedPicture { networkId?: unknown; name?: unknown; own?: unknown; picture?: unknown }
+
+/** Where pictures are kept, under the data directory. */
+const PICTURES_DIR = 'grid-pictures'
+
+/** The row a view offers for `model`, whatever its case. */
+function servedRow(rows: readonly GridModel[], model: string): GridModel | undefined {
+ const key = idKey(model)
+ return rows.find((row) => idKey(row.id) === key)
+}
+
function liveKeys(records: readonly LocalRecord[]): string[] {
return records
.filter((record) => record.pid !== null && record.alive)
@@ -432,11 +712,59 @@ export async function listGridModels(gridName: string | null): Promise<GridModel
return service.models(gridName.trim())
}
-/** Every grid this computer is signed into, each with its models, own grid first. */
-export function listAllGridModels(ownGridName: string | null, opts: { refresh?: boolean } = {}): Promise<GridSection[]> {
+/** The pictures this computer saved, back in memory ([GridModelsService.warm]) — at daemon start. */
+export function warmGridModels(): Promise<void> {
+ return service.warm()
+}
+
+/** Every grid this computer is signed into, each with its models, own grid first. `wake` names the
+ * sections a person asked to start (issue 03's explicit wake). */
+export function listAllGridModels(ownGridName: string | null, opts: { refresh?: boolean; wake?: readonly string[] } = {}): Promise<GridSection[]> {
return service.sections(ownGridName, opts)
}
+/**
+ * The sections as a client that did or did not ask for row state reads them. One that did (`rowState`)
+ * gets each label as `unavailable` beside a plain `node`; an older one, which would draw neither, reads
+ * the label in the node text — "<computer> · seems offline" — and nothing else changes for it.
+ */
+export function presentGridSections(sections: GridSection[], opts: { rowState: boolean }): GridSection[] {
+ if (opts.rowState) return sections
+ return sections.map((section) => ({
+ ...section,
+ models: section.models.map(({ unavailable, ...row }) => unavailable ? { ...row, node: `${unavailable.machine} · seems offline` } : row),
+ }))
+}
+
+/** An agent was just moved onto the grid model `launch` names — start that grid while the pane restarts,
+ * if it needs it ([GridModelsService.retargetPrewarm]), with the relay and credential the move resolved.
+ * A launch with no model (Auto) names nothing to check, and starts nothing. */
+export async function retargetPrewarm(launch: GridLaunchOverride): Promise<PrewarmOutcome | null> {
+ if (!launch.model) return null
+ return service.retargetPrewarm({ networkId: launch.networkId, gridName: launch.networkName }, launch.model,
+ { baseUrl: launch.baseUrl, apiKey: launch.apiKey })
+}
+
+/** Input reached a terminal whose agent runs on `target` ([GridModelsService.keystrokePrewarm]). */
+export function keystrokePrewarm(target: AgentGridTarget | null | undefined): Promise<PrewarmOutcome> {
+ return service.keystrokePrewarm(target)
+}
+
+/** What an agent frame says about the grid the agent is on ([GridModelsService.annotation]). */
+export function gridAnnotation(target: AgentGridTarget | null | undefined): GridAnnotation | null {
+ return service.annotation(target)
+}
+
+/** The context window `model` was last reported with on `grid`, read without a credential. */
+export function gridContextWindow(grid: GridRef, model: string): Promise<number | undefined> {
+ return service.contextWindow(grid, model)
+}
+
+/** A machine list this daemon just read, or null when signed out ([GridModelsService.observeMachines]). */
+export function observeMachineList(body: unknown, localComputerId: string): void {
+ service.observeMachines(body, localComputerId)
+}
+
/** The Model Manager's inventory of the own grid (`LocalModels`' injected `inventory`). */
export function gridInventory(gridName: string, force: boolean): Promise<GridInventoryAnswer> {
return service.inventory(gridName, force)
@@ -457,110 +785,3 @@ export function resetGridModels(deps: Partial<GridModelsDeps> = {}): GridModelsS
service = new GridModelsService(deps)
return service
}
-
-/** A row of the relay's `/models`: the id it routes, and the context window it reports for it. */
-interface RelayModel { id: string; contextWindow?: number }
-
-/**
- * The relay's own catalogue. Empty when it cannot be asked — callers read that as "fall back".
- *
- * ⚠️ A SIGNED-IN read, so on a sleeping grid it WAKES it. Asked only by [resolveGridTarget], i.e. when
- * a person moves an agent onto a model or starts one there — an act that needs the grid anyway. Never
- * from the model list or any other read made on the app's own schedule (grid-reads-without-waking).
- */
-async function relayModels(baseUrl: string, apiKey: string): Promise<RelayModel[]> {
- try {
- const response = await fetch(`${baseUrl.replace(/\/$/, '')}/models`, {
- headers: { authorization: `Bearer ${apiKey}` },
- signal: AbortSignal.timeout(10_000),
- })
- if (!response.ok) return []
- const body = await response.json() as { data?: Array<{ id?: unknown; context_window?: unknown }> }
- return (body.data ?? []).flatMap((m) => {
- if (typeof m.id !== 'string' || !m.id) return []
- const contextWindow = contextWindowHint(m.context_window)
- return [{ id: m.id, ...(contextWindow ? { contextWindow } : {}) }]
- })
- } catch {
- return []
- }
-}
-
-
-/** `grid info --env` prints shell exports; these are the two that matter. */
-const ENV_LINE = /^export\s+(OPENAI_BASE_URL|OPENAI_API_KEY)=(.*)$/gm
-
-/** What `resolveGridTarget` answers: the launch override an engine is built from. */
-export interface GridTarget {
- networkId: string
- networkName: string
- baseUrl: string
- /** A live credential — see the function comment. */
- apiKey: string
- model: string
- /** The control plane's web-tools MCP endpoint. Absent when it could not be obtained; the agent
- * then runs on the grid with no web tools, and the daemon log says why. */
- mcpUrl?: string
- /** The model's context window as the relay reports it, so the engine can be told to compact
- * inside it (`GridLaunchOverride.contextWindow`). Absent when the relay did not say. */
- contextWindow?: number
-}
-
-/**
- * Everything an engine needs to be pointed at `gridName`, resolved on THIS machine.
- *
- * Deliberately not something a client sends. The app names a model; the endpoint and the credential
- * are read here, from the `grid` CLI that is already signed in, so no grid credential ever crosses
- * the relay and there is one source of truth for an address the app could not know anyway.
- *
- * ⚠️ The returned `apiKey` is a live credential. It goes into the engine's ENVIRONMENT and never into
- * argv or a log line — `gridLaunch.ts` is what enforces that, and this value must keep travelling
- * through it rather than around it.
- *
- * Web tools ride on the same credential: the control plane's MCP server accepts the inference token,
- * so `mcpUrl` is the only thing added here, and it is added FIRST. `grid mcp config` renews the token
- * when it is within a month of expiry and persists the renewal; `info --env` never renews, so asked
- * in the other order it could hand inference an older token than the one the web tools hold — both
- * valid, and a mismatch nobody would think to look for. A missing `mcpUrl` degrades rather than
- * refuses: inference is the feature, web search is an accessory (`gridMcpUrl.ts`).
- */
-export async function resolveGridTarget(gridName: string | null, model: string): Promise<GridTarget | null> {
- if (!gridName?.trim() || !model.trim()) return null
- const mcpUrl = await resolveGridMcpUrl(gridName)
- const info = await gridExec(['--remote', 'info', gridName, '--env'])
- if (info.code !== 'OK') return null
- const { baseUrl, apiKey } = readEnvExports(info.stdout)
- if (!baseUrl || !apiKey) return null
- // The grid's own id, for the record the launch is written into. Falls back to the name, which is
- // unique on this account and is all the launch actually needs to be re-derivable. The relay's
- // catalogue alongside it, not after: it is only for the window, and a click waits on both.
- const [{ value: rows }, served] = await Promise.all([
- gridJson<Array<{ grid?: unknown; id?: unknown }>>(['--remote', 'ls']),
- relayModels(baseUrl, apiKey),
- ])
- const row = Array.isArray(rows) ? rows.find((r) => r.grid === gridName) : undefined
- // Exact first: the relay is case-sensitive about ids and the picker sends the relay's spelling.
- const listed = served.find((m) => m.id === model) ?? served.find((m) => m.id.toLowerCase() === model.toLowerCase())
- return {
- networkId: typeof row?.id === 'string' ? row.id : gridName,
- networkName: gridName,
- baseUrl,
- apiKey,
- model,
- ...(mcpUrl ? { mcpUrl } : {}),
- ...(listed?.contextWindow ? { contextWindow: listed.contextWindow } : {}),
- }
-}
-
-/** The two exports out of `grid info --env`. ⚠️ Values are SHELL-QUOTED — a base URL read with the
- * quotes still on produces a request to a host that does not exist. */
-function readEnvExports(stdout: string): { baseUrl: string; apiKey: string } {
- let baseUrl = ''
- let apiKey = ''
- for (const match of stdout.matchAll(ENV_LINE)) {
- const value = match[2]!.trim().replace(/^["']|["']$/g, '')
- if (match[1] === 'OPENAI_BASE_URL') baseUrl = value
- else apiKey = value
- }
- return { baseUrl, apiKey }
-}
diff --git a/cli/src/lib/gridPicture.ts b/cli/src/lib/gridPicture.ts
index 517c86558..60273aea5 100644
--- a/cli/src/lib/gridPicture.ts
+++ b/cli/src/lib/gridPicture.ts
@@ -9,6 +9,7 @@
* answer or record, or this computer's own run records. Everything that is not evidence leaves the list
* stale, never shorter, and never wakes anything.
*/
+import type { OfflineReading } from './gridPresence.js'
import type { LastKnown, ReadNode } from './gridReader.js'
/**
@@ -74,10 +75,20 @@ export interface GridPicture {
nodes: PictureNode[]
/** lower-case id → exact id. */
caseMap: Record<string, string>
+ /** lower-case id → the model's context window, as the last awake read that reported one said. */
+ windows: Record<string, number>
}
export function emptyPicture(): GridPicture {
- return { spec: 1, state: 'unknown', seenAt: null, listAt: null, nodes: [], caseMap: {} }
+ return { spec: 1, state: 'unknown', seenAt: null, listAt: null, nodes: [], caseMap: {}, windows: {} }
+}
+
+/** `windows` (keyed without case) with a read's figures folded in — the latest figure for a model wins. */
+export function withWindows(picture: GridPicture, windows: Record<string, number>): GridPicture {
+ if (!Object.keys(windows).length) return picture
+ const merged = { ...picture.windows, ...windows }
+ const kept = Object.entries(merged).slice(-MAX_SAVED_WINDOWS)
+ return { ...picture, windows: Object.fromEntries(kept) }
}
/** The join key for a model id across every source: trimmed, without case. (Not `localModels.ts`'s own
@@ -117,6 +128,11 @@ export function unspelled(picture: GridPicture, nodes: readonly ReadNode[]): str
return [...missing]
}
+/** Whether an awake answer names a node that serves anything — a router serves nothing of its own. */
+export function servesAModel(nodes: ReadonlyArray<{ engine: string; models: readonly string[] }>): boolean {
+ return nodes.some((node) => node.engine !== ROUTER_ENGINE && node.models.length > 0)
+}
+
const listed = (key: string, at: number): PictureModel => ({ key, seenAt: at, absentSince: null, absentReads: 0 })
function nodeFrom(read: { name: string; engine: string; models: string[] }, at: number, isMine: boolean): PictureNode {
@@ -241,10 +257,21 @@ export function provenStopped(picture: GridPicture, here: ServedHere, name: stri
return here.own || same[0]!.isMine
}
+/** A row nobody may be able to answer right now — a label on it, never a reason to leave it out. */
+export interface RowUnavailable {
+ reason: 'offline'
+ /** The computer's name as the Machines list shows it. */
+ machine: string
+ /** ISO-8601 of the first offline read. */
+ since: string
+}
+
/** One row of the picker's section: the id an engine is pointed at, and which machine answers it. */
export interface GridModelRow {
id: string
node: string
+ /** Every computer serving it seems offline (issue 03). Absent otherwise. */
+ unavailable?: RowUnavailable
}
export interface SectionView {
@@ -256,34 +283,59 @@ export interface SectionView {
lastKnownAge: number | null
}
+/**
+ * Whether the account's computer behind the grid node `name` seems offline — the caller's answer from the
+ * machine list (`gridPresence.ts`). Asked only while a grid is not awake, and only about nodes that are the
+ * account's own.
+ */
+export type SeemsOffline = (name: string) => OfflineReading | null
+
/**
* What the picker is told about one grid. While the grid is not awake, this computer's own live records
- * are shown under its name (a model this computer serves is never "set up your first model"), and a row
- * this computer has proof it stopped is taken out at once.
+ * are shown under its name (a model this computer serves is never "set up your first model"), a row
+ * this computer has proof it stopped is taken out at once, and a row that only the account's own
+ * computers serve, every one of which seems offline, is LABELLED — never taken out.
*/
-export function sectionView(picture: GridPicture, here: ServedHere, now: number): SectionView {
+export function sectionView(picture: GridPicture, here: ServedHere, now: number, seemsOffline: SeemsOffline = () => null): SectionView {
const awake = picture.state === 'awake'
const caseMap = withSpellings(picture.caseMap, here.records.flatMap((record) => record.ids))
- const rows: GridModelRow[] = []
- const offered = new Set<string>()
- const offer = (key: string, node: string): void => {
- if (!key || offered.has(key)) return
- offered.add(key)
- rows.push({ id: caseMap[key] ?? key, node })
- }
+ /** key → the node entries serving it, in the order the picture lists them; `namedBy` → the one whose
+ * name the row shows (the first to list it, or this computer for a model only its records serve). */
+ const serving = new Map<string, PictureNode[]>()
+ const namedBy = new Map<string, string>()
for (const node of picture.nodes) {
if (node.engine === ROUTER_ENGINE) continue
for (const model of node.models) {
- if (!awake && provenStopped(picture, here, node.name, model.key)) continue
- offer(model.key, node.name)
+ if (!model.key || (!awake && provenStopped(picture, here, node.name, model.key))) continue
+ if (!namedBy.has(model.key)) namedBy.set(model.key, node.name)
+ serving.set(model.key, [...serving.get(model.key) ?? [], node])
}
}
+ const servedHere = new Set<string>()
if (!awake) {
for (const record of here.records) {
if (record.pid === null || !record.alive) continue
- for (const id of record.ids) offer(idKey(id), record.name)
+ for (const id of record.ids) {
+ const key = idKey(id)
+ if (!key) continue
+ servedHere.add(key)
+ if (!namedBy.has(key)) namedBy.set(key, record.name)
+ }
}
}
+ const unavailable = (key: string): RowUnavailable | undefined => {
+ // Awake, the grid itself says what answers; served here, this computer is the answer.
+ if (awake || servedHere.has(key)) return undefined
+ const readings = (serving.get(key) ?? []).map((node) => here.own || node.isMine ? seemsOffline(node.name) : null)
+ if (!readings.length || readings.some((reading) => !reading)) return undefined
+ const first = readings[0]!
+ const since = Math.min(...readings.map((reading) => reading!.since))
+ return { reason: 'offline', machine: first.machine, since: new Date(since).toISOString() }
+ }
+ const rows = [...namedBy].map(([key, node]): GridModelRow => {
+ const label = unavailable(key)
+ return { id: caseMap[key] ?? key, node, ...(label ? { unavailable: label } : {}) }
+ })
return {
models: rows,
state: picture.state,
@@ -299,6 +351,7 @@ const MAX_SAVED_NODES = 256
const MAX_SAVED_MODELS_PER_NODE = 256
const MAX_SAVED_TEXT = 256
const MAX_SAVED_SPELLINGS = 4096
+const MAX_SAVED_WINDOWS = 4096
/** A picture read back from disk, or null when it is not one this module wrote. Never trusts the file. */
export function parsePicture(value: unknown): GridPicture | null {
@@ -328,6 +381,13 @@ export function parsePicture(value: unknown): GridPicture | null {
if (typeof exact === 'string' && exact && idKey(exact) === key) caseMap[key] = exact.slice(0, MAX_SAVED_TEXT)
}
}
+ // Absent from a picture written before issue 03: nothing is known, which is what an empty map says.
+ const windows: Record<string, number> = {}
+ if (record.windows && typeof record.windows === 'object' && !Array.isArray(record.windows)) {
+ for (const [key, window] of Object.entries(record.windows as Record<string, unknown>).slice(0, MAX_SAVED_WINDOWS)) {
+ if (key && key === idKey(key) && typeof window === 'number' && Number.isSafeInteger(window) && window > 0) windows[key.slice(0, MAX_SAVED_TEXT)] = window
+ }
+ }
return {
spec: 1,
// Waking is a person's request in flight, and that request died with the process that made it.
@@ -336,5 +396,6 @@ export function parsePicture(value: unknown): GridPicture | null {
listAt: time(record.listAt),
nodes,
caseMap,
+ windows,
}
}
diff --git a/cli/src/lib/gridPresence.ts b/cli/src/lib/gridPresence.ts
new file mode 100644
index 000000000..59382fc5b
--- /dev/null
+++ b/cli/src/lib/gridPresence.ts
@@ -0,0 +1,133 @@
+/**
+ * Which of the account's OTHER computers seem offline — read from the machine list this daemon already
+ * keeps (`GET /api/machines`, refreshed every 60 s), and used for ONE thing: labelling a model that only
+ * such a computer serves on a sleeping grid, so it is not offered as if it would answer.
+ *
+ * ⚠️ A label, never a removal. Presence describes the harness daemon on that computer, not the model
+ * server it runs: a computer whose daemon is down may still be serving (and a computer whose daemon is
+ * up may not be). So every rule below errs toward NOT labelling, and nothing here ever hides a row, and
+ * nothing here ever refuses a move (grid-reads-without-waking issue 03).
+ *
+ * Pure but for the clock the caller passes in.
+ */
+import { sameComputer } from '../device/machineList.js'
+
+/** A computer reads "seems offline" only once two lists at least this far apart both said `offline`,
+ * with nothing else read between them — one list is a blip, not a finding. */
+export const COMPUTER_OFFLINE_MIN_MS = 60_000
+
+/** The list is re-read every 60 s; one that has not been re-read in three of those is not evidence. */
+export const MACHINE_LIST_FRESH_MS = 3 * 60_000
+
+/** One of the account's computers, as the machine list says it. */
+export interface ListedComputer {
+ machineId: string
+ /** Every name a grid node on it could be registered under: its hostname, and its name as the Machines
+ * list shows it (the Model Manager joins a grid under that). */
+ names: string[]
+ /** Its name as the Machines list shows it — what a label says. */
+ display: string
+ /** The backend's word. Only `offline` is offline: `unknown` is a presence the backend could not read. */
+ status: string
+ /** This computer — the one running this daemon, which is by definition not offline. */
+ local: boolean
+}
+
+export interface ComputerList {
+ computers: ListedComputer[]
+ /** The signed-out list — this computer alone, made up locally, which says nothing about any other. */
+ guest: boolean
+}
+
+export interface OfflineReading {
+ /** The computer's name as the Machines list shows it. */
+ machine: string
+ /** When the first of the offline reads was made, epoch ms. */
+ since: number
+}
+
+type Json = Record<string, unknown>
+const isObject = (value: unknown): value is Json => !!value && typeof value === 'object' && !Array.isArray(value)
+const name = (value: unknown): string => typeof value === 'string' ? value.trim() : ''
+
+/** The computers in a `GET /api/machines` body — `{data:{machines}}` as the backend answers, or the older
+ * top-level `{machines}` — or null when the body carries no machine list at all. */
+export function computersIn(body: unknown, localComputerId: string): ComputerList | null {
+ if (!isObject(body)) return null
+ const data = isObject(body.data) ? body.data : body
+ if (!Array.isArray(data.machines)) return null
+ const computers = data.machines.filter(isObject).flatMap((row): ListedComputer[] => {
+ const machineId = name(row.machineId)
+ if (!machineId) return []
+ const hostname = name(row.hostname)
+ const shown = name(row.name)
+ return [{
+ machineId,
+ names: [...new Set([hostname, shown].filter(Boolean))],
+ display: shown || hostname || machineId,
+ status: typeof row.status === 'string' ? row.status : '',
+ local: sameComputer(name(row.computerId), localComputerId),
+ }]
+ })
+ return { computers, guest: data.guest === true }
+}
+
+/** When one computer has been reading offline: the first read of the run, and the latest. */
+interface Streak { since: number; last: number }
+
+export class ComputerPresence {
+ private computers: ListedComputer[] = []
+ private guest = true
+ private listAt: number | null = null
+ private readonly streaks = new Map<string, Streak>()
+
+ /**
+ * Take a list read at `at`. Returns whether any computer's verdict may have changed, so a caller can
+ * re-tell its clients only when there is something to tell.
+ */
+ observe(list: ComputerList, at: number): boolean {
+ const before = this.verdicts(at)
+ this.computers = list.computers
+ this.guest = list.guest
+ this.listAt = at
+ const listed = new Set(list.computers.map((computer) => computer.machineId))
+ for (const id of [...this.streaks.keys()]) if (!listed.has(id)) this.streaks.delete(id)
+ for (const computer of list.computers) {
+ if (computer.status !== 'offline') { this.streaks.delete(computer.machineId); continue }
+ const streak = this.streaks.get(computer.machineId)
+ this.streaks.set(computer.machineId, { since: streak?.since ?? at, last: at })
+ }
+ return this.verdicts(at) !== before
+ }
+
+ /**
+ * The computer a grid node named `nodeName` runs on, when that computer seems offline — else null. All
+ * must hold: the list is fresh and not the guest one; exactly ONE of the account's computers goes by
+ * that name (counting this one, so a name this computer shares is never labelled); it is not this
+ * computer; and it read offline in two lists at least [COMPUTER_OFFLINE_MIN_MS] apart, with nothing else
+ * read between them.
+ */
+ seemsOffline(nodeName: string, now: number): OfflineReading | null {
+ if (!this.fresh(now)) return null
+ const named = this.computers.filter((computer) => computer.names.includes(nodeName))
+ if (named.length !== 1 || named[0]!.local) return null
+ const streak = this.streaks.get(named[0]!.machineId)
+ if (!streak || streak.last - streak.since < COMPUTER_OFFLINE_MIN_MS) return null
+ return { machine: named[0]!.display, since: streak.since }
+ }
+
+ private fresh(now: number): boolean {
+ return !this.guest && this.listAt !== null && now - this.listAt <= MACHINE_LIST_FRESH_MS
+ }
+
+ /** The computers labelled right now, as one comparable value — empty when none is (a stale list
+ * labels nothing, the same as a fresh one in which every computer is up). */
+ private verdicts(now: number): string {
+ if (!this.fresh(now)) return ''
+ return this.computers
+ .filter((computer) => computer.names.some((nodeName) => this.seemsOffline(nodeName, now)))
+ .map((computer) => computer.machineId)
+ .sort()
+ .join('\n')
+ }
+}
diff --git a/cli/src/lib/gridReader.ts b/cli/src/lib/gridReader.ts
index 33772c68a..4fbf2c701 100644
--- a/cli/src/lib/gridReader.ts
+++ b/cli/src/lib/gridReader.ts
@@ -15,13 +15,15 @@
* ⚠️ **Never add a credential to anything in this file.** Not an Authorization header, not x-api-key,
* not a token in the query. The whole resource saving rests on it, and its failure is SILENT: every list
* still looks perfect while every open harness keeps every grid awake again. A person's act that SHOULD
- * wake a grid (a message, Start, an explicit wake) goes out another way, on purpose.
+ * wake a grid (a message, Start, an explicit wake, a prewarm) goes out another way — `gridWake.ts` — on
+ * purpose.
*
* The values below are cross-repo (the lockstep register; `tests/test_grid_reads_lockstep.py` in the
* public `grid` repository finds the two literals by these exact quoted spellings).
*/
import { VERSION } from '../version.js'
import { gridExec, gridJson } from './gridExec.js'
+import { idKey } from './gridPicture.js'
/** The master's two public reads, under a grid's address. ⚠️ Cross-repo literals (grid-src's routes,
* grid-apis' route rules and sleep record, the public CLI's `remote_overview`). */
@@ -82,8 +84,9 @@ export interface LastKnown {
export type GridRead =
/** It answered: these are the live nodes. `rawNodes` is the overview's own node objects, for the Model
- * Manager, which reads telemetry off them; through the CLI fallback, the little `grid models` says. */
- | { kind: 'awake'; nodes: ReadNode[]; curatedIds: string[]; rawNodes: Array<Record<string, unknown>> }
+ * Manager, which reads telemetry off them; through the CLI fallback, the little `grid models` says.
+ * `windows` is each model's context window, keyed without case (empty through the fallback). */
+ | { kind: 'awake'; nodes: ReadNode[]; curatedIds: string[]; rawNodes: Array<Record<string, unknown>>; windows: Record<string, number> }
/** The platform says it is resting. `lastKnown` is its record, when it has a valid one. */
| { kind: 'asleep'; lastKnown: LastKnown | null }
/** Anything else: stopped by its owner, master down, deleted, a codeless 503, garbage, a timeout. */
@@ -200,7 +203,34 @@ export async function readOverview(base: string): Promise<GridRead> {
? body.models.filter(isObject).map((entry) => text(entry.id)).filter(Boolean).slice(0, MAX_IDS)
: []
const rawNodes = body.nodes.filter(isObject).slice(0, MAX_NODES)
- return { kind: 'awake', nodes: readNodes(rawNodes), curatedIds, rawNodes }
+ return { kind: 'awake', nodes: readNodes(rawNodes), curatedIds, rawNodes, windows: readWindows(body.models, rawNodes) }
+}
+
+/** No model's window is this large; a number past it is not one. */
+const MAX_WINDOW = 100_000_000
+
+/**
+ * Each model's context window as the overview reports it — the largest of its curated entry's
+ * `context_length` and every node's `model_capabilities[id].context_length`. The same figure the relay's
+ * signed-in `/models` gives as `context_window` (grid-src `advertised_context_window`, MAX across the
+ * engines serving it), read here without a credential. Keyed without case.
+ */
+function readWindows(curated: unknown, nodes: Array<Record<string, unknown>>): Record<string, number> {
+ const windows: Record<string, number> = {}
+ const take = (id: unknown, value: unknown): void => {
+ const key = idKey(text(id))
+ if (!key || typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0 || value > MAX_WINDOW) return
+ if (Object.keys(windows).length >= MAX_IDS && !(key in windows)) return
+ windows[key] = Math.max(windows[key] ?? 0, value)
+ }
+ if (Array.isArray(curated)) for (const entry of curated.filter(isObject)) take(entry.id, entry.context_length)
+ for (const node of nodes) {
+ const capabilities = isObject(node.model_capabilities) ? node.model_capabilities : {}
+ for (const [id, cell] of Object.entries(capabilities).slice(0, MAX_MODELS_PER_NODE)) {
+ if (isObject(cell)) take(id, cell.context_length)
+ }
+ }
+ return windows
}
/** The master's display rule (grid-src `model_ids.display_model_name`): a trailing `.gguf` removed,
@@ -299,5 +329,5 @@ export async function readViaCli(gridName: string): Promise<GridRead> {
// The Model Manager reads node objects; these carry what `grid models` knows, and a node it lists is
// one the grid is routing to right now.
const rawNodes = nodes.map((node) => ({ name: node.name, engine: node.engine, models: node.models, online: true }))
- return { kind: 'awake', nodes, curatedIds: exact.slice(0, MAX_IDS), rawNodes }
+ return { kind: 'awake', nodes, curatedIds: exact.slice(0, MAX_IDS), rawNodes, windows: {} }
}
diff --git a/cli/src/lib/gridModels.spec.ts b/cli/src/lib/gridTarget.spec.ts
similarity index 53%
rename from cli/src/lib/gridModels.spec.ts
rename to cli/src/lib/gridTarget.spec.ts
index 71e9e9bdd..a2830e2d2 100644
--- a/cli/src/lib/gridModels.spec.ts
+++ b/cli/src/lib/gridTarget.spec.ts
@@ -4,11 +4,16 @@
* subprocess whose ORDER matters — `mcp config` renews the token, `info --env` reads it.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { fakeGridAnswers, installFakeGrid, type FakeGrid, type FakeGridPlan } from './__fixtures__/fakeGrid.js'
import { clearGridMcpUrlCache } from './gridMcpUrl.js'
-import { resolveGridTarget } from './gridModels.js'
+import { listAllGridModels, resetGridModels, type GridModelsService } from './gridModels.js'
+import { resolveGridTarget } from './gridTarget.js'
const { gridName: GRID, networkId, baseUrl: BASE_URL, mcpUrl: MCP_URL, token: TOKEN, plan } = fakeGridAnswers()
+const GRID_URL = `https://grid.autonomous.ai/${networkId}`
let fake: FakeGrid | null = null
function install(overrides: FakeGridPlan = {}): FakeGrid {
@@ -16,22 +21,29 @@ function install(overrides: FakeGridPlan = {}): FakeGrid {
return fake
}
-/** The relay's `/models`, answered here so no test reaches the network. Empty unless a test says. */
-let relayRows: unknown[] = []
-const relayFetch = vi.fn(async (_url: string | URL, _init?: RequestInit) =>
- new Response(JSON.stringify({ data: relayRows }), { status: 200, headers: { 'content-type': 'application/json' } }))
+/** The grid's public overview, answered here so no test reaches the network; anything else is a 404. */
+let overview: unknown = { nodes: [], models: [] }
+const relayFetch = vi.fn(async (url: string | URL, _init?: RequestInit) =>
+ String(url).endsWith('/relay/v1/grid/overview')
+ ? new Response(JSON.stringify(overview), { status: 200, headers: { 'content-type': 'application/json' } })
+ : new Response('{}', { status: 404 }))
+let root: string, service: GridModelsService
beforeEach(() => {
- relayRows = []
+ overview = { nodes: [], models: [] }
relayFetch.mockClear()
vi.stubGlobal('fetch', relayFetch)
+ root = mkdtempSync(join(tmpdir(), 'grid-target-'))
+ service = resetGridModels({ dataDir: () => join(root, 'data'), gridHome: () => join(root, 'grid-home'), email: () => null })
})
-afterEach(() => {
+afterEach(async () => {
+ await service.settled()
fake?.dispose()
fake = null
clearGridMcpUrlCache()
vi.restoreAllMocks()
vi.unstubAllGlobals()
+ rmSync(root, { recursive: true, force: true })
})
describe('resolveGridTarget', () => {
@@ -77,45 +89,55 @@ describe('resolveGridTarget', () => {
// ── the model's context window ─────────────────────────────────────────────────────────────────
//
// A coding agent compacts only inside the window it believes, and it believes nothing true about
- // a grid model — so the target carries the relay's figure for the engine to be told.
+ // a grid model — so the target carries the grid's figure for the engine to be told. It comes from the
+ // picture the model list keeps, read WITHOUT a credential: it used to be a signed-in read of the
+ // relay's `/models` on every move, which woke a sleeping grid and held the click while the grid booted
+ // (grid-reads-without-waking issue 03).
+
+ /** The grid seen once by the model list — the credential-less overview read every picker makes. */
+ async function seen(body: unknown): Promise<void> {
+ install({ [`info ${GRID} --json`]: { stdout: JSON.stringify({ grid: GRID, status: null, grid_url: GRID_URL }) } })
+ overview = body
+ await listAllGridModels(null)
+ await service.settled()
+ }
+ const capable = (id: string, window: unknown) =>
+ ({ name: 'rig', engine: 'llama.cpp', models: [id.toLowerCase()], model_capabilities: { [id.toLowerCase()]: { context_length: window } } })
+
+ it('carries the window the grid last reported for the chosen model, and asks the relay nothing', async () => {
+ await seen({ nodes: [capable('GLM-4.7-Flash', 131072), capable('DeepSeek-V4-Flash-0731', 262144)], models: [{ id: 'GLM-4.7-Flash' }] })
- it("carries the relay's context window for the chosen model", async () => {
- install()
- relayRows = [
- { id: 'DeepSeek-V4-Flash-0731', context_window: 262144 },
- { id: 'GLM-4.7-Flash', context_window: 131072 },
- ]
const target = await resolveGridTarget(GRID, 'GLM-4.7-Flash')
+
expect(target?.contextWindow).toBe(131072)
- // Asked of the relay the launch will talk to, with the credential it will use.
- expect(String(relayFetch.mock.calls[0]![0])).toBe(`${BASE_URL.replace(/\/$/, '')}/models`)
+ // Only the model list's own credential-less reads went out — no signed-in `/models`.
+ expect(relayFetch.mock.calls.some(([url]) => String(url).endsWith('/relay/v1/models'))).toBe(false)
+ for (const [, init] of relayFetch.mock.calls) expect(new Headers(init?.headers).has('authorization')).toBe(false)
})
- it('matches the id without regard to case only when no exact row exists', async () => {
- install()
- relayRows = [{ id: 'glm-4.7-flash', context_window: 65536 }]
- expect((await resolveGridTarget(GRID, 'GLM-4.7-Flash'))?.contextWindow).toBe(65536)
+ it('takes the largest figure among the curated entry and the nodes serving it, whatever its case', async () => {
+ await seen({ nodes: [capable('glm-4.7-flash', 65536)], models: [{ id: 'GLM-4.7-Flash', context_length: 131072 }] })
+ expect((await resolveGridTarget(GRID, 'glm-4.7-FLASH'))?.contextWindow).toBe(131072)
})
it.each([
- ['the relay lists no window', [{ id: 'GLM-4.7-Flash' }]],
- ['the window is not a number', [{ id: 'GLM-4.7-Flash', context_window: '131072' }]],
- ['the window is implausibly small', [{ id: 'GLM-4.7-Flash', context_window: 512 }]],
- ['the model is not listed', [{ id: 'Other', context_window: 131072 }]],
- ])('resolves without a window when %s', async (_case, rows) => {
- install()
- relayRows = rows
+ ['the grid reports no window', { nodes: [{ name: 'rig', engine: 'llama.cpp', models: ['glm-4.7-flash'] }], models: [] }],
+ ['the window is not a number', { nodes: [capable('GLM-4.7-Flash', '131072')], models: [] }],
+ ['the window is implausibly small', { nodes: [capable('GLM-4.7-Flash', 512)], models: [] }],
+ ['the model is not listed', { nodes: [capable('Other', 131072)], models: [] }],
+ ])('resolves without a window when %s', async (_case, body) => {
+ await seen(body)
const target = await resolveGridTarget(GRID, 'GLM-4.7-Flash')
expect(target).toMatchObject({ baseUrl: BASE_URL, model: 'GLM-4.7-Flash' })
expect(target).not.toHaveProperty('contextWindow')
})
- it('resolves without a window when the relay cannot be asked', async () => {
+ it('resolves without a window when the grid has never been seen', async () => {
install()
- relayFetch.mockRejectedValueOnce(new Error('offline'))
const target = await resolveGridTarget(GRID, 'GLM-4.7-Flash')
expect(target).toMatchObject({ apiKey: TOKEN, model: 'GLM-4.7-Flash' })
expect(target).not.toHaveProperty('contextWindow')
+ expect(relayFetch).not.toHaveBeenCalled()
})
it('asks nothing of `grid` without a grid name or a model', async () => {
diff --git a/cli/src/lib/gridTarget.ts b/cli/src/lib/gridTarget.ts
new file mode 100644
index 000000000..8ccd9777a
--- /dev/null
+++ b/cli/src/lib/gridTarget.ts
@@ -0,0 +1,75 @@
+/**
+ * Where an engine is pointed when a person moves an agent onto a grid model, or starts one there — the
+ * relay, the credential, the web tools and the model's context window, all resolved on THIS machine.
+ *
+ * Its own module since grid-reads-without-waking issue 03: the model list (`gridModels.ts`) answers what
+ * grids serve; this answers how one agent reaches one of them. The window comes from the model list's
+ * credential-less picture, so resolving a target never reads a grid with its credential — waking one is
+ * the prewarm's job, after the move (`gridModels.ts`, `gridWake.ts`).
+ */
+import { gridJson } from './gridExec.js'
+import { contextWindowHint } from './gridLaunch.js'
+import { resolveGridMcpUrl } from './gridMcpUrl.js'
+import { gridContextWindow } from './gridModels.js'
+import { relayAccess } from './gridWake.js'
+
+/** What `resolveGridTarget` answers: the launch override an engine is built from. */
+export interface GridTarget {
+ networkId: string
+ networkName: string
+ baseUrl: string
+ /** A live credential — see the function comment. */
+ apiKey: string
+ model: string
+ /** The control plane's web-tools MCP endpoint. Absent when it could not be obtained; the agent
+ * then runs on the grid with no web tools, and the daemon log says why. */
+ mcpUrl?: string
+ /** The model's context window as the grid last reported it, so the engine can be told to compact
+ * inside it (`GridLaunchOverride.contextWindow`). Absent when it has not been seen. */
+ contextWindow?: number
+}
+
+/**
+ * Everything an engine needs to be pointed at `gridName`, resolved on THIS machine.
+ *
+ * Deliberately not something a client sends. The app names a model; the endpoint and the credential
+ * are read here, from the `grid` CLI that is already signed in, so no grid credential ever crosses
+ * the relay and there is one source of truth for an address the app could not know anyway.
+ *
+ * ⚠️ The returned `apiKey` is a live credential. It goes into the engine's ENVIRONMENT and never into
+ * argv or a log line — `gridLaunch.ts` is what enforces that, and this value must keep travelling
+ * through it rather than around it.
+ *
+ * Web tools ride on the same credential: the control plane's MCP server accepts the inference token,
+ * so `mcpUrl` is the only thing added here, and it is added FIRST. `grid mcp config` renews the token
+ * when it is within a month of expiry and persists the renewal; `info --env` never renews, so asked
+ * in the other order it could hand inference an older token than the one the web tools hold — both
+ * valid, and a mismatch nobody would think to look for. A missing `mcpUrl` degrades rather than
+ * refuses: inference is the feature, web search is an accessory (`gridMcpUrl.ts`).
+ */
+export async function resolveGridTarget(gridName: string | null, model: string): Promise<GridTarget | null> {
+ if (!gridName?.trim() || !model.trim()) return null
+ const mcpUrl = await resolveGridMcpUrl(gridName)
+ const access = await relayAccess(gridName)
+ if (!access) return null
+ const { baseUrl, apiKey } = access
+ // The grid's own id, for the record the launch is written into. Falls back to the name, which is
+ // unique on this account and is all the launch actually needs to be re-derivable.
+ const { value: rows } = await gridJson<Array<{ grid?: unknown; id?: unknown }>>(['--remote', 'ls'])
+ const row = Array.isArray(rows) ? rows.find((r) => r.grid === gridName) : undefined
+ const networkId = typeof row?.id === 'string' && row.id.trim() ? row.id.trim() : null
+ // The window from the picture — read WITHOUT a credential. It was a signed-in read of the relay's
+ // `/models` on every move, which woke a sleeping grid, held the click for as long as the proxy held
+ // the request, and could not be skipped when nobody could answer; waking is the prewarm's job now,
+ // and it goes out after the move, detached (issue 03).
+ const contextWindow = networkId ? contextWindowHint(await gridContextWindow({ networkId, gridName }, model)) : undefined
+ return {
+ networkId: networkId ?? gridName,
+ networkName: gridName,
+ baseUrl,
+ apiKey,
+ model,
+ ...(mcpUrl ? { mcpUrl } : {}),
+ ...(contextWindow ? { contextWindow } : {}),
+ }
+}
diff --git a/cli/src/lib/gridWake.ts b/cli/src/lib/gridWake.ts
new file mode 100644
index 000000000..321d2bb99
--- /dev/null
+++ b/cli/src/lib/gridWake.ts
@@ -0,0 +1,123 @@
+/**
+ * The reads a PERSON'S act makes — the one place in this daemon that reads a grid WITH the account's grid
+ * credential, and does it on purpose: on the platform a signed-in read of a sleeping grid starts it.
+ *
+ * Every other read of a grid goes through `gridReader.ts`, which never carries a credential, so a grid is
+ * never woken by being looked at (grid-reads-without-waking issue 02). What may wake one (issue 03):
+ *
+ * - an explicit wake — "Show models" in a picker, "Wake now" in the Model Manager viewer — `(wake)`;
+ * - moving an agent onto a model on a grid that is asleep or has not been seen awake lately — `(prewarm)`;
+ * - the first input into a terminal whose agent runs on a grid that is asleep — `(prewarm-key)`;
+ *
+ * (and, outside this daemon's reads altogether, a message the agent sends and the Model Manager's Start).
+ * Each one is ONE request, detached from whatever the person is waiting on, and marked in its User-Agent
+ * so the platform's journal attributes the wake it causes. No automatic seed or discovery wake, ever.
+ */
+import { gridExec } from './gridExec.js'
+import { idKey } from './gridPicture.js'
+import { harnessUserAgent, readBase, type ReadPurpose } from './gridReader.js'
+
+/** Why a credentialed read is being made. */
+export type WakePurpose = Exclude<ReadPurpose, 'read'>
+
+/** A prewarm (of either kind) fires at most once per grid in this long: a boot it paid for is still up. */
+export const PREWARM_DEBOUNCE_MS = 10 * 60_000
+
+/** The proxy holds a request to a sleeping grid while its master boots — up to 60 s (grid-apis
+ * `_WAKE_WAIT_TIMEOUT_SECONDS`) — and replays it once the master is up. Nobody waits on this read. */
+const WAKE_READ_TIMEOUT_MS = 90_000
+
+/** More models than any grid lists, and a window no model has: an answer past either is cut. */
+const MAX_LISTED = 1024
+const MAX_WINDOW = 100_000_000
+
+/** The relay a grid's engines talk to, and the credential they use — `grid info <grid> --env`. */
+export interface RelayAccess {
+ /** `<grid>/relay/v1` */
+ baseUrl: string
+ /** ⚠️ A live credential. Never logged, never in argv. */
+ apiKey: string
+}
+
+/** `grid info --env` prints shell exports; these are the two that matter. */
+const ENV_LINE = /^export\s+(OPENAI_BASE_URL|OPENAI_API_KEY)=(.*)$/gm
+
+/** The two exports out of `grid info --env`. ⚠️ Values are SHELL-QUOTED — a base URL read with the
+ * quotes still on produces a request to a host that does not exist. */
+export function readEnvExports(stdout: string): { baseUrl: string; apiKey: string } {
+ let baseUrl = ''
+ let apiKey = ''
+ for (const match of stdout.matchAll(ENV_LINE)) {
+ const value = match[2]!.trim().replace(/^["']|["']$/g, '')
+ if (match[1] === 'OPENAI_BASE_URL') baseUrl = value
+ else apiKey = value
+ }
+ return { baseUrl, apiKey }
+}
+
+/** The relay and credential for `gridName`, from this computer's signed-in `grid`; null when it has none. */
+export async function relayAccess(gridName: string): Promise<RelayAccess | null> {
+ const info = await gridExec(['--remote', 'info', gridName, '--env'])
+ if (info.code !== 'OK') return null
+ const { baseUrl, apiKey } = readEnvExports(info.stdout)
+ return baseUrl && apiKey ? { baseUrl, apiKey } : null
+}
+
+/**
+ * One credentialed read of the grid's model list, marked `purpose`. Answers each listed model's context
+ * window (keyed without case) when it answered 2xx — what the relay reports as `context_window`, which a
+ * launch tells its engine to compact inside — and null when it did not. Never throws: a wake that did not
+ * happen costs the person the boot on their next message, nothing more.
+ *
+ * The credential goes only to an `https` relay, or plain `http` on this computer (a developer's grid):
+ * a bearer sent in the clear to anywhere else would be a leak, and a LAN grid never sleeps anyway.
+ */
+export async function wakeRead(gridName: string, purpose: WakePurpose, known?: RelayAccess): Promise<Record<string, number> | null> {
+ try {
+ const access = known ?? await relayAccess(gridName)
+ const base = access ? readBase(access.baseUrl) : null
+ if (!access || !base) return null
+ const response = await fetch(`${base}/models`, {
+ method: 'GET',
+ headers: { authorization: `Bearer ${access.apiKey}`, 'user-agent': harnessUserAgent(purpose), accept: 'application/json' },
+ redirect: 'manual',
+ signal: AbortSignal.timeout(WAKE_READ_TIMEOUT_MS),
+ })
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => {})
+ return null
+ }
+ return listedWindows(await response.json().catch(() => null))
+ } catch {
+ return null
+ }
+}
+
+/** `{data: [{id, context_window}]}` → each window, keyed without case; anything else in it is ignored. */
+function listedWindows(body: unknown): Record<string, number> {
+ const rows = body && typeof body === 'object' && Array.isArray((body as { data?: unknown }).data) ? (body as { data: unknown[] }).data : []
+ const windows: Record<string, number> = {}
+ for (const row of rows.slice(0, MAX_LISTED)) {
+ const { id, context_window: window } = (row && typeof row === 'object' ? row : {}) as { id?: unknown; context_window?: unknown }
+ if (typeof id !== 'string' || !idKey(id)) continue
+ if (typeof window !== 'number' || !Number.isSafeInteger(window) || window <= 0 || window > MAX_WINDOW) continue
+ windows[idKey(id)] = window
+ }
+ return windows
+}
+
+/** When each grid was last woken by any act here, so a prewarm right after one is not sent again. */
+export class PrewarmDebounce {
+ private readonly firedAt = new Map<string, number>()
+
+ /** Whether a prewarm of `gridId` may go out at `now`. Asking records nothing. */
+ allows(gridId: string, now: number): boolean {
+ const last = this.firedAt.get(gridId)
+ return last === undefined || now - last >= PREWARM_DEBOUNCE_MS
+ }
+
+ /** A credentialed read of `gridId` went out at `now` — a prewarm, or an explicit wake. */
+ mark(gridId: string, now: number): void {
+ this.firedAt.set(gridId, now)
+ }
+}
diff --git a/cli/src/lib/gridWebSearchFrame.spec.ts b/cli/src/lib/gridWebSearchFrame.spec.ts
index fc15363fb..c469746b6 100644
--- a/cli/src/lib/gridWebSearchFrame.spec.ts
+++ b/cli/src/lib/gridWebSearchFrame.spec.ts
@@ -17,7 +17,7 @@ import { fakeGridAnswers, installFakeGrid, type FakeGrid, type FakeGridPlan } fr
import { agentFrame } from './agentFrame.js'
import { buildLaunchOverrides, type LaunchOverridesDeps } from './launchOverrides.js'
import { clearGridMcpUrlCache } from './gridMcpUrl.js'
-import { resolveGridTarget } from './gridModels.js'
+import { resolveGridTarget } from './gridTarget.js'
const { gridName: GRID, baseUrl: BASE_URL, mcpUrl: MCP_URL, plan } = fakeGridAnswers()
diff --git a/cli/src/lib/localModels.spec.ts b/cli/src/lib/localModels.spec.ts
index 82536de11..9b820ec07 100644
--- a/cli/src/lib/localModels.spec.ts
+++ b/cli/src/lib/localModels.spec.ts
@@ -134,6 +134,34 @@ describe('local model discovery and lifecycle', () => {
expect(await readFile(join(stateDir, (await readdir(stateDir))[0]), 'utf8')).not.toContain('token')
})
+ // grid-reads-without-waking issue 03: the reply test is an inference THROUGH the grid, so on a sleeping
+ // grid it starts it — and the platform then keeps it up for hours. A stray Start on a model that is
+ // already serving has nothing to check.
+ it('Start on a model already serving at the last read skips the reply test', async () => {
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ expect((await service.list('home', true)).models[0].state).toBe('running')
+ request.mockClear(); calls.length = 0
+
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+
+ // Nothing that reads through the grid with its credential: no reply test, no `info --env` for its
+ // key, no signed-in `engines` for the served window — and nothing started.
+ expect(request.mock.calls.some(([url]) => String(url).includes(RELAY_CHAT))).toBe(false)
+ expect(calls.filter(args => args.includes('--env') || args.includes('engines') || args.includes('join'))).toEqual([])
+ expect((await service.list('home')).models[0]).toMatchObject({ state: 'running', operation: { phase: 'done' } })
+ })
+
+ it('Start on a model this computer holds but that was not serving at the last read runs the reply test, as before', async () => {
+ await writeFile(join(home, 'models', 'Small-Q4.gguf'), Buffer.alloc(64))
+ await writeFile(join(records, 'remote.json'), JSON.stringify({ node_id: 'local-node', engines: [{ endpoint_url: null, models: ['Small-Q4.gguf'] }], advertise_as: [] }))
+ expect((await service.list('home', true)).models[0].state).not.toBe('running')
+
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+
+ expect(request.mock.calls.some(([url]) => String(url).includes(RELAY_CHAT))).toBe(true)
+ expect(calls.some(args => args.includes('join'))).toBe(false)
+ })
+
it('uses an already downloaded complete file, and Stop retains it', async () => {
await writeFile(join(home, 'models', 'Small-Q4.gguf'), Buffer.alloc(64))
expect((await service.list('home')).models[0].state).toBe('downloaded')
diff --git a/cli/src/lib/localModels.ts b/cli/src/lib/localModels.ts
index 78f6ffab2..1f9f0bd2e 100644
--- a/cli/src/lib/localModels.ts
+++ b/cli/src/lib/localModels.ts
@@ -10,6 +10,7 @@ import { binaryOnPath } from './binaryOnPath.js'
import { processExists } from './processLiveness.js'
import type { LocalRecord, PictureState } from './gridPicture.js'
import { displayModelName } from './gridReader.js'
+import { readEnvExports } from './gridWake.js'
const GiB = 1024 ** 3
const obj = (v: unknown): Record<string, any> => v && typeof v === 'object' && !Array.isArray(v) ? v : {}
@@ -153,6 +154,8 @@ export class LocalModels {
private listPending?: Promise<LocalModelsSnapshot>
private listGrid?: string
private cached?: { at: number; grid: string; value: LocalModelsSnapshot }
+ /** The models the last read of each grid found running — kept past `cached`, which any save clears. */
+ private readonly runningAtLastRead = new Map<string, Set<string>>()
private active?: { grid: string; operation: ModelOperation; done: Promise<void> }
private receipt?: Receipt
private receiptScope?: string
@@ -483,6 +486,7 @@ export class LocalModels {
hardware: str(obj(this.device.machine).model || obj(this.device.cpu).brand), notice: inventoryError || this.catalogError,
observedAt: new Date().toISOString(), busy: !!this.active }
this.cached = { grid, at: Date.now(), value }
+ this.runningAtLastRead.set(grid, new Set(models.filter(model => model.state === 'running').map(model => model.id)))
return value
}
@@ -614,6 +618,13 @@ export class LocalModels {
? `This computer does not have the memory to run ${candidate.name} with a 64K context. Close some apps, or choose a smaller model.`
: 'The model could not start. Try again.')
}
+ } else if (this.runningAtLastRead.get(grid)?.has(operation.modelId)) {
+ // Already serving when last read, and nothing was started: nothing to check. The reply test is an
+ // inference THROUGH the grid (so is the served-window read) — on a sleeping grid it would start it,
+ // and the platform then holds it up for hours, for a stray click (grid-reads-without-waking 03).
+ operation.phase = 'done'
+ await this.save(grid, operation)
+ return
}
await change('verifying')
const model = instance?.aliases[0] || candidate.aliases?.[0] || candidate.file
@@ -634,14 +645,13 @@ export class LocalModels {
private async verify(grid: string, model: string): Promise<void> {
const info = await this.run(['--remote', 'info', grid, '--env'])
- const exports: Record<string, string> = {}
- for (const match of info.stdout.matchAll(/^export\s+(OPENAI_BASE_URL|OPENAI_API_KEY)=(.*)$/gm)) exports[match[1]] = match[2].trim().replace(/^["']|["']$/g, '')
- if (!info.ok || !exports.OPENAI_BASE_URL || !exports.OPENAI_API_KEY) throw new ModelError('The model is starting, but could not be checked. Try again shortly.')
+ const { baseUrl, apiKey } = readEnvExports(info.stdout)
+ if (!info.ok || !baseUrl || !apiKey) throw new ModelError('The model is starting, but could not be checked. Try again shortly.')
const deadline = Date.now() + 180_000
do {
try {
- const response = await this.request(`${exports.OPENAI_BASE_URL.replace(/\/$/, '')}/chat/completions`, {
- method: 'POST', headers: { authorization: `Bearer ${exports.OPENAI_API_KEY}`, 'content-type': 'application/json' },
+ const response = await this.request(`${baseUrl.replace(/\/$/, '')}/chat/completions`, {
+ method: 'POST', headers: { authorization: `Bearer ${apiKey}`, 'content-type': 'application/json' },
body: JSON.stringify({ model, messages: [{ role: 'user', content: 'Reply with the single word: ok' }], max_tokens: 8 }),
signal: AbortSignal.timeout(30_000), redirect: 'error',
})
diff --git a/cli/src/lib/newAgentModel.spec.ts b/cli/src/lib/newAgentModel.spec.ts
index 3fa65485c..36e174232 100644
--- a/cli/src/lib/newAgentModel.spec.ts
+++ b/cli/src/lib/newAgentModel.spec.ts
@@ -1,10 +1,12 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { ENGINES } from '../engines/types.js'
import { gridCapableEngines } from './gridLaunch.js'
-import { forgetGridModels, listGridModels, resolveGridTarget } from './gridModels.js'
+import { forgetGridModels, listGridModels } from './gridModels.js'
+import { resolveGridTarget } from './gridTarget.js'
import { parseNewAgentModel, resolveNewAgentModel } from './newAgentModel.js'
-vi.mock('./gridModels.js', () => ({ forgetGridModels: vi.fn(), listGridModels: vi.fn(), resolveGridTarget: vi.fn() }))
+vi.mock('./gridModels.js', () => ({ forgetGridModels: vi.fn(), listGridModels: vi.fn() }))
+vi.mock('./gridTarget.js', () => ({ resolveGridTarget: vi.fn() }))
const choice = { gridModel: 'Qwen-35B', gridName: 'my-grid' }
const target = { networkId: 'g', networkName: 'my-grid', baseUrl: 'https://fixture.invalid/relay/v1', apiKey: 'fixture-key', model: 'Qwen-35B' }
beforeEach(() => vi.resetAllMocks())
diff --git a/cli/src/lib/newAgentModel.ts b/cli/src/lib/newAgentModel.ts
index 6e2e14007..77c998922 100644
--- a/cli/src/lib/newAgentModel.ts
+++ b/cli/src/lib/newAgentModel.ts
@@ -1,6 +1,7 @@
import type { AgentEngine } from '../engines/types.js'
import { gridCapableEngines, type GridLaunchOverride } from './gridLaunch.js'
-import { forgetGridModels, listGridModels, resolveGridTarget } from './gridModels.js'
+import { forgetGridModels, listGridModels } from './gridModels.js'
+import { resolveGridTarget } from './gridTarget.js'
export interface NewAgentModel { model: string; grid: string }
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.ts
index 4608ac2b1..618ee7958 100644
--- a/cli/src/lib/terminalStreamManager.spec.ts
+++ b/cli/src/lib/terminalStreamManager.spec.ts
@@ -153,6 +153,34 @@ describe('TerminalStreamManager', () => {
expect(sent.at(-1)?.payload.code).toBe('TERMINAL_AGENT_NOT_FOUND')
})
+ it('tells the daemon an agent took input from its controller — never from a watcher, never for input it refused', async () => {
+ // The keystroke prewarm (grid-reads-without-waking issue 03) hangs off this: typing into a pane whose
+ // agent runs on a sleeping grid starts that grid. A read-only watcher's input reaches no pty, so it
+ // must start nothing either.
+ const typed: string[] = []
+ await manager.stop()
+ manager = newManager({ onInput: (agentId) => { typed.push(agentId) } })
+ await manager.handleFrame('web-1', 'terminal_open', { requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40 })
+ const controller = sent.find((frame) => frame.type === 'terminal_ready' && frame.connId === 'web-1')!.payload.streamId as string
+ await manager.handleFrame('web-2', 'terminal_open', {
+ requestId: 'open-2', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40, takeover: false,
+ })
+ const watcher = sent.find((frame) => frame.type === 'terminal_ready' && frame.connId === 'web-2')!
+ expect(watcher.payload.readOnly).toBe(true)
+
+ await manager.handleBinary('web-2', {
+ kind: TerminalBinaryKind.input, streamId: watcher.payload.streamId as string, seq: 0, compressed: false, bytes: Buffer.from('x'),
+ })
+ await manager.handleBinary('web-1', {
+ kind: TerminalBinaryKind.input, streamId: controller, seq: 5, compressed: false, bytes: Buffer.from('out of order'),
+ })
+ expect(typed).toEqual([])
+
+ await manager.handleBinary('web-1', { kind: TerminalBinaryKind.input, streamId: controller, seq: 0, compressed: false, bytes: Buffer.from('x') })
+ await manager.handleBinary('web-1', { kind: TerminalBinaryKind.paste, streamId: controller, seq: 0, compressed: false, bytes: Buffer.from('hello') })
+ expect(typed).toEqual(['agent-1', 'agent-1'])
+ })
+
it('opens with a keyframe, streams coalesced output, and writes ordered raw input', async () => {
await manager.handleFrame('web-1', 'terminal_open', {
requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40, compression: ['zlib'],
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index 99d26cd66..fb7bc66fa 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -163,6 +163,13 @@ export interface TerminalStreamManagerDeps {
streamingAvailable: boolean
now?: () => number
diagnostic?: (event: string, fields: Record<string, unknown>) => void
+ /**
+ * An agent's terminal just took input (a keystroke or a paste) from the stream that holds it — never
+ * from a watcher, whose input is refused before it gets here. Called on every accepted frame, so it
+ * must be cheap and must not throw; the daemon starts a sleeping grid from it (the keystroke prewarm,
+ * grid-reads-without-waking issue 03), which is why it lives here, below every client that types.
+ */
+ onInput?: (agentId: string) => void
}
function sizeFrom(payload: FramePayload): TerminalStreamSize | null {
@@ -619,6 +626,7 @@ export class TerminalStreamManager {
}
state.lastInputSeq = inputSeq
state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS
+ this.tookInput(state)
// Not awaited. `writeRaw` hands its `send-keys` to the control client's FIFO synchronously, so
// keystroke order is already fixed by the time it returns its promise — and the seq above is
// spent, so the next frame cannot race this one. Awaiting the reply held the whole local
@@ -645,6 +653,13 @@ export class TerminalStreamManager {
})
}
+ /** See `TerminalStreamManagerDeps.onInput`. A listener's failure is its own: input is never held by it. */
+ private tookInput(state: ActiveStream): void {
+ try { this.deps.onInput?.(state.agentId) } catch (error) {
+ this.diagnostic(state, 'input_listener_failed', { reason: error instanceof Error ? error.message : String(error) })
+ }
+ }
+
private async resize(connId: string, payload: FramePayload): Promise<void> {
const state = this.streamFor(connId, payload)
if (!state) return
@@ -685,6 +700,7 @@ export class TerminalStreamManager {
return
}
state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS
+ this.tookInput(state)
const result = await state.handle.pasteRaw(text)
if (result.state !== 'succeeded') {
this.sendError(state.connId, 'TERMINAL_PASTE_FAILED', { streamId: state.streamId, message: result.reason })
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index ab7d405ed..c73ecaa80 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -296,6 +296,14 @@ class Agent {
/// the daemon when it built the launch and carried on every frame, so it is right after a
/// reconnect or a restart without anything being replayed.
final GridWebSearch? gridWebSearch;
+
+ /// How the daemon's picture has the grid this agent's model is on (`grid.state`), or null when
+ /// it did not say — an agent on its own login, or an older daemon. Asleep or waking is what puts
+ /// the "Starting up…" chip on its pane between a message and the first answer.
+ final GridSectionState? gridState;
+
+ /// Why the agent's model will not answer right now (`grid.note`), or null when nothing is wrong.
+ final GridNote? gridNote;
final String? parentAgentId;
final AgentProject? project;
@@ -381,6 +389,8 @@ class Agent {
this.codexHome,
this.gridModel,
this.gridWebSearch,
+ this.gridState,
+ this.gridNote,
this.parentAgentId,
this.project,
this.lastActivityAt,
@@ -505,6 +515,8 @@ class Agent {
codexHome: j['engine'] == 'codex' ? _safeCodexHome(j['codexHome']) : null,
gridModel: _safeLabel(grid?['model']),
gridWebSearch: GridWebSearch.fromWire(grid?['webSearch']),
+ gridState: GridSectionState.parse(grid?['state']),
+ gridNote: GridNote.fromWire(grid?['note']),
parentAgentId: _safeLabel(j['parentAgentId'] ?? j['parentId']),
project: AgentProject.fromJson(j['project']),
lastActivityAt: j['updatedAt'] is String
@@ -556,6 +568,8 @@ class Agent {
codexHome: codexHome,
gridModel: gridModel,
gridWebSearch: gridWebSearch,
+ gridState: gridState,
+ gridNote: gridNote,
parentAgentId: parentAgentId,
project: project,
lastActivityAt: lastActivityAt,
@@ -1026,7 +1040,104 @@ class GridModel {
/// sends only the own grid's list, which the retarget then targets as it always did.
final String? grid;
- const GridModel({required this.id, required this.node, this.grid});
+ /// Set when every computer serving this row seems offline — see [GridModelUnavailable]. Null
+ /// for every other row, and always from a daemon that predates it.
+ final GridModelUnavailable? unavailable;
+
+ const GridModel({
+ required this.id,
+ required this.node,
+ this.grid,
+ this.unavailable,
+ });
+}
+
+/// Why a listed model will not answer, as the daemon labels a row (`unavailable`, sent only to a
+/// client that asked with `rowState: true`).
+///
+/// Only `offline` is a reason this build knows: every computer serving the row read offline twice,
+/// a minute apart. The row is labelled, never removed — the daemon may be wrong about a computer
+/// that is merely asleep, and a move onto it is the person's call. A reason this build has not
+/// heard of is no claim at all, the rule [GridSectionState] follows.
+class GridModelUnavailable {
+ /// The computer's name as the Machines list shows it.
+ final String machine;
+
+ /// When it was first read offline, or null when the daemon did not say.
+ final DateTime? since;
+
+ const GridModelUnavailable({required this.machine, this.since});
+
+ static GridModelUnavailable? fromWire(Object? raw) {
+ if (raw is! Map || raw['reason'] != 'offline') return null;
+ final machine = Agent._safeLabel(raw['machine']);
+ if (machine == null) return null;
+ final since = raw['since'];
+ return GridModelUnavailable(
+ machine: machine,
+ since: since is String ? DateTime.tryParse(since) : null,
+ );
+ }
+}
+
+/// What came of the last explicit wake of a section that did not end in models (`wakeOutcome`).
+///
+/// A wake that shows models leaves nothing — the section is simply awake with them. The daemon
+/// keeps an outcome until a later read finds the section awake with a model, or ten minutes pass.
+enum GridWakeOutcome {
+ /// The section could not be started; it will start on the next message.
+ notStarted,
+
+ /// It started, and nobody is serving a model on it.
+ nobodyServing;
+
+ static GridWakeOutcome? parse(Object? raw) => switch (raw) {
+ 'not_started' => GridWakeOutcome.notStarted,
+ 'nobody_serving' => GridWakeOutcome.nobodyServing,
+ _ => null,
+ };
+}
+
+/// Why an agent's model will not answer right now, as the daemon notes it on the agent's frame
+/// (`grid.note`): [GridNoteOffline] or [GridNoteNotServed].
+///
+/// Absent when there is nothing to say; the daemon re-pushes the agent when it clears, and never
+/// notes an agent on Auto (no model).
+sealed class GridNote {
+ /// The model the agent is on, as the daemon named it in the note.
+ final String model;
+
+ const GridNote(this.model);
+
+ /// Read defensively: a reason this build does not know, or a note missing the names its
+ /// sentence needs, is no note at all.
+ static GridNote? fromWire(Object? raw) {
+ if (raw is! Map) return null;
+ final model = Agent._safeLabel(raw['model']);
+ if (model == null) return null;
+ final machine = Agent._safeLabel(raw['machine']);
+ return switch (raw['reason']) {
+ 'not_served' => GridNoteNotServed(model),
+ 'offline' when machine != null => GridNoteOffline(
+ model,
+ machine: machine,
+ ),
+ _ => null,
+ };
+ }
+}
+
+/// Every computer serving the agent's model seems offline.
+final class GridNoteOffline extends GridNote {
+ /// The computer, as the Machines list names it.
+ final String machine;
+
+ const GridNoteOffline(super.model, {required this.machine});
+}
+
+/// The latest list (an awake read, or the sleep record) no longer has the agent's model.
+final class GridNoteNotServed extends GridNote {
+ const GridNoteNotServed(super.model);
}
/// Which `grid` a machine would run, as its daemon reports beside the model list (`gridCli`).
@@ -1068,6 +1179,10 @@ enum GridSectionState {
'unknown' => GridSectionState.unknown,
_ => null,
};
+
+ /// Asleep, or on its way up: a message sent now waits for it to start.
+ bool get resting =>
+ this == GridSectionState.asleep || this == GridSectionState.waking;
}
/// The picker's whole answer: which grid was asked, and what it offers.
@@ -1080,7 +1195,7 @@ class GridSection {
final List<GridModel> models;
/// How the grid answered the daemon's last look — see [GridSectionState]. Null from an older
- /// daemon, and nothing here draws it yet.
+ /// daemon, which draws the section as it always was.
final GridSectionState? state;
/// When the grid was last seen awake, or null.
@@ -1089,6 +1204,10 @@ class GridSection {
/// How old [models] is, in seconds, or null when nothing is known.
final int? lastKnownAge;
+ /// What came of the last explicit wake that showed no models — see [GridWakeOutcome]. Null
+ /// otherwise, and always from a daemon that predates it.
+ final GridWakeOutcome? wakeOutcome;
+
const GridSection({
required this.name,
required this.own,
@@ -1096,6 +1215,7 @@ class GridSection {
this.state,
this.seenAt,
this.lastKnownAge,
+ this.wakeOutcome,
});
}
@@ -1152,6 +1272,7 @@ class GridModels {
id: m['id'] is String ? m['id'] as String : '',
node: m['node'] is String ? m['node'] as String : '',
grid: grid,
+ unavailable: GridModelUnavailable.fromWire(m['unavailable']),
),
)
.where((m) => m.id.isNotEmpty)
@@ -1173,6 +1294,7 @@ class GridModels {
lastKnownAge: known is num && known.isFinite && known >= 0
? known.round()
: null,
+ wakeOutcome: GridWakeOutcome.parse(g['wakeOutcome']),
);
})
.toList();
diff --git a/desktop/lib/models/local_model.dart b/desktop/lib/models/local_model.dart
index 68f42b2fb..d5e02a35a 100644
--- a/desktop/lib/models/local_model.dart
+++ b/desktop/lib/models/local_model.dart
@@ -14,13 +14,22 @@ class LocalModel {
this.requests,
this.windowSeconds,
this.operation,
+ this.gridAsleep = false,
});
final String id, name, state;
final String? quant;
final double? sizeBytes, tokensPerSecond, requests, windowSeconds;
final bool recommended, canStart, canStop;
final LocalModelOperation? operation;
+
+ /// Running here, parked while the account's own grid sleeps (`gridAsleep`). It answers again by
+ /// itself on the next message, so the row says so rather than reading as a plain `running`. An
+ /// older daemon never sends it.
+ final bool gridAsleep;
bool get running => state == 'running';
+
+ /// Running, and resting until somebody sends a message — see [gridAsleep].
+ bool get resting => running && gridAsleep;
bool get downloaded => state == 'downloaded' || running;
factory LocalModel.fromJson(Map<String, dynamic> data) => LocalModel(
@@ -36,6 +45,7 @@ class LocalModel {
requests: _number(data['requests']),
windowSeconds: _number(data['windowSeconds']),
operation: LocalModelOperation.parse(data['operation']),
+ gridAsleep: data['gridAsleep'] == true,
);
}
diff --git a/desktop/lib/models/model_manager_controller.dart b/desktop/lib/models/model_manager_controller.dart
index 6d77ad8dc..fe46a0e92 100644
--- a/desktop/lib/models/model_manager_controller.dart
+++ b/desktop/lib/models/model_manager_controller.dart
@@ -422,6 +422,23 @@ class ModelManagerController extends ChangeNotifier {
}
}
+ /// "Show models" on a resting shared section: ask this computer's daemon to wake [sectionName]
+ /// (see [AppNotifier.wakeGridModels]) and show its answer — the section starting up — at once.
+ /// What follows lands through the app's picture, as every other change does.
+ Future<void> wake(String sectionName) async {
+ final owner = machine;
+ if (owner == null || owner.connectionStatus != ConnectionStatus.connected) {
+ return;
+ }
+ final answer = await app.wakeGridModels(
+ owner.machine.machineId,
+ sectionName,
+ );
+ if (!_current(owner) || !answer.reachable) return;
+ models = app.gridPictures[owner.machine.machineId] ?? answer;
+ _changed();
+ }
+
Future<void> toggle(LocalModel model) async {
final owner = machine;
if (owner == null || busy || !inventoryAvailable) return;
diff --git a/desktop/lib/models/models_panel.dart b/desktop/lib/models/models_panel.dart
index 7e70c3f7a..f75d3f047 100644
--- a/desktop/lib/models/models_panel.dart
+++ b/desktop/lib/models/models_panel.dart
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
+import '../core/models.dart';
import '../shared/theme/app_theme.dart';
import '../theme/app_theme.dart';
import '../usage/models_menu_controller.dart';
@@ -11,6 +12,9 @@ import 'local_model.dart';
import 'model_manager_controller.dart';
import 'model_mark.dart';
import '../widgets/onboarding_card.dart';
+import '../widgets/resting_model_words.dart';
+import '../widgets/resting_section.dart';
+import 'shared_model_row.dart';
import 'api_connections_panel.dart';
enum ModelsTab { all, subscriptions, local, shared, apis }
@@ -38,7 +42,7 @@ class ModelsPanel extends StatefulWidget {
State<ModelsPanel> createState() => _ModelsPanelState();
}
-class _ModelsPanelState extends State<ModelsPanel> {
+class _ModelsPanelState extends State<ModelsPanel> with SectionWakes {
final _search = TextEditingController();
bool _exploring = false;
final _searchFocus = FocusNode(debugLabel: 'Search models');
@@ -81,7 +85,7 @@ class _ModelsPanelState extends State<ModelsPanel> {
final matchingShared = [
for (final section in sharedSections)
(
- name: section.name,
+ section: section,
models: section.models
.where(
(model) => [
@@ -91,8 +95,15 @@ class _ModelsPanelState extends State<ModelsPanel> {
].any((text) => text.toLowerCase().contains(query)),
)
.toList(),
+ // Resting, starting, not answering.
+ words: wordsFor(section),
),
];
+ // Drawn while it lists something or, with no search, has something to say (only ever from a
+ // newer daemon). A search is for models: a section it emptied says nothing.
+ bool drawn(
+ ({GridSection section, List<GridModel> models, SectionWords words}) s,
+ ) => s.models.isNotEmpty || (query.isEmpty && s.words.speaks);
final models = controller.localModels
.where(
(m) =>
@@ -100,9 +111,7 @@ class _ModelsPanelState extends State<ModelsPanel> {
m.id.toLowerCase().contains(query),
)
.toList();
- final hasShared = matchingShared.any(
- (section) => section.models.isNotEmpty,
- );
+ final hasShared = matchingShared.any(drawn);
final hasApis = controller.apis.connections.any(
(row) => row.matches(query),
);
@@ -333,61 +342,33 @@ class _ModelsPanelState extends State<ModelsPanel> {
_retry(controller.error!)
else if (controller.models == null)
_empty('Finding shared models…')
- else if (matchingShared.every(
- (s) => s.models.isEmpty,
- ))
+ else if (!matchingShared.any(drawn))
_empty(
query.isEmpty
? 'No shared models'
: 'No matching models',
),
- for (final section in matchingShared)
- if (section.models.isNotEmpty) ...[
+ for (final shared in matchingShared)
+ if (drawn(shared)) ...[
_heading(
- all ? 'Shared · ${section.name}' : section.name,
+ all
+ ? 'Shared · ${shared.section.name}'
+ : shared.section.name,
),
- for (final model in section.models)
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 12,
- 14,
- 6,
- 14,
- ),
- child: Row(
- children: [
- ModelMark(model: model.id),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Text(
- model.id,
- style: AppType.label(
- color: AppPalette.textPrimary,
- height: 1.3,
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- const SizedBox(height: 6),
- Text(
- model.node,
- style: AppType.monoMeta(
- color: AppPalette.textSecondary,
- height: 1.3,
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ],
- ),
- ),
- ],
+ if (shared.words.speaks)
+ RestingSectionNotes(
+ words: shared.words,
+ inset: 12,
+ onWake: () => unawaited(
+ wakeSection(
+ shared.section,
+ (section) =>
+ controller.wake(section.name),
+ ),
),
),
+ for (final model in shared.models)
+ SharedModelRow(model: model),
],
],
if (_selectedTab == ModelsTab.apis ||
@@ -518,6 +499,9 @@ class _ModelsPanelState extends State<ModelsPanel> {
? operation?.error ?? 'Could not finish. Try again.'
: [
if (model.sizeBytes case final size?) _size(size),
+ // Parked while this computer's models rest: running, and answering again by itself on
+ // the next message — not a plain "running" with its telemetry gone blank.
+ if (model.resting) kRestingUntilNextMessage,
if (model.tokensPerSecond case final speed? when model.running)
'${speed.toStringAsFixed(1)} tok/s',
if (model.requests case final requests?
diff --git a/desktop/lib/models/shared_model_row.dart b/desktop/lib/models/shared_model_row.dart
new file mode 100644
index 000000000..2d1b2de77
--- /dev/null
+++ b/desktop/lib/models/shared_model_row.dart
@@ -0,0 +1,77 @@
+import 'package:flutter/material.dart';
+
+import '../core/models.dart';
+import '../shared/theme/app_theme.dart';
+import '../theme/app_theme.dart';
+import '../widgets/resting_model_words.dart';
+import '../widgets/resting_section.dart';
+import 'model_mark.dart';
+
+/// One model a shared section of the Models panel serves: its mark, its id, and the computer
+/// serving it.
+///
+/// A row every serving computer of which seems offline stays listed — the daemon labels such rows,
+/// it never removes them — faded, with why under it. Every other row draws as it always did.
+class SharedModelRow extends StatelessWidget {
+ const SharedModelRow({super.key, required this.model});
+
+ final GridModel model;
+
+ @override
+ Widget build(BuildContext context) {
+ final offline = offlineRowNote(model);
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(12, 14, 6, 14),
+ child: Row(
+ children: [
+ offline == null
+ ? ModelMark(model: model.id)
+ : Opacity(
+ opacity: kUnavailableOpacity,
+ child: ModelMark(model: model.id),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ model.id,
+ style: AppType.label(
+ color: offline == null
+ ? AppPalette.textPrimary
+ : AppPalette.textFaint,
+ height: 1.3,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ const SizedBox(height: 6),
+ Text(
+ model.node,
+ style: AppType.monoMeta(
+ color: offline == null
+ ? AppPalette.textSecondary
+ : AppPalette.textFaint,
+ height: 1.3,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ if (offline != null) ...[
+ const SizedBox(height: 4),
+ Text(
+ offline,
+ style: AppType.body(color: AppColors.textSoft),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ],
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 286b0240f..a9c18bb81 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -52,6 +52,7 @@ import '../widgets/engine_identity.dart'
import '../store/store_screen.dart' show openStoreAgent;
import 'dial_status.dart';
import 'grid_pictures.dart';
+import 'model_start_watch.dart';
import 'harness_placement.dart';
import 'desk_sync.dart';
import 'pane_layout_store.dart';
@@ -565,6 +566,11 @@ class AppNotifier extends ChangeNotifier {
/// picker, the macOS Models menu and the Model Manager all read. See [GridPictures].
final GridPictures gridPictures = GridPictures();
+ /// Which agents were sent a message while their model's computer was resting and have not
+ /// answered yet — the pane chip's "Starting up…". Fed by [_watchModelStart] and ended with every
+ /// turn ([_cancelTurnActivity]). See [ModelStartWatch] for why these signals and not others.
+ final ModelStartWatch modelStarts = ModelStartWatch();
+
/// Whether the app is in front of the person (`AppLifecycleState.resumed`). The three surfaces
/// that refresh [gridPictures] on their own — the Model Manager's timer, the macOS menu's refresh
/// and the pane picker's prefetch — run only while this is true, and each refreshes once when it
@@ -3048,6 +3054,7 @@ class AppNotifier extends ChangeNotifier {
machineStates.clear();
sessionPreviews.clear();
gridPictures.clear();
+ _stopWakeFollowers();
expandedMachines.clear();
selectedMachineId = null;
_ensurePool();
@@ -3388,6 +3395,7 @@ class AppNotifier extends ChangeNotifier {
machineStates.clear();
sessionPreviews.clear();
gridPictures.clear();
+ _stopWakeFollowers();
expandedMachines.clear();
selectedMachineId = null;
_closedHistory.clear();
@@ -5128,10 +5136,25 @@ class AppNotifier extends ChangeNotifier {
///
/// Never throws — a machine whose daemon is too old to know the RPC, one with no grid, and one
/// that timed out are all "nothing to offer", which is what the picker shows.
- Future<GridModels> gridModels(String machineId) async {
+ Future<GridModels> gridModels(String machineId) =>
+ _askGridModels(machineId, const {'rowState': true});
+
+ /// One `grid_models_list` ask with [payload].
+ ///
+ /// `rowState: true` on every ask this app makes: every surface here draws row state, so rows
+ /// come back with `unavailable` beside a plain `node` rather than the old build's
+ /// `<computer> · seems offline` folded into it — and a loopback window that asked this way gets
+ /// its `grid_models_changed` pushes in the same form. An older daemon ignores the field.
+ Future<GridModels> _askGridModels(
+ String machineId,
+ Map<String, dynamic> payload,
+ ) async {
try {
- final response = await _conn(machineId)
- .request('grid_models_list', timeout: const Duration(seconds: 12));
+ final response = await _conn(machineId).request(
+ 'grid_models_list',
+ payload: payload,
+ timeout: const Duration(seconds: 12),
+ );
return GridModels.fromReply(response);
} catch (_) {
// NOT `gridName: null` with an empty list — that is the shape of "this account has no grid",
@@ -5141,6 +5164,76 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// A person asked to see what a resting section serves ("Show models"): ask [machineId]'s
+ /// daemon to wake [sectionName], and take its answer as the picture like any read.
+ ///
+ /// This is one of the acts that may wake a grid — nothing automatic ever calls it. The daemon
+ /// answers at once with the section `waking`; the wake itself (one credentialed read, then
+ /// credential-less re-reads for up to 45 s) runs there. Its progress reaches a loopback window by
+ /// `grid_models_changed`, and every other window only by asking again — which [_followWake] does,
+ /// credential-less, for as long as the picture says something is waking.
+ ///
+ /// Not joined with [refreshGridModels]' in-flight read: that ask carries no `wake`, and folding
+ /// this one into it would drop the person's request. An answer that was out when this one landed
+ /// is older, and the picture's epoch keeps it from overwriting this.
+ Future<GridModels> wakeGridModels(
+ String machineId,
+ String sectionName,
+ ) async {
+ final epoch = gridPictures.epochOf(machineId);
+ final answer = await _askGridModels(machineId, {
+ 'rowState': true,
+ 'wake': [sectionName],
+ });
+ if (_disposed || !answer.reachable) return answer;
+ gridPictures.adopt(machineId, answer, ifEpoch: epoch);
+ _followWake(machineId);
+ return answer;
+ }
+
+ /// How often, and for how long at most, a window re-reads a machine whose picture has a section
+ /// waking. The daemon's own wake gives up at 45 s; the extra is its last re-read landing.
+ static const _wakeFollowEvery = Duration(seconds: 5);
+ static const _wakeFollowFor = Duration(seconds: 60);
+ final Map<String, Timer> _wakeFollowers = {};
+
+ bool _pictureWaking(String machineId) =>
+ gridPictures[machineId]?.sections.any(
+ (s) => s.state == GridSectionState.waking,
+ ) ??
+ false;
+
+ /// Re-read [machineId] until no section in its picture is waking, or [_wakeFollowFor] passes.
+ ///
+ /// Harmless where pushes do arrive (this computer's own daemon): the read is the same
+ /// credential-less one every surface makes, joined with any other in flight, and a push that
+ /// already ended the wake ends this at its next tick. Skipped while the app is in the background,
+ /// like every other refresher.
+ void _followWake(String machineId) {
+ _wakeFollowers.remove(machineId)?.cancel();
+ if (!_pictureWaking(machineId)) return;
+ final deadline = _wakeFollowFor.inMilliseconds;
+ var elapsed = 0;
+ _wakeFollowers[machineId] = Timer.periodic(_wakeFollowEvery, (timer) {
+ elapsed += _wakeFollowEvery.inMilliseconds;
+ if (_disposed || !_pictureWaking(machineId) || elapsed > deadline) {
+ timer.cancel();
+ if (identical(_wakeFollowers[machineId], timer)) {
+ _wakeFollowers.remove(machineId);
+ }
+ return;
+ }
+ if (inForeground) unawaited(refreshGridModels(machineId));
+ });
+ }
+
+ void _stopWakeFollowers() {
+ for (final timer in _wakeFollowers.values) {
+ timer.cancel();
+ }
+ _wakeFollowers.clear();
+ }
+
final Map<String, Future<GridModels>> _gridReads = {};
/// Ask [machineId]'s daemon for the model list and take the answer as its [gridPictures] entry.
@@ -6608,6 +6701,55 @@ class AppNotifier extends ChangeNotifier {
PendingQuestion? questionFor(String machineId, String agentId) =>
machineStates[machineId]?.blockedAgents[agentId];
+ /// The per-agent events that only a model answering produces — the CLI's live event kinds
+ /// (`SessionEvent` and `LiveEvent` in `cli/src/lib/normalize.ts`) other than the prompt itself
+ /// (`turn_started`, `user_message`), the turn's end (which [_cancelTurnActivity] handles), and a
+ /// compaction (`context_compact`, which is the engine, not the model). A reasoning model's first
+ /// output is its thinking (`thinking_delta`, from the codex, hermes and grok normalizers among
+ /// others), long before any text.
+ static const _modelAnswerEvents = {
+ 'thinking_delta',
+ 'thinking_title',
+ 'text_delta',
+ 'tool_start',
+ 'tool_end',
+ 'subagent_finished',
+ 'done',
+ };
+
+ /// Start or end the pane chip from one of an agent's turn events — see [ModelStartWatch].
+ ///
+ /// A message is a `turn_started` that is not a `replay` (a turn picked back up at attach), for
+ /// the agent's own session, while its frame says its model's grid is asleep or waking — the
+ /// daemon's picture, carried on the agent (`grid.state`). Any of [_modelAnswerEvents] is the
+ /// model answering; the turn's end comes through [_cancelTurnActivity]. Terminal bytes are not
+ /// read at all: the first thing a pane prints after Enter is its own echo of the prompt.
+ void _watchModelStart(
+ MachineState machine,
+ String type,
+ Map<String, dynamic> event,
+ Map<String, dynamic> payload,
+ ) {
+ final agentId = _eventAgentId(machine, event, payload);
+ if (agentId == null) return;
+ final machineId = machine.machine.machineId;
+ if (_modelAnswerEvents.contains(type)) {
+ modelStarts.end(machineId, agentId);
+ return;
+ }
+ if (type != 'turn_started' || event['replay'] == true) return;
+ final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
+ if (agent == null || agent.gridState?.resting != true) return;
+ final sessionId = _eventSessionId(event, payload);
+ // A sub-agent's turn is not a message this pane sent.
+ if (sessionId != null &&
+ agent.sessionId != null &&
+ sessionId != agent.sessionId) {
+ return;
+ }
+ modelStarts.start(machineId, agentId);
+ }
+
void _cancelTurnActivity(String machineId, String agentId) {
final key = _turnActivityKey(machineId, agentId);
_turnActivityWatchdogs.remove(key)?.cancel();
@@ -6616,6 +6758,9 @@ class AppNotifier extends ChangeNotifier {
// a turn this process never saw start contributes nothing (see
// `HarnessStats.onTurnEnded`), which is what makes the disconnect sweep safe.
harnessStats.onTurnEnded(key);
+ // The same ends close the pane's "Starting up…": a turn that ended, however, has nothing
+ // left to start for.
+ modelStarts.end(machineId, agentId);
final machine = machineStates[machineId];
machine?.processingAgentIds.remove(agentId);
// A question cannot outlive its own turn — the daemon's watcher says the
@@ -6639,6 +6784,7 @@ class AppNotifier extends ChangeNotifier {
timer.cancel();
}
_turnActivityWatchdogs.clear();
+ modelStarts.clear();
for (final machine in machineStates.values) {
machine.processingAgentIds.clear();
machine.pendingProcessingSessions.clear();
@@ -10709,6 +10855,11 @@ class AppNotifier extends ChangeNotifier {
}
return;
}
+ // Before the preview's early returns: several first-output kinds (`thinking_delta`) are not
+ // preview events at all.
+ if (type == 'turn_started' || _modelAnswerEvents.contains(type)) {
+ _watchModelStart(machine, type, event, payload);
+ }
if (SessionPreviewStore.eventTypes.contains(type)) {
final agentId = _eventAgentId(machine, event, payload);
final agent = machine.agents
@@ -11205,6 +11356,8 @@ class AppNotifier extends ChangeNotifier {
_localGitProjects.dispose();
sessionPreviews.dispose();
gridPictures.dispose();
+ _stopWakeFollowers();
+ modelStarts.dispose();
foreground.dispose();
// Its sweep timer would otherwise outlive the window it was drawing into.
agentAlerts.dispose();
diff --git a/desktop/lib/state/model_start_watch.dart b/desktop/lib/state/model_start_watch.dart
new file mode 100644
index 000000000..8ca0e0f37
--- /dev/null
+++ b/desktop/lib/state/model_start_watch.dart
@@ -0,0 +1,117 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+/// How long a pane says "Starting up…" before it says the wait may be longer.
+const kStillStartingAfter = Duration(seconds: 60);
+
+/// The most a pane will say either, whatever happens — the safety cap.
+///
+/// The chip ends on the agent's first output; this is for the answer that never comes as an event:
+/// a daemon that sends no transcript events for this engine, a frame lost with a dropped socket, an
+/// engine that failed without a word. Three minutes is three times the wait the chip's second
+/// phase promises ("up to a minute") — past it, the sentence is no longer true, and the pane's own
+/// terminal is the better witness of what is happening.
+const kStartWatchCap = Duration(minutes: 3);
+
+/// What a pane waiting on a resting model says — see [ModelStartWatch].
+enum ModelStartPhase {
+ /// From the message until [kStillStartingAfter]: "Starting up…".
+ starting,
+
+ /// After that, until the first output or [kStartWatchCap]: "Still starting — …".
+ stillStarting,
+}
+
+/// Which agents have been sent a message while their model's computer was resting, and have not
+/// answered yet.
+///
+/// Fed by [AppNotifier] from the daemon's per-agent turn events, never from terminal bytes:
+///
+/// * **Sent** is `turn_started` — the CLI's own word that a prompt was submitted, from the engine's
+/// hook or transcript. It covers a message typed straight into the terminal, one sent from the
+/// composer, and one sent from another client alike; the composer alone would miss the first.
+/// A `turn_started` marked `replay` is a turn picked back up at attach, not a message now.
+/// * **First output** is the first `text_delta` or `tool_start` of that turn — the model answering —
+/// or the turn ending (`turn_ended`, a deleted agent, a lost connection).
+///
+/// Terminal output is deliberately NOT a signal: the first bytes a pane prints after Enter are the
+/// engine echoing the prompt and drawing its own spinner, which would end the chip the moment it
+/// appeared. Those events are what this app already trusts for the rail's working mark and for
+/// `app_first_message`.
+///
+/// Its own notifier, like [GridPictures], so a pane header listening for its chip is not rebuilt on
+/// every terminal frame.
+class ModelStartWatch extends ChangeNotifier {
+ final Map<String, _Wait> _waits = {};
+ bool _disposed = false;
+
+ static String _key(String machineId, String agentId) =>
+ '$machineId\u0000$agentId';
+
+ /// What [agentId]'s pane says right now, or null when it is not waiting on anything.
+ ModelStartPhase? phaseOf(String machineId, String agentId) =>
+ _waits[_key(machineId, agentId)]?.phase;
+
+ /// A message went to [agentId] while its model's computer was resting. A second message while
+ /// the first is still waiting is the same wait continuing, and keeps its clock.
+ void start(String machineId, String agentId) {
+ if (_disposed) return;
+ final key = _key(machineId, agentId);
+ if (_waits.containsKey(key)) return;
+ late final _Wait wait;
+ wait = _Wait(
+ still: Timer(kStillStartingAfter, () {
+ if (!identical(_waits[key], wait)) return;
+ wait.phase = ModelStartPhase.stillStarting;
+ notifyListeners();
+ }),
+ cap: Timer(kStartWatchCap, () {
+ if (identical(_waits[key], wait)) end(machineId, agentId);
+ }),
+ );
+ _waits[key] = wait;
+ notifyListeners();
+ }
+
+ /// [agentId] answered, its turn ended, or it is gone: its pane stops waiting.
+ void end(String machineId, String agentId) {
+ final wait = _waits.remove(_key(machineId, agentId));
+ if (wait == null) return;
+ wait.cancel();
+ if (!_disposed) notifyListeners();
+ }
+
+ /// Forget every wait — a sign-out, where the next account's agents are not these.
+ void clear() {
+ if (_waits.isEmpty) return;
+ for (final wait in _waits.values) {
+ wait.cancel();
+ }
+ _waits.clear();
+ if (!_disposed) notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ for (final wait in _waits.values) {
+ wait.cancel();
+ }
+ _waits.clear();
+ super.dispose();
+ }
+}
+
+class _Wait {
+ _Wait({required this.still, required this.cap});
+
+ final Timer still;
+ final Timer cap;
+ ModelStartPhase phase = ModelStartPhase.starting;
+
+ void cancel() {
+ still.cancel();
+ cap.cancel();
+ }
+}
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 19d56c389..3c6084150 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -22,6 +22,7 @@ import '../core/project_folder.dart';
import '../core/repository_clone.dart';
import '../core/test_run.dart';
import '../widgets/engine_identity.dart';
+import '../widgets/resting_model_words.dart';
import 'app_state.dart';
import 'harness_placement.dart';
import 'pane_arrangement.dart';
@@ -997,7 +998,12 @@ class NewHarnessController extends ChangeNotifier {
GridModel(id: model.id, node: model.node, grid: section.name),
),
title: model.id,
- detail: model.node,
+ // Every read now asks for row state, so the daemon no longer folds "seems
+ // offline" into the node — this row puts back what an older build showed.
+ detail: switch (model.unavailable) {
+ final offline? => offlineNodeLabel(offline.machine),
+ null => model.node,
+ },
group: section.own
? 'On your machines'
: 'Shared · ${section.name}',
diff --git a/desktop/lib/widgets/grid_model_picker.dart b/desktop/lib/widgets/grid_model_picker.dart
index a94449d9a..fc5e81b8e 100644
--- a/desktop/lib/widgets/grid_model_picker.dart
+++ b/desktop/lib/widgets/grid_model_picker.dart
@@ -10,8 +10,11 @@ import '../shared/theme/app_type.dart';
import '../theme/app_theme.dart';
import '../usage/models_menu_controller.dart';
import 'engine_identity.dart';
+import 'model_picker_answer.dart';
import 'model_picker_chrome.dart';
import 'pane_menu.dart';
+import 'resting_model_words.dart';
+import 'resting_section.dart';
/// The engines whose panes carry a model picker.
///
@@ -75,6 +78,9 @@ class GridModelPicker extends StatefulWidget {
final String? engineLabel;
final bool compact;
+ /// Opens the menu whenever it fires, as a click does — the pane note's "Pick another".
+ final Listenable? openRequests;
+
const GridModelPicker({
super.key,
required this.notifier,
@@ -86,6 +92,7 @@ class GridModelPicker extends StatefulWidget {
this.webSearch,
this.engineLabel,
this.compact = false,
+ this.openRequests,
});
@override
@@ -112,6 +119,7 @@ class _GridModelPickerState extends State<GridModelPicker> {
_last = widget.notifier.gridPictures[widget.machineId];
widget.notifier.gridPictures.addListener(_pictureChanged);
widget.notifier.foreground.addListener(_foregroundChanged);
+ widget.openRequests?.addListener(_openRequested);
// A reading that lands while the menu is open redraws its Subscription row, rather than
// leaving "Checking usage…" there until the next open.
_usage.addListener(_redrawOpenMenu);
@@ -127,6 +135,12 @@ class _GridModelPickerState extends State<GridModelPicker> {
}
}
+ /// [GridModelPicker.openRequests] fired. One menu at a time.
+ void _openRequested() {
+ if (!mounted || _entry != null) return;
+ unawaited(_open());
+ }
+
void _foregroundChanged() {
if (!mounted || !_prefetchOwed || !widget.notifier.inForeground) return;
_prefetchOwed = false;
@@ -196,6 +210,10 @@ class _GridModelPickerState extends State<GridModelPicker> {
@override
void didUpdateWidget(GridModelPicker oldWidget) {
super.didUpdateWidget(oldWidget);
+ if (!identical(widget.openRequests, oldWidget.openRequests)) {
+ oldWidget.openRequests?.removeListener(_openRequested);
+ widget.openRequests?.addListener(_openRequested);
+ }
if (widget.currentModel == oldWidget.currentModel) return;
if (_expecting && _settles(widget.currentModel)) {
_expiry?.cancel();
@@ -250,6 +268,7 @@ class _GridModelPickerState extends State<GridModelPicker> {
void dispose() {
widget.notifier.gridPictures.removeListener(_pictureChanged);
widget.notifier.foreground.removeListener(_foregroundChanged);
+ widget.openRequests?.removeListener(_openRequested);
_expiry?.cancel();
// A pane can go away under an open menu — closed, moved, or its swarm switched — and an overlay
// entry outlives the State that inserted it.
@@ -335,6 +354,8 @@ class _GridModelPickerState extends State<GridModelPicker> {
sections: _sectionsToDraw(_shown!),
subtitleFor: _subtitleFor,
emptySentence: (section) => _emptySentence(_shown!, section),
+ onWake: (section) =>
+ widget.notifier.wakeGridModels(widget.machineId, section.name),
close: close,
),
);
@@ -351,10 +372,20 @@ class _GridModelPickerState extends State<GridModelPicker> {
}
return;
}
- if (chosen.model!.id != _effectiveModel) {
- _expect(chosen.model!.id);
- widget.onSelected?.call(chosen.model!);
+ final model = chosen.model!;
+ if (model.id == _effectiveModel) return;
+ // A row whose every computer seems offline is asked about first; the move is never refused.
+ if (model.unavailable case final offline?) {
+ if (!mounted) return;
+ final go = await confirmSwitchAnyway(
+ context,
+ model: model.id,
+ offline: offline,
+ );
+ if (!go || !mounted) return;
}
+ _expect(model.id);
+ widget.onSelected?.call(model);
}
/// What the Local section says when it lists nothing.
@@ -385,9 +416,10 @@ class _GridModelPickerState extends State<GridModelPicker> {
/// and a shared grid only while it serves something. A team grid with nothing running is not
/// a choice this menu can offer, and a heading over "nothing here" was a line to read for no
/// gain — the menu is for picking a model, not for surveying grids.
+ /// Unless it has something to SAY ([SectionWords.speaks] — only ever from a newer daemon).
List<GridSection> _sectionsToDraw(GridModels answer) {
final sections = answer.sections
- .where((s) => s.own || s.models.isNotEmpty)
+ .where((s) => s.own || s.models.isNotEmpty || sectionWords(s).speaks)
.toList();
if (sections.any((s) => s.own)) return sections;
return [
@@ -431,47 +463,13 @@ class _GridModelPickerState extends State<GridModelPicker> {
final fresh = _last;
final shown = _shown;
if (!mounted || entry == null || fresh == null || shown == null) return;
- if (_sameAnswer(fresh, shown)) return;
+ if (drawsSameMenu(fresh, shown)) return;
_shown = fresh;
// One safe path for every redraw — see [_redrawOpenMenu]. This one arrives off an async read
// and so is usually clear of the build phase, but "usually" is what the crash was.
_redrawOpenMenu();
}
- static bool _sameAnswer(GridModels a, GridModels b) {
- if (a.reachable != b.reachable ||
- a.gridName != b.gridName ||
- a.gridCli != b.gridCli) {
- return false;
- }
- if (a.models.length != b.models.length) return false;
- for (var i = 0; i < a.models.length; i += 1) {
- if (a.models[i].id != b.models[i].id ||
- a.models[i].node != b.models[i].node) {
- return false;
- }
- }
- if (a.grids.length != b.grids.length) return false;
- for (var i = 0; i < a.grids.length; i += 1) {
- final left = a.grids[i];
- final right = b.grids[i];
- if (left.name != right.name ||
- left.own != right.own ||
- left.state != right.state ||
- left.models.length != right.models.length) {
- return false;
- }
- for (var j = 0; j < left.models.length; j += 1) {
- if (left.models[j].id != right.models[j].id ||
- left.models[j].node != right.models[j].node ||
- left.models[j].grid != right.models[j].grid) {
- return false;
- }
- }
- }
- return true;
- }
-
@override
Widget build(BuildContext context) {
TerminalFontScope.watch(context);
@@ -573,6 +571,7 @@ class _ModelPickerPanel extends StatefulWidget {
required this.sections,
required this.subtitleFor,
required this.emptySentence,
+ required this.onWake,
required this.close,
});
@@ -583,13 +582,17 @@ class _ModelPickerPanel extends StatefulWidget {
final List<GridSection> sections;
final String? Function(GridModel) subtitleFor;
final String? Function(GridSection) emptySentence;
+
+ /// "Show models": wake that section. The menu stays open; the answer lands in it.
+ final Future<void> Function(GridSection) onWake;
final void Function(_Choice?) close;
@override
State<_ModelPickerPanel> createState() => _ModelPickerPanelState();
}
-class _ModelPickerPanelState extends State<_ModelPickerPanel> {
+class _ModelPickerPanelState extends State<_ModelPickerPanel>
+ with SectionWakes {
final _query = TextEditingController();
String _needle = '';
@@ -645,6 +648,8 @@ class _ModelPickerPanelState extends State<_ModelPickerPanel> {
// A section a search has emptied says nothing: the query is the reason, and repeating
// "nothing here" under every heading turns one empty result into a wall of them.
if (_needle.isNotEmpty && models.isEmpty) continue;
+ // Resting, starting, not answering — nothing for an engine that cannot use it at all.
+ final words = canRunLocally ? wordsFor(section) : SectionWords.none;
rows.add(
ModelPickerSectionHeader(
label: section.own ? 'On your machines' : 'Shared · ${section.name}',
@@ -659,18 +664,30 @@ class _ModelPickerPanelState extends State<_ModelPickerPanel> {
);
continue;
}
+ if (words.speaks) {
+ rows.add(
+ RestingSectionNotes(
+ words: words,
+ inset: kModelPickerInset,
+ onWake: () => unawaited(wakeSection(section, widget.onWake)),
+ ),
+ );
+ }
if (models.isEmpty) {
- final sentence = widget.emptySentence(section);
+ // Resting or starting is not empty: "set up your first model" would be wrong about it.
+ final sentence = words.speaks ? null : widget.emptySentence(section);
if (sentence != null) rows.add(_panelSentence(sentence));
continue;
}
for (final model in models) {
+ final offlineSentence = offlineRowNote(model);
rows.add(
Padding(
padding: const EdgeInsets.only(bottom: 2),
child: Tooltip(
message: [
'Where this agent runs',
+ ?offlineSentence,
?widget.subtitleFor(model),
].join('\n'),
child: ModelPickerRow(
@@ -679,8 +696,10 @@ class _ModelPickerPanelState extends State<_ModelPickerPanel> {
// The web-search sentence for the CURRENT model only — a fact
// about this agent's launch, not about the model. Dropped when
// the panel replaced the old row list, which lost it silently;
- // the tests that caught it are the reason it is back.
- hint: widget.subtitleFor(model),
+ // the tests that caught it are the reason it is back. A row
+ // that will not answer at all says that instead.
+ hint: offlineSentence ?? widget.subtitleFor(model),
+ dimmed: offlineSentence != null,
selected: widget.currentModel == model.id,
avatar: ModelAvatar(label: model.id),
note: null,
diff --git a/desktop/lib/widgets/model_picker_answer.dart b/desktop/lib/widgets/model_picker_answer.dart
new file mode 100644
index 000000000..f4aa5c83f
--- /dev/null
+++ b/desktop/lib/widgets/model_picker_answer.dart
@@ -0,0 +1,45 @@
+/// When a fresh model list is the one an open picker already draws.
+///
+/// The picker redraws its open menu when a read or a push lands with a different list; a rebuild
+/// for an identical one would only flicker the hover. "Different" is what the menu SHOWS — rows,
+/// their nodes and labels, and what each section says about itself — not every field under it:
+/// `lastKnownAge` moves on every read, and a subtitle that rounds to the same words is the same.
+library;
+
+import '../core/models.dart';
+import 'resting_model_words.dart';
+
+bool drawsSameMenu(GridModels a, GridModels b) {
+ if (a.reachable != b.reachable ||
+ a.gridName != b.gridName ||
+ a.gridCli != b.gridCli) {
+ return false;
+ }
+ if (a.models.length != b.models.length) return false;
+ for (var i = 0; i < a.models.length; i += 1) {
+ if (!_sameRow(a.models[i], b.models[i])) return false;
+ }
+ if (a.grids.length != b.grids.length) return false;
+ for (var i = 0; i < a.grids.length; i += 1) {
+ final left = a.grids[i];
+ final right = b.grids[i];
+ // What a section SAYS, not every field: `lastKnownAge` moves on every read.
+ if (left.name != right.name ||
+ left.own != right.own ||
+ left.state != right.state ||
+ sectionWords(left) != sectionWords(right) ||
+ left.models.length != right.models.length) {
+ return false;
+ }
+ for (var j = 0; j < left.models.length; j += 1) {
+ if (!_sameRow(left.models[j], right.models[j])) return false;
+ }
+ }
+ return true;
+}
+
+bool _sameRow(GridModel a, GridModel b) =>
+ a.id == b.id &&
+ a.node == b.node &&
+ a.grid == b.grid &&
+ a.unavailable?.machine == b.unavailable?.machine;
diff --git a/desktop/lib/widgets/model_picker_chrome.dart b/desktop/lib/widgets/model_picker_chrome.dart
index 5cf6ad9f7..ad737bb92 100644
--- a/desktop/lib/widgets/model_picker_chrome.dart
+++ b/desktop/lib/widgets/model_picker_chrome.dart
@@ -16,6 +16,7 @@ import 'package:flutter/services.dart';
import '../models/model_mark.dart';
import '../shared/theme/app_type.dart';
import '../theme/app_theme.dart';
+import 'resting_section.dart' show kUnavailableOpacity;
/// The panel's own width. Narrower than a row list, because every row here is two lines and the
/// eye reads a column better than a stripe.
@@ -205,6 +206,7 @@ class ModelPickerRow extends StatelessWidget {
this.meter,
this.note,
this.hint,
+ this.dimmed = false,
});
final String title;
@@ -213,6 +215,10 @@ class ModelPickerRow extends StatelessWidget {
final VoidCallback onTap;
final Widget? avatar;
+ /// Greyed: a row the picker still offers but that will not answer right now — every computer
+ /// serving it seems offline. Still a choice; what picking it does is the picker's to decide.
+ final bool dimmed;
+
/// The right-hand column — a quota, a state, whatever the row is worth saying.
final Widget? trailing;
@@ -233,7 +239,12 @@ class ModelPickerRow extends StatelessWidget {
final row = Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
- if (avatar != null) ...[avatar!, const SizedBox(width: 11)],
+ if (avatar != null) ...[
+ dimmed
+ ? Opacity(opacity: kUnavailableOpacity, child: avatar)
+ : avatar!,
+ const SizedBox(width: 11),
+ ],
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -243,8 +254,9 @@ class ModelPickerRow extends StatelessWidget {
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: AppType.body(color: AppColors.text)
- .copyWith(fontWeight: FontWeight.w600, fontSize: 13.5),
+ style: AppType.body(
+ color: dimmed ? AppColors.muted : AppColors.text,
+ ).copyWith(fontWeight: FontWeight.w600, fontSize: 13.5),
),
if (subtitle.isNotEmpty) ...[
const SizedBox(height: 2),
@@ -252,14 +264,18 @@ class ModelPickerRow extends StatelessWidget {
subtitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: AppType.mono(color: AppColors.mutedStrong),
+ style: AppType.mono(
+ color: dimmed ? AppColors.muted : AppColors.mutedStrong,
+ ),
),
],
if (hint != null) ...[
const SizedBox(height: 2),
+ // Two lines: "<computer> seems offline — its models come back when it does" is
+ // longer than a row is wide, and cut short it no longer says when.
Text(
hint!,
- maxLines: 1,
+ maxLines: 2,
overflow: TextOverflow.ellipsis,
style: AppType.body(color: AppColors.muted)
.copyWith(fontSize: 11.5),
diff --git a/desktop/lib/widgets/pane_model_status.dart b/desktop/lib/widgets/pane_model_status.dart
new file mode 100644
index 000000000..db658a268
--- /dev/null
+++ b/desktop/lib/widgets/pane_model_status.dart
@@ -0,0 +1,175 @@
+/// What a pane says about the model its agent is on, when that model is resting or not answering
+/// (grid-reads-without-waking, issue 03): the header chip between a message and its first answer,
+/// and the note under the header while the daemon notes the agent's model will not answer.
+///
+/// Presentation only. When the chip shows is [ModelStartWatch]'s to say; what the note says is the
+/// daemon's (`grid.note`), in the words of `resting_model_words.dart`.
+library;
+
+import 'package:flutter/material.dart';
+
+import '../core/models.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../state/model_start_watch.dart';
+import '../theme/app_theme.dart';
+import 'resting_model_words.dart';
+
+/// The chip's mark, the gap after it, and its padding — one set of numbers for the chip and for
+/// the room [paneStartingChipWidth] asks the header to leave it.
+const double _kChipMark = 14;
+const double _kChipGap = 6;
+const EdgeInsets _kChipPadding = EdgeInsets.symmetric(horizontal: 6, vertical: 4);
+
+/// The note strip's one line: tall enough for its "Pick another" button, and the same height with
+/// or without one, so a note that loses its action does not resize the terminal again.
+const double _kNoteHeight = 30;
+
+/// Opens a pane's model picker from somewhere other than its control — the model note's
+/// "Pick another". Owned by the pane; handed to the picker as its `openRequests`.
+class ModelPickerOpener extends ChangeNotifier {
+ void open() => notifyListeners();
+}
+
+/// The chip's words for [phase].
+String startingChipLabel(ModelStartPhase phase) => switch (phase) {
+ ModelStartPhase.starting => kStartingUp,
+ ModelStartPhase.stillStarting => kStillStarting,
+};
+
+TextStyle _chipStyle() => grid.AppType.monoLabel(
+ fontWeight: FontWeight.w400,
+ color: AppColors.textSoft,
+);
+
+/// The pane header's "Starting up…" chip. Not a button: there is nothing to do but wait, and the
+/// tooltip says why the wait happens at all. [narrow] draws only the mark, the way a narrow header
+/// draws its status chip, with the words on hover.
+class PaneStartingChip extends StatelessWidget {
+ const PaneStartingChip({super.key, required this.phase, this.narrow = false});
+
+ final ModelStartPhase phase;
+ final bool narrow;
+
+ @override
+ Widget build(BuildContext context) {
+ final label = startingChipLabel(phase);
+ final mark = Icon(
+ Icons.hourglass_top,
+ size: _kChipMark,
+ color: AppColors.textSoft,
+ );
+ return Semantics(
+ liveRegion: true,
+ label: label,
+ child: Tooltip(
+ message: narrow ? '$label\n$kRestingTooltip' : kRestingTooltip,
+ child: Padding(
+ padding: _kChipPadding,
+ child: narrow
+ ? mark
+ : Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ mark,
+ const SizedBox(width: _kChipGap),
+ Flexible(
+ child: Text(
+ label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: _chipStyle(),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// The room [PaneStartingChip] asks for in a header, so the header can leave it that much beside
+/// the agent's name.
+double paneStartingChipWidth(ModelStartPhase phase, TextScaler scaler) {
+ final painter = TextPainter(
+ text: TextSpan(text: startingChipLabel(phase), style: _chipStyle()),
+ textDirection: TextDirection.ltr,
+ textScaler: scaler,
+ maxLines: 1,
+ )..layout();
+ final width = painter.width;
+ painter.dispose();
+ return _kChipMark + _kChipGap + width + _kChipPadding.horizontal;
+}
+
+/// The strip under a pane's header while its agent's model will not answer — one line, in flow, so
+/// it covers none of the terminal. [onPickAnother] opens the pane's model picker; it is offered
+/// only for a model that is not being served (an offline computer comes back by itself) and only
+/// where the pane has a picker to open.
+class PaneModelNote extends StatelessWidget {
+ const PaneModelNote({super.key, required this.note, this.onPickAnother});
+
+ final GridNote note;
+ final VoidCallback? onPickAnother;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final pick = switch (note) {
+ GridNoteNotServed() => onPickAnother,
+ GridNoteOffline() => null,
+ };
+ final sentence = noteSentence(note);
+ return Semantics(
+ container: true,
+ liveRegion: true,
+ child: Container(
+ height: _kNoteHeight,
+ padding: const EdgeInsets.only(left: 14, right: 8),
+ decoration: BoxDecoration(
+ color: Color.alphaBlend(
+ AppColors.warning.withValues(alpha: 0.10),
+ grid.AppPalette.panelBg,
+ ),
+ border: Border(bottom: BorderSide(color: AppColors.border)),
+ ),
+ child: Row(
+ children: [
+ Icon(
+ switch (note) {
+ GridNoteOffline() => Icons.cloud_off,
+ GridNoteNotServed() => Icons.info_outline,
+ },
+ size: _kChipMark,
+ color: AppColors.warning,
+ ),
+ const SizedBox(width: 8),
+ Flexible(
+ child: Tooltip(
+ message: pick == null ? sentence : '$sentence — $kPickAnother',
+ child: Text(
+ pick == null ? sentence : '$sentence —',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: grid.AppType.body(color: AppColors.textSoft),
+ ),
+ ),
+ ),
+ if (pick != null)
+ TextButton(
+ onPressed: pick,
+ style: TextButton.styleFrom(
+ minimumSize: Size.zero,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ padding: _kChipPadding,
+ foregroundColor: AppColors.accent,
+ textStyle: grid.AppType.monoLabel(),
+ ),
+ child: const Text(kPickAnother),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/resting_model_words.dart b/desktop/lib/widgets/resting_model_words.dart
new file mode 100644
index 000000000..39c8ee4c3
--- /dev/null
+++ b/desktop/lib/widgets/resting_model_words.dart
@@ -0,0 +1,189 @@
+/// What the app says about models on computers that rest to save resources.
+///
+/// The daemon reads the account's grids without waking them (grid-reads-without-waking, issue 02)
+/// and, since issue 03, labels what it read: a section asleep with its last known list, one it
+/// could not reach, a wake a person asked for, a row whose computers seem offline, an agent whose
+/// model is not answering. The wire contract's table ("How a client reads a section") is the
+/// authority for every sentence here.
+///
+/// Written ONCE, here, for every surface — the pane picker, the Models panel and the pane itself —
+/// so one state cannot be worded two ways, and so one test can hold all of them to the rule that no
+/// sentence a person reads says "grid". Nothing here decides anything; a surface that gets no new
+/// field from its daemon gets nothing from this file, and draws exactly what it drew before.
+library;
+
+import '../core/models.dart';
+
+/// Under an asleep section's heading, on hover.
+const kRestingTooltip =
+ 'Resting to save resources. It starts by itself when you send a message.';
+
+/// The row a section with no record offers instead of a list, and the wait it promises.
+const kShowModels = 'Show models';
+const kShowModelsWait = 'usually 15–40 s';
+
+/// While a wake a person asked for is running.
+const kStartingUpWait = 'Starting up… usually 15–40 s';
+
+/// Asleep, with a record that lists nothing.
+const kNobodyWasServing = 'Nobody was serving here when it went to sleep';
+
+/// A read that failed some other way, above whatever was last known.
+const kNotAnswering = 'Not answering right now';
+
+/// A wake that started the section and found nobody serving.
+const kNobodyServing = 'Nobody is serving a model here right now';
+
+/// The pane chip, from a message sent to a resting model until its first output.
+const kStartingUp = 'Starting up…';
+const kStillStarting = 'Still starting — this can take up to a minute';
+
+/// The pane note's action, which opens that pane's model picker.
+const kPickAnother = 'Pick another';
+
+/// The confirmation before moving an agent onto a row whose computers seem offline.
+const kSwitchAnyway = 'Switch anyway?';
+const kSwitchAnywayAction = 'Switch';
+
+/// The Model Manager's row for a model parked while this computer's models rest.
+const kRestingUntilNextMessage = 'Running · resting until your next message';
+
+/// How old the list shown is, in the contract's units: "just now" under a minute, then whole
+/// minutes, hours and days — rounded down, so a list is never called younger than it is.
+String listAge(int seconds) {
+ if (seconds < 60) return 'just now';
+ if (seconds < 3600) return '${seconds ~/ 60} min ago';
+ if (seconds < 86400) return '${seconds ~/ 3600} h ago';
+ return '${seconds ~/ 86400} d ago';
+}
+
+/// The asleep section's subtitle. The age is left off when the daemon did not send one — a list
+/// with no known age is still a resting section, and "from ? ago" would be a guess.
+String restingSubtitle(int? lastKnownAge) => [
+ 'Asleep',
+ 'starts when you send a message (about 10–30 s)',
+ if (lastKnownAge != null) 'list from ${listAge(lastKnownAge)}',
+].join(' · ');
+
+/// A wake that could not start [section]. The account's own section is "your models" — its name is
+/// an internal id nobody chose — and a shared one goes by the name it is listed under.
+String couldNotStart(GridSection section) =>
+ "Couldn't start ${section.own ? 'your models' : section.name} right now — "
+ 'it will start on your next message';
+
+/// Under a row every serving computer of which seems offline. The row stays: labelled, never
+/// removed, and still pickable behind [kSwitchAnyway].
+String offlineRowSentence(String machine) =>
+ '$machine seems offline — its models come back when it does';
+
+/// [offlineRowSentence] for [model], or null for a row that is fine.
+String? offlineRowNote(GridModel model) => switch (model.unavailable) {
+ final offline? => offlineRowSentence(offline.machine),
+ null => null,
+};
+
+/// A row's node as a client that does not draw row state reads it — the daemon's own words for
+/// such a client (`<computer> · seems offline`, with the computer as the Machines list names it).
+/// New Harness lists rows as text, so it asks for row state like every surface and puts this back.
+String offlineNodeLabel(String machine) => '$machine · seems offline';
+
+/// The pane note for an agent whose model's computers all seem offline.
+String offlineNoteSentence(String machine, String model) =>
+ "$machine seems offline — $model won't answer until it's back";
+
+/// The pane note for an agent whose model the latest list no longer has, up to its action — the
+/// pane draws [kPickAnother] after it as the button that opens its picker.
+String notServedNoteSentence(String model) =>
+ "$model isn't being served right now";
+
+/// What one section says about itself beside its list.
+///
+/// [subtitle] and [tooltip] go under the heading; [sentence] above the rows (or alone, when there
+/// are none); [offerWake] is the "Show models" row. All empty for a daemon that sent no state,
+/// which is what keeps an older daemon's menu byte for byte what it was.
+class SectionWords {
+ final String? subtitle;
+ final String? tooltip;
+ final String? sentence;
+ final bool offerWake;
+
+ const SectionWords({
+ this.subtitle,
+ this.tooltip,
+ this.sentence,
+ this.offerWake = false,
+ });
+
+ static const none = SectionWords();
+
+ /// Whether a section with no models still has something to show: a shared section is drawn only
+ /// while it serves something OR has this to say.
+ bool get speaks => subtitle != null || sentence != null || offerWake;
+
+ @override
+ bool operator ==(Object other) =>
+ other is SectionWords &&
+ other.subtitle == subtitle &&
+ other.tooltip == tooltip &&
+ other.sentence == sentence &&
+ other.offerWake == offerWake;
+
+ @override
+ int get hashCode => Object.hash(subtitle, tooltip, sentence, offerWake);
+}
+
+/// Read [section] the way the contract's table does.
+///
+/// One sentence at most, in this order — the most recent thing a person did first: a wake that is
+/// running; the outcome of one that showed nothing; then what the section's own state says. The
+/// asleep subtitle is independent of all of them: it describes the list, and a list can be there
+/// under any of them.
+///
+/// [asking] is a wake this surface has sent and not yet heard back about. The daemon answers one
+/// at once with `waking`, so this only covers that round trip — and an answer that does not say
+/// `waking` (a daemon that predates the wake) puts the "Show models" row back rather than leaving a
+/// promise nothing will keep.
+SectionWords sectionWords(GridSection section, {bool asking = false}) {
+ final state = section.state;
+ final hasModels = section.models.isNotEmpty;
+ final noRecord = section.lastKnownAge == null;
+ final subtitle = state == GridSectionState.asleep && hasModels
+ ? restingSubtitle(section.lastKnownAge)
+ : null;
+ final wakeable = state == GridSectionState.asleep && !hasModels && noRecord;
+ final String? sentence;
+ var offerWake = false;
+ if (state == GridSectionState.waking) {
+ sentence = kStartingUpWait;
+ } else if (section.wakeOutcome case final outcome?) {
+ sentence = switch (outcome) {
+ GridWakeOutcome.notStarted => couldNotStart(section),
+ GridWakeOutcome.nobodyServing => kNobodyServing,
+ };
+ } else if (wakeable) {
+ sentence = asking ? kStartingUpWait : null;
+ offerWake = !asking;
+ } else if (state == GridSectionState.asleep && !hasModels) {
+ sentence = kNobodyWasServing;
+ } else if (state == GridSectionState.unknown &&
+ (hasModels || section.seenAt != null || !noRecord)) {
+ sentence = kNotAnswering;
+ } else {
+ sentence = null;
+ }
+ if (subtitle == null && sentence == null && !offerWake) {
+ return SectionWords.none;
+ }
+ return SectionWords(
+ subtitle: subtitle,
+ tooltip: subtitle == null ? null : kRestingTooltip,
+ sentence: sentence,
+ offerWake: offerWake,
+ );
+}
+
+/// The note for [note], up to the picker action when it has one — see [notServedNoteSentence].
+String noteSentence(GridNote note) => switch (note) {
+ GridNoteOffline(:final machine) => offlineNoteSentence(machine, note.model),
+ GridNoteNotServed() => notServedNoteSentence(note.model),
+};
diff --git a/desktop/lib/widgets/resting_section.dart b/desktop/lib/widgets/resting_section.dart
new file mode 100644
index 000000000..b2b344e05
--- /dev/null
+++ b/desktop/lib/widgets/resting_section.dart
@@ -0,0 +1,187 @@
+/// What the pane picker and the Models panel both draw for a section whose computers rest to save
+/// resources (grid-reads-without-waking, issue 03): the lines under its heading, the "Show models"
+/// row and the wake it sends, the fade on a row that will not answer, and the question before an
+/// agent is moved onto one. Written once so the two surfaces cannot drift apart; the words
+/// themselves are `resting_model_words.dart`'s.
+library;
+
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../core/models.dart';
+import '../shared/theme/app_type.dart';
+import '../shared/widgets/app_dialog.dart';
+import '../theme/app_theme.dart';
+import 'resting_model_words.dart';
+
+/// How far a row that will not answer is faded — every computer serving it seems offline. Listed
+/// still, never removed.
+const double kUnavailableOpacity = 0.45;
+
+/// The "Show models" row's mark: the size the Models panel draws its row icons at, in a column as
+/// wide as the smaller of the two surfaces' avatars.
+const double _kWakeIconSize = 17;
+const double _kWakeIconColumn = 28;
+
+/// The sections a surface has asked to wake and not yet heard back about.
+///
+/// The daemon answers a wake at once with the section `waking`, so this covers only that round
+/// trip: "Starting up…" at the click rather than a beat later — and an answer that does not say
+/// `waking` (a daemon that predates the wake) puts "Show models" back rather than leaving a promise
+/// nothing will keep. Lives in the surface's State, so it lasts exactly as long as the surface.
+mixin SectionWakes<T extends StatefulWidget> on State<T> {
+ final Set<String> _asking = {};
+
+ /// What [section] says, counting a wake this surface has in flight — see [sectionWords].
+ SectionWords wordsFor(GridSection section) =>
+ sectionWords(section, asking: _asking.contains(section.name));
+
+ /// Send [wake] for [section], once however often the row is clicked.
+ Future<void> wakeSection(
+ GridSection section,
+ Future<void> Function(GridSection) wake,
+ ) async {
+ if (!_asking.add(section.name)) return;
+ setState(() {});
+ try {
+ await wake(section);
+ } finally {
+ if (mounted) setState(() => _asking.remove(section.name));
+ }
+ }
+}
+
+/// The lines under a section's heading: the resting subtitle (why, on hover), one sentence above
+/// the rows, and the "Show models" row. Draws nothing for [SectionWords.none] — which is every
+/// section an older daemon sends.
+class RestingSectionNotes extends StatelessWidget {
+ const RestingSectionNotes({
+ super.key,
+ required this.words,
+ required this.inset,
+ required this.onWake,
+ });
+
+ final SectionWords words;
+
+ /// The surface's content line, which the text starts on.
+ final double inset;
+
+ /// "Show models": wake this section. The surface stays open; the answer lands in it.
+ final VoidCallback onWake;
+
+ @override
+ Widget build(BuildContext context) => Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (words.subtitle case final subtitle?)
+ Padding(
+ padding: EdgeInsets.fromLTRB(inset, 0, inset, 4),
+ child: Tooltip(
+ message: words.tooltip ?? '',
+ child: Text(
+ subtitle,
+ style: AppType.caption(color: AppColors.muted),
+ ),
+ ),
+ ),
+ // Above the list it is about ("Not answering right now" over the last known models), or in
+ // place of one.
+ if (words.sentence case final sentence?)
+ Padding(
+ padding: EdgeInsets.fromLTRB(inset, 4, inset, 8),
+ child: Text(sentence, style: AppType.body(color: AppColors.textSoft)),
+ ),
+ if (words.offerWake) _WakeRow(inset: inset, onTap: onWake),
+ ],
+ );
+}
+
+/// "Show models" for a resting section with no record: the one way to learn what it serves short
+/// of sending it a message, and a person's act, so it is allowed to wake it.
+class _WakeRow extends StatelessWidget {
+ const _WakeRow({required this.inset, required this.onTap});
+
+ final double inset;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) => MouseRegion(
+ cursor: SystemMouseCursors.click,
+ child: InkWell(
+ onTap: onTap,
+ mouseCursor: SystemMouseCursors.click,
+ borderRadius: BorderRadius.circular(8),
+ hoverColor: AppColors.rowHover,
+ child: Padding(
+ padding: EdgeInsets.symmetric(horizontal: inset, vertical: 10),
+ child: Row(
+ children: [
+ SizedBox(
+ width: _kWakeIconColumn,
+ child: Icon(
+ Icons.visibility_outlined,
+ size: _kWakeIconSize,
+ color: AppColors.textSoft,
+ ),
+ ),
+ SizedBox(width: inset),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ kShowModels,
+ style: AppType.label(color: AppColors.text),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ kShowModelsWait,
+ style: AppType.monoMeta(color: AppColors.mutedStrong),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+}
+
+/// "Switch anyway?" before moving an agent onto [model], every computer serving which seems
+/// offline. True only for the button that says so; Cancel, Escape and a click outside all leave
+/// the agent where it is. The move itself is never refused — the daemon can be wrong about a
+/// computer — but an agent moved there will not answer until it is back.
+Future<bool> confirmSwitchAnyway(
+ BuildContext context, {
+ required String model,
+ required GridModelUnavailable offline,
+}) async =>
+ await showAppDialog<bool>(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: const Text(kSwitchAnyway),
+ content: SizedBox(
+ width: 360,
+ child: Text(
+ offlineNoteSentence(offline.machine, model),
+ style: AppType.body(color: AppColors.textSoft, height: 1.4),
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context, false),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(context, true),
+ child: const Text(kSwitchAnywayAction),
+ ),
+ ],
+ ),
+ ) ??
+ false;
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index b4e3f97c9..e977bbceb 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -14,7 +14,9 @@ import 'package:flutter/services.dart';
import 'package:xterm/xterm.dart';
import '../clipboard/native_clipboard.dart';
+import '../core/models.dart';
import '../state/app_state.dart';
+import '../state/model_start_watch.dart';
import 'agent_drag.dart';
import 'rename_agent_dialog.dart';
@@ -38,10 +40,16 @@ import '../theme/app_theme.dart';
import 'engine_identity.dart';
import 'grid_model_picker.dart';
import 'pane_header_actions.dart';
+import 'pane_model_status.dart';
/// The pane header's own horizontal inset.
const double _stripPadding = 14;
+/// What sits in a header row beside a status: the engine mark (17) and its gap (10), the gap
+/// before the status (8), and the gap and link badge after the row (8 + 18). The "Starting up…"
+/// chip is never given more than the row's room less these.
+const double _headerFurniture = 17 + 10 + 8 + 8 + 18;
+
typedef TerminalNotice = ({
String label,
String detail,
@@ -232,6 +240,16 @@ class _TerminalPanelState extends State<TerminalPanel>
Object? _headerPresentation;
Widget? _header;
+ /// Opens this pane's model picker from outside its header — the model note's "Pick another".
+ final ModelPickerOpener _pickerOpener = ModelPickerOpener();
+
+ /// What this pane's "Starting up…" chip said at the last build, so a change for another agent's
+ /// pane does not rebuild this one. See [ModelStartWatch].
+ ModelStartPhase? _startPhase;
+
+ /// Whether the model note holds a line under the header — see [_syncNoteLine].
+ bool _noted = false;
+
/// Set while the in-pane control banner is answering a keystroke that went
/// nowhere (see [_nudgeControlBanner]); cleared by [_controlNudgeTimer].
bool _controlNudged = false;
@@ -267,9 +285,26 @@ class _TerminalPanelState extends State<TerminalPanel>
// they still need a rebuild to reach it, and this widget reads the store
// directly rather than through a builder.
terminalThemeStore.addListener(_onFontChanged);
+ widget.notifier.modelStarts.addListener(_onModelStartsChanged);
+ _startPhase = _startPhaseNow();
+ _noted = _gridNote() != null;
_afterTerminalMounted();
}
+ ModelStartPhase? _startPhaseNow() => widget.notifier.modelStarts.phaseOf(
+ widget.session.machineId,
+ widget.session.agentId,
+ );
+
+ /// The chip is driven by timers and turn events, neither of which rebuilds the pane grid — so
+ /// the pane listens for it itself, and rebuilds only when ITS phase moved.
+ void _onModelStartsChanged() {
+ if (!mounted) return;
+ final phase = _startPhaseNow();
+ if (phase == _startPhase) return;
+ setState(() => _startPhase = phase);
+ }
+
@override
void didChangeDependencies() {
super.didChangeDependencies();
@@ -318,6 +353,12 @@ class _TerminalPanelState extends State<TerminalPanel>
@override
void didUpdateWidget(TerminalPanel oldWidget) {
super.didUpdateWidget(oldWidget);
+ if (!identical(oldWidget.notifier, widget.notifier)) {
+ oldWidget.notifier.modelStarts.removeListener(_onModelStartsChanged);
+ widget.notifier.modelStarts.addListener(_onModelStartsChanged);
+ }
+ _startPhase = _startPhaseNow();
+ _syncNoteLine();
if (!identical(oldWidget.session, widget.session)) {
_closeFind(restore: false, focus: false, rebuild: false);
_clearLastFind();
@@ -404,6 +445,8 @@ class _TerminalPanelState extends State<TerminalPanel>
widget.session.detachViewport(this);
terminalFontStore.removeListener(_onFontChanged);
terminalThemeStore.removeListener(_onFontChanged);
+ widget.notifier.modelStarts.removeListener(_onModelStartsChanged);
+ _pickerOpener.dispose();
_cancelDialInertia();
_cursorBlinkTimer?.cancel();
_controlNudgeTimer?.cancel();
@@ -1614,6 +1657,7 @@ class _TerminalPanelState extends State<TerminalPanel>
// Goes with the row above it: the phone draws its own rule under
// [PhoneHeader], and keeping this one would stack two.
if (widget.showHeader) Divider(height: 1, color: AppColors.border),
+ ?_modelNote(),
Expanded(
// Any press into the pane's body — the terminal, the band, its
// scrollbar; not the header, which is chrome — is the person
@@ -1770,6 +1814,42 @@ class _TerminalPanelState extends State<TerminalPanel>
);
}
+ /// This agent's model note (`grid.note`), or null when nothing is wrong. Read from the app's
+ /// agents, which the pane grid rebuilds this panel on.
+ GridNote? _gridNote() => widget.notifier
+ .stateOf(widget.session.machineId)
+ ?.agents
+ .where((agent) => agent.id == widget.session.agentId)
+ .firstOrNull
+ ?.gridNote;
+
+ /// The note taking or giving back its line resizes the terminal, so the pane re-measures then,
+ /// as it does when the composer comes or goes.
+ void _syncNoteLine() {
+ final noted = _gridNote() != null;
+ if (noted == _noted) return;
+ _noted = noted;
+ _afterTerminalMounted(claimFocus: false, scrollToEnd: false);
+ }
+
+ /// The note under the header while the daemon says this agent's model will not answer, or null.
+ ///
+ /// In flow rather than over the output, like the composer: a note can stand for hours, and a
+ /// band that long over the top rows would hide what the agent last said. "Pick another" is
+ /// offered only where the header has a picker to open.
+ Widget? _modelNote() {
+ final note = _gridNote();
+ if (note == null) return null;
+ final hasPicker =
+ widget.showHeader &&
+ !widget.readOnly &&
+ modelPickerSupports(widget.session.engineId);
+ return PaneModelNote(
+ note: note,
+ onPickAnother: hasPicker ? _pickerOpener.open : null,
+ );
+ }
+
/// Visibility and focus affect the renderer, not its title and controls.
/// Retain that subtree until its presentation changes. Callback wrappers
/// resolve the current widget so cached controls never retain an old action.
@@ -1811,6 +1891,7 @@ class _TerminalPanelState extends State<TerminalPanel>
zoom: widget.onToggleZoom != null,
dragId: widget.paneDrag?.ref.paneId,
dragSize: widget.paneDrag?.size,
+ starting: _startPhase,
);
if (_headerPresentation != presentation) {
_headerPresentation = presentation;
@@ -1838,6 +1919,8 @@ class _TerminalPanelState extends State<TerminalPanel>
? null
: () => widget.onToggleComposer?.call(),
paneDrag: widget.paneDrag,
+ starting: _startPhase,
+ pickerOpener: _pickerOpener,
);
}
return _header!;
@@ -1876,6 +1959,14 @@ class _TerminalHeader extends StatelessWidget {
/// share one drag. The window is moved from HarnessTopBar now.
final PaneDragHandle? paneDrag;
+ /// What the "Starting up…" chip says, or null when this pane is not waiting on a resting model.
+ /// Drawn where the status chip goes, and only when there is no status: "Connecting" or
+ /// "Reconnect" is the more urgent thing to know.
+ final ModelStartPhase? starting;
+
+ /// Opens this pane's model picker from the model note — see [GridModelPicker.openRequests].
+ final Listenable? pickerOpener;
+
const _TerminalHeader({
required this.notifier,
required this.session,
@@ -1892,6 +1983,8 @@ class _TerminalHeader extends StatelessWidget {
this.paneDrag,
this.onToggleComposer,
this.composerVisible = false,
+ this.starting,
+ this.pickerOpener,
});
@override
@@ -1956,6 +2049,7 @@ class _TerminalHeader extends StatelessWidget {
session.status == TerminalSessionStatus.closed ||
session.status == TerminalSessionStatus.takenOver);
final statusAction = noticeAction ?? (canReconnect ? onReconnect : null);
+ final starting = status == null ? this.starting : null;
final machine = notifier.stateOf(session.machineId);
final agent = machine?.agents
.where((a) => a.id == session.agentId)
@@ -2019,8 +2113,16 @@ class _TerminalHeader extends StatelessWidget {
)..layout();
final width = name.width;
name.dispose();
+ final statusRoom = status != null
+ ? 120.0
+ : starting != null
+ ? paneStartingChipWidth(
+ starting,
+ MediaQuery.textScalerOf(context),
+ )
+ : 16.0;
return math.min(
- 17 + 10 + width + 8 + (status == null ? 16 : 120) + 8,
+ 17 + 10 + width + 8 + statusRoom + 8,
constraints.maxWidth * .45,
);
}
@@ -2076,7 +2178,7 @@ class _TerminalHeader extends StatelessWidget {
),
),
),
- if (status != null || !compact)
+ if (status != null || starting != null || !compact)
const SizedBox(width: 8),
if (status != null && narrow)
Tooltip(
@@ -2150,6 +2252,28 @@ class _TerminalHeader extends StatelessWidget {
),
),
)
+ else if (starting != null && narrow)
+ PaneStartingChip(phase: starting, narrow: true)
+ else if (starting != null)
+ // Never wider than the room this row is sure to have: the name's
+ // share (at most 45%) or what the actions and the PR badge leave —
+ // less [_headerFurniture]. Its words shorten rather than push the
+ // row past the header's edge.
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: math.max(
+ 0,
+ math.min(
+ constraints.maxWidth * .45 - _headerFurniture,
+ constraints.maxWidth -
+ actionsWidth -
+ badgeWidth -
+ _headerFurniture,
+ ),
+ ),
+ ),
+ child: PaneStartingChip(phase: starting),
+ )
else if (!compact)
Padding(
padding: const EdgeInsets.all(4),
@@ -2204,6 +2328,7 @@ class _TerminalHeader extends StatelessWidget {
currentModel: agent?.gridModel,
webSearch: agent?.gridWebSearch,
engineLabel: session.engineId,
+ openRequests: pickerOpener,
onSelected: (model) => unawaited(
notifier.retargetAgentToGridModel(
session.machineId,
diff --git a/desktop/test/pane_model_status_test.dart b/desktop/test/pane_model_status_test.dart
new file mode 100644
index 000000000..f1f8990e3
--- /dev/null
+++ b/desktop/test/pane_model_status_test.dart
@@ -0,0 +1,334 @@
+// The pane saying what its model is doing (grid-reads-without-waking, issue 03): the chip from a
+// message sent to a resting model until its first output, and the note on an agent whose model is
+// not answering — and, for an agent whose frame says neither, the header it always had.
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/model_start_watch.dart';
+import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/widgets/terminal_panel.dart';
+
+import 'support/real_fonts.dart';
+import 'support/resting_models.dart';
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ setUpAll(loadRealFonts);
+
+ late AppNotifier app;
+ late RecordingDaemon daemon;
+ late TerminalSession session;
+
+ /// A pane on agent `agent-1`, whose frame's `grid` block is [grid].
+ Future<void> pane(
+ WidgetTester tester,
+ Map<String, Object?> grid, {
+ double width = 900,
+ String name = 'Desktop',
+ }) async {
+ tester.view.physicalSize = const Size(1200, 800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ daemon = RecordingDaemon(
+ modelsReply([
+ section('home', own: true, models: [row('Gemma-4-12B', 'macbook')]),
+ ]),
+ );
+ app = createApp(connectionForTest: (_) => daemon);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [_agent(grid)];
+ session =
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'agent-1',
+ agentName: name,
+ engineId: 'codex',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream-1';
+ addTearDown(session.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SizedBox(
+ width: width,
+ height: 320,
+ // Rebuilt on every change to the app, as the pane grid rebuilds it.
+ child: ListenableBuilder(
+ listenable: app,
+ builder: (context, _) =>
+ TerminalPanel(notifier: app, session: session, focused: true),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ }
+
+ /// The daemon re-pushing the agent with [grid] (`agent_synced`) — as it does when the state or
+ /// the note of its model's grid moves.
+ Future<void> agentSays(WidgetTester tester, Map<String, Object?> grid) async {
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {'agent': _json(grid)},
+ });
+ await tester.pump();
+ }
+
+ Future<void> event(
+ WidgetTester tester,
+ String type, {
+ Map<String, Object?> payload = const {},
+ bool replay = false,
+ }) async {
+ await app.handleEventForTest('m', {
+ 'type': type,
+ 'agentId': 'agent-1',
+ 'payload': payload,
+ if (replay) 'replay': true,
+ });
+ await tester.pump();
+ }
+
+ /// Let the turn's own watchdog (12 s) run out, so no timer outlives the test.
+ Future<void> settle(WidgetTester tester) =>
+ tester.pump(const Duration(seconds: 13));
+
+ testWidgets('an agent whose frame says neither keeps the header it had', (
+ tester,
+ ) async {
+ await pane(tester, {'model': 'Qwen3.5-4B', 'webSearch': 'on'});
+ // What the build before this one drew for this very frame, captured from it.
+ expect(textsUnder(tester), ['Desktop', 'Qwen3.5-4B', 'Test host']);
+ await event(tester, 'turn_started', payload: {'userMessage': 'hi'});
+ expect(textsUnder(tester), ['Desktop', 'Qwen3.5-4B', 'Test host']);
+ await settle(tester);
+ });
+
+ testWidgets(
+ 'a message to a resting model says Starting up… until the first output',
+ (tester) async {
+ await pane(tester, {'model': 'Qwen3.5-4B', 'state': 'asleep'});
+ expect(find.text('Starting up…'), findsNothing);
+
+ await event(tester, 'turn_started', payload: {'userMessage': 'hi'});
+ expect(find.text('Starting up…'), findsOneWidget);
+ expect(saysGrid, findsNothing);
+
+ // The terminal echoing the prompt and drawing its spinner is not the model answering.
+ session.terminal.write('hi\r\n⠋ Working');
+ await tester.pump();
+ expect(find.text('Starting up…'), findsOneWidget);
+ // Nor is the grid coming up: the chip is about THIS message's answer.
+ await agentSays(tester, {'model': 'Qwen3.5-4B', 'state': 'awake'});
+ expect(find.text('Starting up…'), findsOneWidget);
+
+ await tester.pump(kStillStartingAfter);
+ expect(find.text('Starting up…'), findsNothing);
+ expect(
+ find.text('Still starting — this can take up to a minute'),
+ findsOneWidget,
+ );
+ expect(saysGrid, findsNothing);
+
+ await event(tester, 'text_delta', payload: {'content': 'Hello'});
+ expect(
+ find.text('Still starting — this can take up to a minute'),
+ findsNothing,
+ );
+ expect(find.text('Starting up…'), findsNothing);
+ await settle(tester);
+ },
+ );
+
+ // A reasoning model's first output is its thinking, long before any text — and every other kind
+ // of output the CLI's normalizers emit for a turn counts the same way.
+ for (final kind in [
+ 'thinking_delta',
+ 'thinking_title',
+ 'tool_end',
+ 'subagent_finished',
+ 'done',
+ ]) {
+ testWidgets('$kind is the model answering', (tester) async {
+ await pane(tester, {'model': 'Qwen3.5-4B', 'state': 'asleep'});
+ await event(tester, 'turn_started', payload: {'userMessage': 'hi'});
+ expect(find.text('Starting up…'), findsOneWidget);
+ await event(tester, kind, payload: {'content': 'Let me think'});
+ expect(find.text('Starting up…'), findsNothing);
+ await settle(tester);
+ });
+ }
+
+ testWidgets('a sub-agent starting its own turn is not a message sent here', (
+ tester,
+ ) async {
+ await pane(tester, {'model': 'Qwen3.5-4B', 'state': 'asleep'});
+ app.machineStates['m']!.agents = [
+ Agent.fromJson({
+ ..._json({'model': 'Qwen3.5-4B', 'state': 'asleep'}),
+ 'sessionId': 'own',
+ }),
+ ];
+ await app.handleEventForTest('m', {
+ 'type': 'turn_started',
+ 'agentId': 'agent-1',
+ 'dbSessionId': 'a-sub-agent',
+ 'payload': {'userMessage': 'specialist task'},
+ });
+ await tester.pump();
+ expect(find.text('Starting up…'), findsNothing);
+ await settle(tester);
+ });
+
+ testWidgets('a tool call is output too, and so is the turn ending', (
+ tester,
+ ) async {
+ await pane(tester, {'model': 'Qwen3.5-4B', 'state': 'waking'});
+ await event(tester, 'turn_started', payload: {'userMessage': 'hi'});
+ expect(find.text('Starting up…'), findsOneWidget);
+ await event(tester, 'tool_start', payload: {'id': 't', 'tool': 'Read'});
+ expect(find.text('Starting up…'), findsNothing);
+ await settle(tester);
+
+ await event(tester, 'turn_started', payload: {'userMessage': 'again'});
+ expect(find.text('Starting up…'), findsOneWidget);
+ await app.handleEventForTest('m', {
+ 'type': 'turn_ended',
+ 'agentId': 'agent-1',
+ 'payload': const <String, dynamic>{},
+ });
+ await tester.pump();
+ expect(find.text('Starting up…'), findsNothing);
+ await tester.pump(const Duration(minutes: 1));
+ });
+
+ testWidgets(
+ 'no chip for an awake model, a daemon that did not say, or a replayed turn',
+ (tester) async {
+ await pane(tester, {'model': 'Qwen3.5-4B', 'state': 'awake'});
+ await event(tester, 'turn_started', payload: {'userMessage': 'hi'});
+ expect(find.text('Starting up…'), findsNothing);
+
+ await agentSays(tester, {'model': 'Qwen3.5-4B'});
+ await event(tester, 'turn_started', payload: {'userMessage': 'hi'});
+ expect(find.text('Starting up…'), findsNothing);
+
+ // A turn picked back up at attach is not a message sent now.
+ await agentSays(tester, {'model': 'Qwen3.5-4B', 'state': 'asleep'});
+ await event(
+ tester,
+ 'turn_started',
+ payload: {'userMessage': 'hi'},
+ replay: true,
+ );
+ expect(find.text('Starting up…'), findsNothing);
+ await settle(tester);
+ },
+ );
+
+ for (final width in [420.0, 600.0, 760.0, 900.0, 1100.0]) {
+ testWidgets('the chip fits a header $width wide, beside a long name', (
+ tester,
+ ) async {
+ await pane(
+ tester,
+ {'model': 'Qwen3.6-35B-A3B-UD-Q5_K_XL', 'state': 'asleep'},
+ width: width,
+ name: 'A harness with a very long name indeed, for the header',
+ );
+ await event(tester, 'turn_started', payload: {'userMessage': 'hi'});
+ await tester.pump(kStillStartingAfter);
+ expect(tester.takeException(), isNull);
+ // A narrow header draws the chip's mark and says the words on hover, as it does its status.
+ expect(
+ width < 560
+ ? find.byTooltip(
+ 'Still starting — this can take up to a minute\n'
+ 'Resting to save resources. It starts by itself when you send a message.',
+ )
+ : find.text('Still starting — this can take up to a minute'),
+ findsOneWidget,
+ );
+ await event(tester, 'text_delta', payload: {'content': 'Hello'});
+ await settle(tester);
+ });
+ }
+
+ testWidgets('the chip never outlives its cap', (tester) async {
+ await pane(tester, {'model': 'Qwen3.5-4B', 'state': 'asleep'});
+ await event(tester, 'turn_started', payload: {'userMessage': 'hi'});
+ await tester.pump(kStartWatchCap - const Duration(seconds: 1));
+ expect(
+ find.text('Still starting — this can take up to a minute'),
+ findsOneWidget,
+ );
+ await tester.pump(const Duration(seconds: 1));
+ expect(
+ find.text('Still starting — this can take up to a minute'),
+ findsNothing,
+ );
+ expect(find.text('Starting up…'), findsNothing);
+ });
+
+ testWidgets(
+ "a model no longer served says so, and Pick another opens this pane's picker",
+ (tester) async {
+ await pane(tester, {
+ 'model': 'Qwen3.5-4B',
+ 'state': 'awake',
+ 'note': {'reason': 'not_served', 'model': 'Qwen3.5-4B'},
+ });
+ expect(
+ find.textContaining("Qwen3.5-4B isn't being served right now"),
+ findsOneWidget,
+ );
+ expect(find.text('Pick another'), findsOneWidget);
+ expect(saysGrid, findsNothing);
+
+ await tester.tap(find.text('Pick another'));
+ await tester.pumpAndSettle();
+ // The pane's own model picker, open on its models.
+ expect(find.text('SUBSCRIPTION'), findsOneWidget);
+ expect(find.text('Gemma-4-12B'), findsOneWidget);
+ },
+ );
+
+ testWidgets('a model whose computer seems offline says until when', (
+ tester,
+ ) async {
+ await pane(tester, {
+ 'model': 'Qwen3.5-4B',
+ 'state': 'asleep',
+ 'note': {'reason': 'offline', 'model': 'Qwen3.5-4B', 'machine': 'Studio'},
+ });
+ expect(
+ find.text(
+ "Studio seems offline — Qwen3.5-4B won't answer until it's back",
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Pick another'), findsNothing);
+ expect(saysGrid, findsNothing);
+
+ // Cleared by the daemon re-pushing the agent once the model is served again.
+ await agentSays(tester, {'model': 'Qwen3.5-4B', 'state': 'awake'});
+ expect(find.textContaining('seems offline'), findsNothing);
+ // The note gave its line back to the terminal, which tells the machine its new size.
+ await tester.pump(const Duration(milliseconds: 100));
+ });
+}
+
+Map<String, Object?> _json(Map<String, Object?> grid) => {
+ 'id': 'agent-1',
+ 'name': 'Desktop',
+ 'engine': 'codex',
+ 'terminal': {'available': true},
+ 'grid': grid,
+};
+
+Agent _agent(Map<String, Object?> grid) => Agent.fromJson(_json(grid));
diff --git a/desktop/test/resting_model_picker_test.dart b/desktop/test/resting_model_picker_test.dart
new file mode 100644
index 000000000..20e6d60dd
--- /dev/null
+++ b/desktop/test/resting_model_picker_test.dart
@@ -0,0 +1,361 @@
+// The pane picker saying what a resting computer is doing (grid-reads-without-waking, issue 03):
+// each state of the contract's table, the "Show models" wake, and the "Switch anyway?" gate on a
+// row whose computers seem offline — and, with a daemon that sends none of it, the menu it always
+// drew.
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/grid_model_picker.dart';
+import 'package:harness/widgets/model_picker_chrome.dart';
+
+import 'support/real_fonts.dart';
+import 'support/resting_models.dart';
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ setUpAll(loadRealFonts);
+
+ late RecordingDaemon daemon;
+ late AppNotifier app;
+
+ void serve(List<Map<String, Object?>> grids) {
+ daemon = RecordingDaemon(modelsReply(grids));
+ app = createApp(connectionForTest: (_) => daemon);
+ addTearDown(app.dispose);
+ }
+
+ Future<void> open(
+ WidgetTester tester, {
+ String? currentModel,
+ ValueChanged<GridModel>? onSelected,
+ }) async {
+ tester.view.physicalSize = const Size(1200, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Center(
+ child: GridModelPicker(
+ notifier: app,
+ machineId: 'm',
+ engineLabel: 'claude',
+ currentModel: currentModel,
+ onSelected: onSelected,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.tap(find.byType(GridModelPicker));
+ await tester.pumpAndSettle();
+ }
+
+ double top(WidgetTester tester, Finder finder) =>
+ tester.getTopLeft(finder).dy;
+
+ testWidgets('with no new field the menu is exactly the one it always was', (
+ tester,
+ ) async {
+ // What the build before this one drew for this very answer, text for text, captured from it.
+ serve([
+ section(
+ 'home',
+ own: true,
+ models: [
+ row('Qwen3.5-4B', 'macbook'),
+ // An older daemon folds the label into the node; this build shows it as it comes.
+ row('LFM2.5-8B', 'studio · seems offline'),
+ ],
+ ),
+ section('team', models: [row('DeepSeek-V4-Flash', 'scholes-60001')]),
+ section('empty-team'),
+ ]);
+ await open(tester, currentModel: 'Qwen3.5-4B');
+ expect(textsUnder(tester), [
+ 'Qwen3.5-4B',
+ 'Search models or machines',
+ 'SUBSCRIPTION',
+ 'Anthropic',
+ 'Checking usage…',
+ 'ON YOUR MACHINES',
+ '2',
+ 'Qwen3.5-4B',
+ 'macbook',
+ 'LFM2.5-8B',
+ 'studio · seems offline',
+ 'SHARED · TEAM',
+ '1',
+ 'DeepSeek-V4-Flash',
+ 'scholes-60001',
+ '3 models available',
+ 'Local models',
+ ]);
+ // No row is greyed and no pick is gated: nothing said any of them was offline.
+ for (final row in tester.widgetList<ModelPickerRow>(
+ find.byType(ModelPickerRow),
+ )) {
+ expect(row.dimmed, isFalse);
+ }
+ });
+
+ testWidgets('every read the picker makes asks for row state', (tester) async {
+ serve([
+ section('home', own: true, models: [row('Qwen3.5-4B', 'macbook')]),
+ ]);
+ await open(tester);
+ expect(daemon.asks, isNotEmpty);
+ for (final ask in daemon.asks) {
+ expect(ask, {'rowState': true});
+ }
+ });
+
+ testWidgets(
+ 'an asleep section says so under its heading, with the list age and why',
+ (tester) async {
+ serve([
+ section(
+ 'home',
+ own: true,
+ state: 'asleep',
+ lastKnownAge: 9 * 3600 + 120,
+ models: [row('Qwen3.5-4B', 'macbook')],
+ ),
+ ]);
+ await open(tester);
+ const subtitle =
+ 'Asleep · starts when you send a message (about 10–30 s) · list from 9 h ago';
+ expect(find.text(subtitle), findsOneWidget);
+ expect(
+ find.byTooltip(
+ 'Resting to save resources. It starts by itself when you send a message.',
+ ),
+ findsOneWidget,
+ );
+ // Under the heading, above the list it describes — and the list is still there to pick from.
+ expect(
+ top(tester, find.text('ON YOUR MACHINES')) <
+ top(tester, find.text(subtitle)),
+ isTrue,
+ );
+ expect(
+ top(tester, find.text(subtitle)) < top(tester, find.text('Qwen3.5-4B')),
+ isTrue,
+ );
+ expect(saysGrid, findsNothing);
+ },
+ );
+
+ testWidgets(
+ 'a section with no record offers Show models, and it wakes just that section',
+ (tester) async {
+ serve([
+ section('home', own: true, models: [row('Qwen3.5-4B', 'macbook')]),
+ section('team', state: 'asleep'),
+ ]);
+ await open(tester);
+ // A shared section that lists nothing is drawn while it has something to offer.
+ expect(find.text('SHARED · TEAM'), findsOneWidget);
+ expect(find.text('Show models'), findsOneWidget);
+ expect(find.text('usually 15–40 s'), findsOneWidget);
+ expect(saysGrid, findsNothing);
+
+ daemon.wakeReply = modelsReply([
+ section('home', own: true, models: [row('Qwen3.5-4B', 'macbook')]),
+ section('team', state: 'waking'),
+ ]);
+ daemon.reply = daemon.wakeReply!;
+ await tester.tap(find.text('Show models'));
+ await tester.pump();
+ await tester.pump();
+
+ expect(daemon.asks.last, {
+ 'rowState': true,
+ 'wake': ['team'],
+ });
+ // The menu stays open and says what is happening.
+ expect(find.text('Show models'), findsNothing);
+ expect(find.text('Starting up… usually 15–40 s'), findsOneWidget);
+
+ // The outcome: the section wakes with its models, found by asking again.
+ daemon.reply = modelsReply([
+ section('home', own: true, models: [row('Qwen3.5-4B', 'macbook')]),
+ section(
+ 'team',
+ state: 'awake',
+ models: [row('DeepSeek-V4-Flash', 'scholes-60001')],
+ ),
+ ]);
+ await tester.pump(const Duration(seconds: 5));
+ await tester.pump();
+ expect(find.text('DeepSeek-V4-Flash'), findsOneWidget);
+ expect(find.text('Starting up… usually 15–40 s'), findsNothing);
+ // Nothing waking any more: the follow-up ends, leaving no timer behind.
+ await tester.pump(const Duration(seconds: 10));
+ },
+ );
+
+ testWidgets('an empty record says nobody was serving', (tester) async {
+ serve([
+ section('home', own: true, models: [row('Qwen3.5-4B', 'macbook')]),
+ section('team', state: 'asleep', lastKnownAge: 3600),
+ ]);
+ await open(tester);
+ expect(find.text('SHARED · TEAM'), findsOneWidget);
+ expect(
+ find.text('Nobody was serving here when it went to sleep'),
+ findsOneWidget,
+ );
+ expect(find.text('Show models'), findsNothing);
+ expect(saysGrid, findsNothing);
+ });
+
+ testWidgets('a section not answering says so above its last known list', (
+ tester,
+ ) async {
+ serve([
+ section(
+ 'home',
+ own: true,
+ state: 'unknown',
+ seenAt: '2026-09-24T08:00:00.000Z',
+ lastKnownAge: 600,
+ models: [row('Qwen3.5-4B', 'macbook')],
+ ),
+ ]);
+ await open(tester);
+ expect(find.text('Not answering right now'), findsOneWidget);
+ expect(
+ top(tester, find.text('Not answering right now')) <
+ top(tester, find.text('Qwen3.5-4B')),
+ isTrue,
+ );
+ expect(saysGrid, findsNothing);
+ });
+
+ testWidgets('a section starting up says so', (tester) async {
+ serve([section('home', own: true, state: 'waking')]);
+ await open(tester);
+ expect(find.text('Starting up… usually 15–40 s'), findsOneWidget);
+ // Not the empty own section's invitation: this one is not empty, it is starting.
+ expect(
+ find.text('Set up your first local model on this computer.'),
+ findsNothing,
+ );
+ expect(saysGrid, findsNothing);
+ });
+
+ testWidgets('a wake that showed nothing says how it ended', (tester) async {
+ serve([
+ section('home', own: true, state: 'asleep', wakeOutcome: 'not_started'),
+ section('team', state: 'asleep', wakeOutcome: 'not_started'),
+ section('lab', state: 'awake', wakeOutcome: 'nobody_serving'),
+ ]);
+ await open(tester);
+ expect(
+ find.text(
+ "Couldn't start your models right now — it will start on your next message",
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.text(
+ "Couldn't start team right now — it will start on your next message",
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.text('Nobody is serving a model here right now'),
+ findsOneWidget,
+ );
+ // An outcome is the answer to the click; the row that asked is not offered again beside it.
+ expect(find.text('Show models'), findsNothing);
+ expect(saysGrid, findsNothing);
+ });
+
+ group('a row whose computers seem offline', () {
+ List<Map<String, Object?>> grids() => [
+ section(
+ 'home',
+ own: true,
+ state: 'asleep',
+ lastKnownAge: 120,
+ models: [
+ row('Qwen3.5-4B', 'macbook'),
+ row('LFM2.5-8B', 'studio', offlineMachine: 'Studio'),
+ ],
+ ),
+ ];
+
+ ModelPickerRow rowOf(WidgetTester tester, String id) =>
+ tester.widget<ModelPickerRow>(
+ find.ancestor(
+ of: find.text(id),
+ matching: find.byType(ModelPickerRow),
+ ),
+ );
+
+ testWidgets('is greyed and says why, and is never removed', (tester) async {
+ serve(grids());
+ await open(tester);
+ expect(find.text('LFM2.5-8B'), findsOneWidget);
+ expect(
+ find.text('Studio seems offline — its models come back when it does'),
+ findsOneWidget,
+ );
+ expect(rowOf(tester, 'LFM2.5-8B').dimmed, isTrue);
+ expect(rowOf(tester, 'Qwen3.5-4B').dimmed, isFalse);
+ // The node stays a node: the label is not folded into it.
+ expect(find.text('studio'), findsOneWidget);
+ expect(saysGrid, findsNothing);
+ });
+
+ testWidgets('asks "Switch anyway?" — and Cancel moves nothing', (
+ tester,
+ ) async {
+ serve(grids());
+ GridModel? picked;
+ await open(tester, onSelected: (model) => picked = model);
+ await tester.tap(find.text('LFM2.5-8B'));
+ await tester.pumpAndSettle();
+ expect(find.text('Switch anyway?'), findsOneWidget);
+ expect(saysGrid, findsNothing);
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(find.text('Switch anyway?'), findsNothing);
+ expect(picked, isNull);
+ // The control says nothing moved.
+ expect(find.text('Switching…'), findsNothing);
+ });
+
+ testWidgets('and Switch moves the agent as any pick does', (tester) async {
+ serve(grids());
+ GridModel? picked;
+ await open(tester, onSelected: (model) => picked = model);
+ await tester.tap(find.text('LFM2.5-8B'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Switch'));
+ await tester.pumpAndSettle();
+ expect(picked?.id, 'LFM2.5-8B');
+ expect(picked?.grid, 'home');
+ expect(find.text('Switching…'), findsOneWidget);
+ // The guess expires on its own when no frame confirms it.
+ await tester.pump(const Duration(seconds: 31));
+ });
+
+ testWidgets('a row that is fine is picked with no question', (
+ tester,
+ ) async {
+ serve(grids());
+ GridModel? picked;
+ await open(tester, onSelected: (model) => picked = model);
+ await tester.tap(find.text('Qwen3.5-4B'));
+ await tester.pumpAndSettle();
+ expect(find.text('Switch anyway?'), findsNothing);
+ expect(picked?.id, 'Qwen3.5-4B');
+ await tester.pump(const Duration(seconds: 31));
+ });
+ });
+}
diff --git a/desktop/test/resting_models_new_harness_test.dart b/desktop/test/resting_models_new_harness_test.dart
new file mode 100644
index 000000000..d2d67bf4b
--- /dev/null
+++ b/desktop/test/resting_models_new_harness_test.dart
@@ -0,0 +1,80 @@
+// New Harness lists the same rows as the pane picker (grid-reads-without-waking, issue 03). Every
+// read now asks for row state, so the daemon labels a row whose computers seem offline with
+// `unavailable` rather than folding the label into its node — and New Harness still says so, in the
+// daemon's own words for a client that does not ask: the computer as the Machines list names it
+// ("Studio"), which is not the node ("studio").
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/new_harness.dart';
+
+import 'support/mixed_agents.dart';
+import 'support/resting_models.dart';
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ Future<List<String>> details(Map<String, dynamic> reply) async {
+ final daemon = RecordingDaemon({
+ ...reply,
+ 'localModelEngines': ['codex'],
+ });
+ final app = createApp(connectionForTest: (_) => daemon);
+ addTearDown(app.dispose);
+ seedMixedAgents(app);
+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/scene',
+ );
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.model);
+ await box.refreshModels();
+ return box.options
+ .where((option) => option.model != null)
+ .map((option) => option.detail)
+ .toList();
+ }
+
+ test('a row whose computers seem offline still says so', () async {
+ expect(
+ await details(
+ modelsReply([
+ section(
+ 'home',
+ own: true,
+ models: [
+ row('Qwen3.5-4B', 'macbook'),
+ row('LFM2.5-8B', 'studio', offlineMachine: 'Studio'),
+ ],
+ ),
+ ]),
+ ),
+ ['macbook', 'Studio · seems offline'],
+ );
+ });
+
+ test(
+ 'an older daemon that folded the label into the node reads as before',
+ () async {
+ expect(
+ await details(
+ modelsReply([
+ section(
+ 'home',
+ own: true,
+ models: [
+ row('Qwen3.5-4B', 'macbook'),
+ // What the daemon sends a client that did not ask for row state, for the
+ // row above.
+ row('LFM2.5-8B', 'Studio · seems offline'),
+ ],
+ ),
+ ]),
+ ),
+ ['macbook', 'Studio · seems offline'],
+ );
+ },
+ );
+}
diff --git a/desktop/test/resting_models_panel_test.dart b/desktop/test/resting_models_panel_test.dart
new file mode 100644
index 000000000..f6941aff6
--- /dev/null
+++ b/desktop/test/resting_models_panel_test.dart
@@ -0,0 +1,321 @@
+// The Models panel saying what a resting computer is doing (grid-reads-without-waking, issue 03):
+// every state of the contract's table on its shared sections, "Show models", greyed offline rows,
+// and the Model Manager's row for a model parked while this computer's models rest — and, with a
+// daemon that sends none of it, the panel it always drew.
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/models/model_manager_controller.dart';
+import 'package:harness/models/models_panel.dart';
+import 'package:harness/shared/theme/app_theme.dart';
+import 'package:harness/usage/models_menu_controller.dart';
+
+import 'support/model_manager.dart';
+import 'support/real_fonts.dart';
+import 'support/resting_models.dart';
+
+class _NoSubscriptions extends ModelsMenuController {
+ @override
+ List<Map<String, Object?>> get rows => const [];
+ @override
+ Future<void> refresh() async {}
+}
+
+/// This computer's daemon, recording the `grid_models_list` asks that go to it for real — the
+/// wake. The panel's plain reads go through [ModelManagerTestApp.gridModels], which answers from
+/// its `inventory`.
+class _Daemon extends ModelManagerConnection {
+ final asks = <Map<String, dynamic>>[];
+ Map<String, dynamic> wakeReply = const {};
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type != 'grid_models_list') {
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+ asks.add(Map.of(payload));
+ return wakeReply;
+ }
+}
+
+void main() {
+ setUpAll(loadRealFonts);
+
+ late _Daemon daemon;
+ late ModelManagerTestApp app;
+ late ModelManagerController controller;
+
+ Future<void> show(
+ WidgetTester tester,
+ List<Map<String, Object?>> grids, {
+ Map<String, dynamic>? local,
+ ModelsTab tab = ModelsTab.all,
+ }) async {
+ tester.view.physicalSize = const Size(900, 1600);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ daemon = _Daemon();
+ app = ModelManagerTestApp(daemon);
+ app.inventory = GridModels.fromReply(modelsReply(grids));
+ app.localInventory = local ?? modelInventory(scenario: 'ready');
+ controller = ModelManagerController(app, poll: false);
+ final subscriptions = _NoSubscriptions();
+ addTearDown(() {
+ controller.dispose();
+ subscriptions.dispose();
+ app.dispose();
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: 640,
+ child: ModelsPanel(
+ controller: controller,
+ subscriptions: subscriptions,
+ initialTab: tab,
+ onClose: () {},
+ onManage: () {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await controller.refresh(force: true);
+ await tester.pump();
+ }
+
+ double top(WidgetTester tester, Finder finder) =>
+ tester.getTopLeft(finder).dy;
+
+ testWidgets('with no new field the panel is exactly the one it always was', (
+ tester,
+ ) async {
+ // What the build before this one drew for this very answer, text for text, captured from it.
+ await show(tester, [
+ section(
+ 'home',
+ own: true,
+ models: [
+ row('Qwen3.5-4B', 'macbook'),
+ row('LFM2.5-8B', 'studio · seems offline'),
+ ],
+ ),
+ section('team', models: [row('DeepSeek-V4-Flash', 'scholes-60001')]),
+ section('empty-team'),
+ ]);
+ expect(textsUnder(tester), [
+ 'Models',
+ 'Search models…',
+ 'All 6',
+ 'Subscriptions 0',
+ 'Local 5',
+ 'Shared 1',
+ 'APIs 0',
+ 'This computer · 64 GB memory',
+ 'Qwen3.8-27B',
+ '16.2 GB · 17.6 tok/s · 42 requests / 24h',
+ 'gemma-4-12B',
+ '7.3 GB',
+ 'Qwen3.8-8B',
+ '4.8 GB',
+ 'Qwen3-Coder-30B-A3B',
+ '18.6 GB',
+ 'gpt-oss-20b',
+ '12.1 GB',
+ 'Shared · team',
+ 'DeepSeek-V4-Flash',
+ 'scholes-60001',
+ 'Select models in a session’s model picker.',
+ 'Manage models',
+ ]);
+ });
+
+ testWidgets('every state of a shared section reads as the table says', (
+ tester,
+ ) async {
+ await show(tester, [
+ section('home', own: true),
+ section(
+ 'team',
+ state: 'asleep',
+ lastKnownAge: 2 * 3600,
+ models: [
+ row('DeepSeek-V4-Flash', 'scholes-60001'),
+ row('Kimi-K2', 'zeus', offlineMachine: 'Zeus'),
+ ],
+ ),
+ section('lab', state: 'asleep'),
+ section('attic', state: 'asleep', lastKnownAge: 60),
+ section(
+ 'garage',
+ state: 'unknown',
+ seenAt: '2026-09-24T08:00:00.000Z',
+ models: [row('Gemma-4-12B', 'garage-box')],
+ ),
+ section('shed', state: 'waking'),
+ section('barn', state: 'asleep', wakeOutcome: 'not_started'),
+ section('loft', state: 'awake', wakeOutcome: 'nobody_serving'),
+ ]);
+
+ const subtitle =
+ 'Asleep · starts when you send a message (about 10–30 s) · list from 2 h ago';
+ expect(find.text(subtitle), findsOneWidget);
+ expect(
+ find.byTooltip(
+ 'Resting to save resources. It starts by itself when you send a message.',
+ ),
+ findsOneWidget,
+ );
+ expect(
+ top(tester, find.text('Shared · team')) <
+ top(tester, find.text(subtitle)),
+ isTrue,
+ );
+
+ // A section with no record is drawn, with the way to find out what it serves.
+ expect(find.text('Shared · lab'), findsOneWidget);
+ expect(find.text('Show models'), findsOneWidget);
+ expect(find.text('usually 15–40 s'), findsOneWidget);
+
+ expect(find.text('Shared · attic'), findsOneWidget);
+ expect(
+ find.text('Nobody was serving here when it went to sleep'),
+ findsOneWidget,
+ );
+
+ expect(find.text('Not answering right now'), findsOneWidget);
+ expect(
+ top(tester, find.text('Not answering right now')) <
+ top(tester, find.text('Gemma-4-12B')),
+ isTrue,
+ );
+
+ expect(find.text('Starting up… usually 15–40 s'), findsOneWidget);
+ expect(
+ find.text(
+ "Couldn't start barn right now — it will start on your next message",
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.text('Nobody is serving a model here right now'),
+ findsOneWidget,
+ );
+
+ // The offline row: still listed, greyed, and saying why.
+ expect(find.text('Kimi-K2'), findsOneWidget);
+ expect(
+ find.text('Zeus seems offline — its models come back when it does'),
+ findsOneWidget,
+ );
+ Color? ink(String text) =>
+ tester.widget<Text>(find.text(text)).style?.color;
+ expect(ink('Kimi-K2'), AppPalette.textFaint);
+ expect(ink('DeepSeek-V4-Flash'), AppPalette.textPrimary);
+
+ // Counts are models, as they always were.
+ expect(find.text('Shared 3'), findsOneWidget);
+ expect(saysGrid, findsNothing);
+
+ // A search narrows to what matches; a section with nothing matching says nothing.
+ await tester.enterText(
+ find.byKey(const ValueKey('models-search')),
+ 'DeepSeek',
+ );
+ await tester.pump();
+ expect(find.text('Show models'), findsNothing);
+ expect(find.text('Shared · lab'), findsNothing);
+ expect(find.text('DeepSeek-V4-Flash'), findsOneWidget);
+ // …and a section it kept still says what it says about its rows.
+ expect(find.text(subtitle), findsOneWidget);
+ await tester.enterText(
+ find.byKey(const ValueKey('models-search')),
+ 'Gemma',
+ );
+ await tester.pump();
+ expect(find.text('Not answering right now'), findsOneWidget);
+ expect(find.text('Gemma-4-12B'), findsOneWidget);
+ });
+
+ testWidgets('the Shared tab draws a speaking section even with no models', (
+ tester,
+ ) async {
+ await show(tester, [
+ section('home', own: true),
+ section('lab', state: 'asleep'),
+ ], tab: ModelsTab.shared);
+ expect(find.text('No shared models'), findsNothing);
+ expect(find.text('lab'), findsOneWidget);
+ expect(find.text('Show models'), findsOneWidget);
+ });
+
+ testWidgets('Show models wakes just that section, and says it is starting', (
+ tester,
+ ) async {
+ await show(tester, [
+ section('home', own: true),
+ section('lab', state: 'asleep'),
+ ]);
+ daemon.wakeReply = modelsReply([
+ section('home', own: true),
+ section('lab', state: 'waking'),
+ ]);
+ await tester.tap(find.text('Show models'));
+ await tester.pump();
+ await tester.pump();
+ expect(daemon.asks.single, {
+ 'rowState': true,
+ 'wake': ['lab'],
+ });
+ expect(find.text('Show models'), findsNothing);
+ expect(find.text('Starting up… usually 15–40 s'), findsOneWidget);
+ expect(saysGrid, findsNothing);
+
+ // It wakes with its models; the follow-up read finds them, and then stops.
+ app.inventory = GridModels.fromReply(
+ modelsReply([
+ section('home', own: true),
+ section(
+ 'lab',
+ state: 'awake',
+ models: [row('Qwen3.6-35B-A3B', 'lab-box')],
+ ),
+ ]),
+ );
+ await tester.pump(const Duration(seconds: 5));
+ await tester.pump(const Duration(seconds: 10));
+ });
+
+ testWidgets('a model parked while this computer rests says so', (
+ tester,
+ ) async {
+ final local = modelInventory(scenario: 'ready');
+ final qwen = (local['models'] as List).first as Map<String, dynamic>;
+ // What the daemon sends for a parked engine: running, no telemetry, `gridAsleep`.
+ qwen
+ ..remove('tokensPerSecond')
+ ..remove('requests')
+ ..remove('windowSeconds')
+ ..['gridAsleep'] = true;
+ await show(tester, [section('home', own: true)], local: local);
+ expect(
+ find.text('16.2 GB · Running · resting until your next message'),
+ findsOneWidget,
+ );
+ expect(saysGrid, findsNothing);
+ // Still running as far as its controls go: Pause is what it offers.
+ expect(
+ find.byTooltip(
+ 'Pause Qwen3.8-27B and free memory. The download is kept.',
+ ),
+ findsOneWidget,
+ );
+ });
+}
diff --git a/desktop/test/resting_models_test.dart b/desktop/test/resting_models_test.dart
new file mode 100644
index 000000000..073adaa85
--- /dev/null
+++ b/desktop/test/resting_models_test.dart
@@ -0,0 +1,433 @@
+// What the app reads and says about models on computers that rest to save resources
+// (grid-reads-without-waking, issue 03, desktop half): the additive fields of the wire contract,
+// the one set of sentences every surface shares, the explicit wake, and the watch behind the pane
+// chip. The surfaces themselves are in resting_model_picker_test, resting_models_panel_test and
+// pane_model_status_test.
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/models/local_model.dart';
+import 'package:harness/state/model_start_watch.dart';
+import 'package:harness/widgets/resting_model_words.dart';
+
+import 'support/resting_models.dart';
+import 'swarm_state_test.dart' show createApp;
+
+GridSection _only(Map<String, Object?> raw) =>
+ GridModels.fromReply(modelsReply([raw])).sections.single;
+
+void main() {
+ group('the additive fields', () {
+ test('a row, a section and an agent read everything issue 03 adds', () {
+ final reply = modelsReply([
+ section(
+ 'team',
+ state: 'waking',
+ wakeOutcome: 'not_started',
+ models: [row('Qwen3.6-35B-A3B', 'studio', offlineMachine: 'Studio')],
+ ),
+ ]);
+ final team = GridModels.fromReply(reply).sections.single;
+ expect(team.state, GridSectionState.waking);
+ expect(team.wakeOutcome, GridWakeOutcome.notStarted);
+ final unavailable = team.models.single.unavailable!;
+ expect(unavailable.machine, 'Studio');
+ expect(unavailable.since, DateTime.utc(2026, 9, 25, 8));
+ // The row keeps a plain node beside the label — the label is not folded into it.
+ expect(team.models.single.node, 'studio');
+
+ final agent = Agent.fromJson({
+ 'id': 'a',
+ 'name': 'Agent',
+ 'grid': {
+ 'model': 'Qwen3.6-35B-A3B',
+ 'state': 'asleep',
+ 'note': {
+ 'reason': 'offline',
+ 'model': 'Qwen3.6-35B-A3B',
+ 'machine': 'Studio',
+ },
+ },
+ });
+ expect(agent.gridState, GridSectionState.asleep);
+ expect(
+ agent.gridNote,
+ isA<GridNoteOffline>().having((n) => n.machine, 'machine', 'Studio'),
+ );
+ // A copy keeps them: a rename must not wipe the pane's note.
+ expect(
+ agent.copyWith(name: 'Renamed').gridNote?.model,
+ 'Qwen3.6-35B-A3B',
+ );
+ expect(
+ agent.copyWith(name: 'Renamed').gridState,
+ GridSectionState.asleep,
+ );
+
+ final notServed = Agent.fromJson({
+ 'id': 'a',
+ 'name': 'Agent',
+ 'grid': {
+ 'model': 'Qwen',
+ 'note': {'reason': 'not_served', 'model': 'Qwen'},
+ },
+ });
+ expect(notServed.gridNote, isA<GridNoteNotServed>());
+ expect(notServed.gridNote?.model, 'Qwen');
+
+ final parked = LocalModel.fromJson({
+ 'id': 'qwen',
+ 'name': 'Qwen',
+ 'state': 'running',
+ 'gridAsleep': true,
+ });
+ expect(parked.resting, isTrue);
+ });
+
+ test('an older daemon that sends none of them claims nothing', () {
+ final team = _only(
+ section('team', models: [row('Qwen', 'studio · seems offline')]),
+ );
+ expect(team.wakeOutcome, isNull);
+ expect(team.models.single.unavailable, isNull);
+ expect(team.models.single.node, 'studio · seems offline');
+ final agent = Agent.fromJson({
+ 'id': 'a',
+ 'name': 'Agent',
+ 'grid': {'model': 'Qwen', 'webSearch': 'on'},
+ });
+ expect(agent.gridState, isNull);
+ expect(agent.gridNote, isNull);
+ expect(
+ LocalModel.fromJson({'id': 'q', 'name': 'Q', 'state': 'running'})
+ .resting,
+ isFalse,
+ );
+ });
+
+ test('words this build has not heard of, and notes missing a name, are no claim', () {
+ final odd = _only({
+ ...section('team', wakeOutcome: 'exploded'),
+ 'models': [
+ {
+ 'id': 'Qwen',
+ 'node': 'studio',
+ 'unavailable': {'reason': 'maintenance', 'machine': 'Studio'},
+ },
+ {
+ 'id': 'Gemma',
+ 'node': 'studio',
+ 'unavailable': {'reason': 'offline'},
+ },
+ ],
+ });
+ expect(odd.wakeOutcome, isNull);
+ expect(odd.models.map((m) => m.unavailable), [isNull, isNull]);
+ for (final note in [
+ {'reason': 'offline', 'model': 'Qwen'},
+ {'reason': 'not_served'},
+ {'reason': 'melted', 'model': 'Qwen'},
+ 'offline',
+ ]) {
+ final agent = Agent.fromJson({
+ 'id': 'a',
+ 'name': 'Agent',
+ 'grid': {'model': 'Qwen', 'note': note},
+ });
+ expect(agent.gridNote, isNull, reason: '$note');
+ }
+ });
+ });
+
+ group('the words', () {
+ test('a list age reads in minutes, hours and days, rounded down', () {
+ expect(listAge(0), 'just now');
+ expect(listAge(59), 'just now');
+ expect(listAge(60), '1 min ago');
+ expect(listAge(3599), '59 min ago');
+ expect(listAge(9 * 3600 + 1800), '9 h ago');
+ expect(listAge(86399), '23 h ago');
+ expect(listAge(3 * 86400), '3 d ago');
+ });
+
+ test('each state of the contract table reads as the table says', () {
+ final served = [row('Qwen', 'studio')];
+ final asleep = sectionWords(
+ _only(
+ section(
+ 'team',
+ state: 'asleep',
+ lastKnownAge: 9 * 3600,
+ models: served,
+ ),
+ ),
+ );
+ expect(
+ asleep.subtitle,
+ 'Asleep · starts when you send a message (about 10–30 s) · list from 9 h ago',
+ );
+ expect(
+ asleep.tooltip,
+ 'Resting to save resources. It starts by itself when you send a message.',
+ );
+ expect(asleep.sentence, isNull);
+ expect(asleep.offerWake, isFalse);
+
+ final noRecord = sectionWords(_only(section('team', state: 'asleep')));
+ expect(noRecord.offerWake, isTrue);
+ expect(noRecord.sentence, isNull);
+ // The round trip of a wake this surface sent: promised at once, never offered twice.
+ final asking = sectionWords(
+ _only(section('team', state: 'asleep')),
+ asking: true,
+ );
+ expect(asking.offerWake, isFalse);
+ expect(asking.sentence, 'Starting up… usually 15–40 s');
+
+ expect(
+ sectionWords(_only(section('team', state: 'asleep', lastKnownAge: 60)))
+ .sentence,
+ 'Nobody was serving here when it went to sleep',
+ );
+ for (final known in [
+ section('team', state: 'unknown', models: served),
+ section('team', state: 'unknown', seenAt: '2026-09-24T08:00:00.000Z'),
+ section('team', state: 'unknown', lastKnownAge: 60),
+ ]) {
+ expect(sectionWords(_only(known)).sentence, 'Not answering right now');
+ }
+ // Unknown with nothing known has nothing to be "above".
+ expect(
+ sectionWords(_only(section('team', state: 'unknown'))),
+ SectionWords.none,
+ );
+ expect(
+ sectionWords(_only(section('team', state: 'waking'))).sentence,
+ 'Starting up… usually 15–40 s',
+ );
+ expect(
+ sectionWords(
+ _only(section('team', state: 'asleep', wakeOutcome: 'not_started')),
+ ).sentence,
+ "Couldn't start team right now — it will start on your next message",
+ );
+ expect(
+ sectionWords(
+ _only(
+ section(
+ 'home',
+ own: true,
+ state: 'asleep',
+ wakeOutcome: 'not_started',
+ ),
+ ),
+ ).sentence,
+ "Couldn't start your models right now — it will start on your next message",
+ );
+ expect(
+ sectionWords(
+ _only(section('team', state: 'awake', wakeOutcome: 'nobody_serving')),
+ ).sentence,
+ 'Nobody is serving a model here right now',
+ );
+ // Awake, and a daemon that sent no state at all, say nothing.
+ expect(
+ sectionWords(_only(section('team', state: 'awake', models: served))),
+ SectionWords.none,
+ );
+ expect(
+ sectionWords(_only(section('team', models: served))),
+ SectionWords.none,
+ );
+ expect(sectionWords(_only(section('team'))), SectionWords.none);
+ });
+
+ test('rows and notes', () {
+ expect(
+ offlineRowSentence('Studio'),
+ 'Studio seems offline — its models come back when it does',
+ );
+ // What the daemon itself sends a client that does not ask for row state.
+ expect(offlineNodeLabel('Studio'), 'Studio · seems offline');
+ expect(
+ noteSentence(const GridNoteOffline('Qwen', machine: 'Studio')),
+ "Studio seems offline — Qwen won't answer until it's back",
+ );
+ expect(
+ noteSentence(const GridNoteNotServed('Qwen')),
+ "Qwen isn't being served right now",
+ );
+ });
+
+ test('no sentence this adds says "grid", in any case', () {
+ const own = GridSection(name: 'home', own: true, models: []);
+ const shared = GridSection(name: 'team', own: false, models: []);
+ final every = <String>[
+ kRestingTooltip,
+ kShowModels,
+ kShowModelsWait,
+ kStartingUpWait,
+ kNobodyWasServing,
+ kNotAnswering,
+ kNobodyServing,
+ kStartingUp,
+ kStillStarting,
+ kPickAnother,
+ kSwitchAnyway,
+ kSwitchAnywayAction,
+ kRestingUntilNextMessage,
+ restingSubtitle(null),
+ for (final age in [0, 60, 3600, 86400]) restingSubtitle(age),
+ couldNotStart(own),
+ couldNotStart(shared),
+ offlineRowSentence('Studio'),
+ offlineNoteSentence('Studio', 'Qwen'),
+ offlineNodeLabel('Studio'),
+ notServedNoteSentence('Qwen'),
+ ];
+ for (final sentence in every) {
+ expect(
+ sentence.toLowerCase(),
+ isNot(contains('grid')),
+ reason: sentence,
+ );
+ }
+ });
+ });
+
+ group('the requests', () {
+ test('every read asks for row state', () async {
+ final daemon = RecordingDaemon(modelsReply([section('home', own: true)]));
+ final app = createApp(connectionForTest: (_) => daemon);
+ addTearDown(app.dispose);
+ await app.gridModels('m');
+ await app.refreshGridModels('m');
+ await app.readGridPicture('m');
+ expect(daemon.asks, isNotEmpty);
+ for (final ask in daemon.asks) {
+ expect(ask, {'rowState': true});
+ }
+ });
+
+ testWidgets(
+ 'Show models asks that one section to wake, takes the answer, and follows it to the end',
+ (tester) async {
+ final daemon = RecordingDaemon(
+ modelsReply([
+ section('home', own: true),
+ section('team', state: 'asleep'),
+ ]),
+ );
+ final app = createApp(connectionForTest: (_) => daemon);
+ addTearDown(app.dispose);
+ await app.refreshGridModels('m');
+ daemon.wakeReply = modelsReply([
+ section('home', own: true),
+ section('team', state: 'waking'),
+ ]);
+ // The daemon answers at once with the section waking; the outcome comes from asking again
+ // (a window that gets no push), which a plain read does.
+ daemon.reply = daemon.wakeReply!;
+
+ final answer = await app.wakeGridModels('m', 'team');
+ expect(daemon.asks.last, {
+ 'rowState': true,
+ 'wake': ['team'],
+ });
+ expect(answer.sections.last.state, GridSectionState.waking);
+ expect(
+ app.gridPictures['m']!.sections.last.state,
+ GridSectionState.waking,
+ );
+
+ final asked = daemon.asks.length;
+ await tester.pump(const Duration(seconds: 5));
+ expect(daemon.asks.length, asked + 1);
+ expect(daemon.asks.last, {'rowState': true});
+
+ daemon.reply = modelsReply([
+ section('home', own: true),
+ section('team', state: 'awake', models: [row('Qwen', 'studio')]),
+ ]);
+ await tester.pump(const Duration(seconds: 5));
+ expect(app.gridPictures['m']!.sections.last.models.single.id, 'Qwen');
+ // Nothing is waking any more, so nothing is asked again — and no timer is left behind.
+ final settled = daemon.asks.length;
+ await tester.pump(const Duration(seconds: 30));
+ expect(daemon.asks.length, settled);
+ },
+ );
+
+ testWidgets('a wake that cannot reach the machine is not adopted', (
+ tester,
+ ) async {
+ final daemon = RecordingDaemon(
+ modelsReply([
+ section('home', own: true),
+ section('team', state: 'asleep'),
+ ]),
+ );
+ final app = createApp(connectionForTest: (_) => daemon);
+ addTearDown(app.dispose);
+ await app.refreshGridModels('m');
+ daemon.wakeReply = {'error': 'GRID_MODELS_FAILED'};
+ final answer = await app.wakeGridModels('m', 'team');
+ expect(answer.reachable, isFalse);
+ expect(app.gridPictures['m']!.reachable, isTrue);
+ expect(
+ app.gridPictures['m']!.sections.last.state,
+ GridSectionState.asleep,
+ );
+ // Nothing is waking in the picture, so nothing follows it.
+ final asked = daemon.asks.length;
+ await tester.pump(const Duration(seconds: 30));
+ expect(daemon.asks.length, asked);
+ });
+ });
+
+ group('the start watch', () {
+ testWidgets(
+ 'starting, then still starting after a minute, then gone on output',
+ (tester) async {
+ final watch = ModelStartWatch();
+ addTearDown(watch.dispose);
+ var changes = 0;
+ watch.addListener(() => changes++);
+
+ watch.start('m', 'a');
+ expect(watch.phaseOf('m', 'a'), ModelStartPhase.starting);
+ await tester.pump(const Duration(seconds: 59));
+ expect(watch.phaseOf('m', 'a'), ModelStartPhase.starting);
+ // A second message while the first is waiting keeps the first one's clock.
+ watch.start('m', 'a');
+ await tester.pump(const Duration(seconds: 1));
+ expect(watch.phaseOf('m', 'a'), ModelStartPhase.stillStarting);
+ expect(watch.phaseOf('m', 'other'), isNull);
+
+ watch.end('m', 'a');
+ expect(watch.phaseOf('m', 'a'), isNull);
+ expect(changes, 3);
+ },
+ );
+
+ testWidgets('never outlives its cap', (tester) async {
+ final watch = ModelStartWatch();
+ addTearDown(watch.dispose);
+ watch.start('m', 'a');
+ await tester.pump(kStartWatchCap - const Duration(seconds: 1));
+ expect(watch.phaseOf('m', 'a'), ModelStartPhase.stillStarting);
+ await tester.pump(const Duration(seconds: 1));
+ expect(watch.phaseOf('m', 'a'), isNull);
+ });
+
+ testWidgets('a sign-out forgets every wait', (tester) async {
+ final watch = ModelStartWatch();
+ addTearDown(watch.dispose);
+ watch
+ ..start('m', 'a')
+ ..start('m', 'b')
+ ..clear();
+ expect(watch.phaseOf('m', 'a'), isNull);
+ expect(watch.phaseOf('m', 'b'), isNull);
+ });
+ });
+}
diff --git a/desktop/test/support/resting_models.dart b/desktop/test/support/resting_models.dart
new file mode 100644
index 000000000..ee4dc58b9
--- /dev/null
+++ b/desktop/test/support/resting_models.dart
@@ -0,0 +1,105 @@
+// Fixtures for the surfaces that say what a resting computer is doing (grid-reads-without-waking,
+// issue 03): a daemon that records every `grid_models_list` it is asked, and the JSON it answers.
+import 'package:flutter/widgets.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+/// A daemon that answers `grid_models_list` and records the payload of every ask — the thing the
+/// app actually sent, never a recomputation of it.
+class RecordingDaemon extends WsConn {
+ RecordingDaemon(this.reply)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ /// The next answer to a plain read.
+ Map<String, dynamic> reply;
+
+ /// The answer to an ask carrying `wake`, when set; a plain read's [reply] otherwise.
+ Map<String, dynamic>? wakeReply;
+
+ /// Every `grid_models_list` payload, in order.
+ final asks = <Map<String, dynamic>>[];
+
+ /// Every other request, by type — a retarget, say.
+ final others = <({String type, Map<String, dynamic> payload})>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type != 'grid_models_list') {
+ others.add((type: type, payload: Map.of(payload)));
+ return {};
+ }
+ asks.add(Map.of(payload));
+ if (payload['wake'] != null && wakeReply != null) return wakeReply!;
+ return reply;
+ }
+}
+
+/// One `grids[i]` entry. Every field issue 03 adds is optional, so an old daemon's section is this
+/// with none of them.
+Map<String, Object?> section(
+ String name, {
+ bool own = false,
+ List<Map<String, Object?>> models = const [],
+ String? state,
+ String? seenAt,
+ int? lastKnownAge,
+ String? wakeOutcome,
+}) => {
+ 'name': name,
+ 'type': own ? 'permissioned-public' : 'permissioned-providers',
+ 'own': own,
+ 'models': models,
+ 'state': ?state,
+ 'seenAt': ?seenAt,
+ 'lastKnownAge': ?lastKnownAge,
+ 'wakeOutcome': ?wakeOutcome,
+};
+
+/// One row. [offlineMachine] makes it a row whose every serving computer seems offline.
+Map<String, Object?> row(String id, String node, {String? offlineMachine}) => {
+ 'id': id,
+ 'node': node,
+ if (offlineMachine != null)
+ 'unavailable': {
+ 'reason': 'offline',
+ 'machine': offlineMachine,
+ 'since': '2026-09-25T08:00:00.000Z',
+ },
+};
+
+/// The whole `grid_models_list` document for [grids], own section first.
+Map<String, dynamic> modelsReply(List<Map<String, Object?>> grids) {
+ final own = grids.where((g) => g['own'] == true).firstOrNull;
+ return {
+ 'gridName': own?['name'] ?? 'home',
+ 'models': own?['models'] ?? const <Object?>[],
+ 'grids': grids,
+ 'supportsModelLaunch': true,
+ };
+}
+
+/// Every string drawn by a [Text] under [of] (the whole tree when null), in paint order — what a
+/// person reads, to compare a surface against what it drew before.
+List<String> textsUnder(WidgetTester tester, [Finder? of]) => tester
+ .widgetList<Text>(
+ of == null
+ ? find.byType(Text)
+ : find.descendant(of: of, matching: find.byType(Text)),
+ )
+ .map((text) => text.data ?? text.textSpan?.toPlainText() ?? '')
+ .toList();
+
+/// Matches any text a person could read that says "grid", in any case.
+final saysGrid = find.textContaining(RegExp('grid', caseSensitive: false));
diff --git a/store/agents/autonomous-grid/README.md b/store/agents/autonomous-grid/README.md
index 1f057259b..aa4d99ca4 100644
--- a/store/agents/autonomous-grid/README.md
+++ b/store/agents/autonomous-grid/README.md
@@ -50,8 +50,10 @@ Remote telemetry does not by itself grant administrative access to each serving
Harness connections use Node 22's WebSocket and bounded, noninteractive commands; use the machine's
terminal for interactive sign-in. No remote command is automatically retried after a lost connection.
- `viewer.mjs` polls `info`, `engines`, `models`, remote `stats`, and managed hosts' `device-info`.
- It serves a read-only loopback viewer and SSE updates. No credential files, full CLI output,
- arbitrary workspace files, or mutation endpoints are exposed to the browser.
+ It serves a loopback viewer and SSE updates. Its only writes are the grid to look at and **Wake
+ now** on a resting grid, which asks the Harness daemon to start it (`lib/wake.mjs`); remote reads
+ carry `--no-wake`, so nothing else the viewer does starts a grid. No credential files, full CLI
+ output, or arbitrary workspace files are exposed to the browser.
- The viewer uses only reported metrics. Local Grid currently exposes less live telemetry than
remote Grid. Missing temperature or speed reads `—`; a failed refresh preserves a visibly stale
observation. Speeds are per-engine last decode estimates, never summed into a fictional fleet rate.
diff --git a/store/agents/autonomous-grid/lib/wake.mjs b/store/agents/autonomous-grid/lib/wake.mjs
new file mode 100644
index 000000000..31a2a6958
--- /dev/null
+++ b/store/agents/autonomous-grid/lib/wake.mjs
@@ -0,0 +1,124 @@
+import { randomUUID } from 'node:crypto';
+import { bridgeUrl, discoverMachines } from './harness.mjs';
+
+/**
+ * The viewer's "Wake now": the one thing in this package that may start a sleeping grid, and only on a
+ * person's click. It never runs `grid` for it (every `grid` read here carries NO_WAKE) and never makes a
+ * credentialed read of its own. It asks the Harness daemon on the controller for ITS explicit wake —
+ * `grid_models_list` with `wake: [grid]` over the loopback bridge (03-wire-contract.md) — which makes the
+ * one credentialed read, marked `(wake)`, and re-reads without a credential until the grid serves a
+ * model or 45 s pass. Here the same question is asked again, without `wake`, until its answer stops
+ * saying `waking`.
+ *
+ * A daemon from before the wake answers the same RPC without `waking` — having read without a
+ * credential, as it always does — so an old daemon costs one harmless read and an honest sentence.
+ */
+
+/** How often the daemon is asked again while its wake runs. */
+export const WAKE_POLL_MS = 3000;
+/** When the viewer stops asking: the daemon's own window is 45 s; the rest covers a relayed controller. */
+export const WAKE_GIVE_UP_MS = 60_000;
+/** How long an ending stands on screen — as long as the daemon keeps its own `wakeOutcome`. */
+export const WAKE_OUTCOME_MS = 10 * 60_000;
+
+// The desktop's copy (desktop/lib/widgets/resting_model_words.dart), word for word where it has one.
+// Never the word "grid": a section is named as the desktop names it — the account's own is "your
+// models", a shared one goes by its name — from the daemon's own answer, never from the viewer's label
+// for the grid, which falls back to "Your grid".
+export const WAKING = 'Starting up… usually 15–40 s';
+const who = section => (section.own === true ? 'your models' : section.name);
+const ENDINGS = {
+ awake: section => (section.own === true ? 'Your models started' : `${section.name} started`),
+ not_started: section => `Couldn't start ${who(section)} right now — it will start on your next message`,
+ nobody_serving: () => 'Nobody is serving a model here right now',
+};
+const UNREACHABLE = "Couldn't reach Harness, so nothing was started — it will start on your next message";
+const OUTDATED = 'Update Harness to start it from here — it will start on your next message';
+/** The daemon failed to answer before it said anything about this grid. */
+const NOT_NOW = "Couldn't start it right now — it will start on your next message";
+/** An SSH controller has no daemon to ask, and a daemon that does not list this grid cannot start it. */
+export const WAKE_FAILED = "Couldn't start it from here — it will start on your next message";
+const LOST = section => `Lost the connection to Harness while starting ${who(section)}`;
+
+/** The machine whose daemon holds the sign-in the viewer reads with: a linked controller by its own id,
+ * this computer by the id Harness Machines gives it. An SSH host has none. */
+async function controllerMachineId(controller, discover) {
+ if (controller?.transport === 'harness') return controller.machineId;
+ if (controller?.transport !== 'local') return null;
+ return (await discover()).find(row => row.current)?.machineId ?? null;
+}
+
+/** How a section the daemon answered with has ended, or null while its wake is still running. A wake
+ * that showed models leaves no `wakeOutcome`, so models are looked at first. */
+function ending(section) {
+ if (section?.state === 'waking') return null;
+ if (section?.state === 'awake' && Array.isArray(section.models) && section.models.length) return 'awake';
+ if (section?.wakeOutcome === 'nobody_serving' || section?.state === 'awake') return 'nobody_serving';
+ return 'not_started';
+}
+
+/**
+ * Wake [grid] (a section name, as `grid ls` prints it) through [controller]'s daemon and settle on how it
+ * ended: `{state, message}`, where state is `awake`, `not_started`, `nobody_serving` or `failed` and
+ * message is what the page says. Never throws.
+ */
+export async function daemonWake({ controller, grid, signal, discover = discoverMachines, env = process.env,
+ WebSocketImpl = globalThis.WebSocket, pollMs = WAKE_POLL_MS, giveUpMs = WAKE_GIVE_UP_MS }) {
+ const failed = message => ({ state: 'failed', message });
+ let machineId;
+ try { machineId = await controllerMachineId(controller, discover); } catch { return failed(UNREACHABLE); }
+ if (!machineId) return failed(controller?.transport === 'local' ? UNREACHABLE : WAKE_FAILED);
+ if (!WebSocketImpl || signal?.aborted) return failed(UNREACHABLE);
+ let socket;
+ try { socket = new WebSocketImpl(bridgeUrl(env)); } catch { return failed(UNREACHABLE); }
+ return await new Promise(resolve => {
+ // The section that answered `waking`: who every later sentence is about.
+ let done = false, waking = null, requestId = null, next;
+ const settle = outcome => {
+ if (done) return;
+ done = true; clearTimeout(next); clearTimeout(giveUp); signal?.removeEventListener('abort', abort);
+ try { socket.close(); } catch { /* already closing */ }
+ resolve(outcome);
+ };
+ const ended = state => settle({ state, message: ENDINGS[state](waking) });
+ // Once the daemon has said `waking`, the start is its to finish: a lost socket says so, it is not
+ // reported as a start that never happened.
+ const lost = () => settle(failed(waking ? LOST(waking) : UNREACHABLE));
+ const abort = () => lost();
+ const ask = wake => {
+ requestId = randomUUID();
+ socket.send(JSON.stringify({ type: 'grid_models_list', payload: { requestId, rowState: true, ...(wake ? { wake: [grid] } : {}) } }));
+ };
+ const giveUp = setTimeout(() => (waking ? ended('not_started') : lost()), giveUpMs);
+ signal?.addEventListener('abort', abort, { once: true });
+ socket.addEventListener('open', () => socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1, relayIsolation: true } })));
+ socket.addEventListener('error', lost);
+ socket.addEventListener('close', lost);
+ socket.addEventListener('message', event => {
+ if (done || typeof event.data !== 'string' || event.data.length > 2 * 1024 * 1024) return;
+ let frame; try { frame = JSON.parse(event.data); } catch { return; }
+ const { type, payload = {} } = frame || {};
+ if (type === 'connected') {
+ // Asked once per connection: a repeated `connected` must not send the wake a second time.
+ if (requestId) return;
+ if (payload.relayIsolation !== true && payload.transport !== 'local') { settle(failed(OUTDATED)); return; }
+ ask(true);
+ } else if (type === 'grid_models_list_result' && payload.requestId === requestId) {
+ const section = Array.isArray(payload.grids) ? payload.grids.find(g => g?.name === grid) : undefined;
+ if (!waking) {
+ if (payload.error) { settle(failed(NOT_NOW)); return; }
+ if (!Array.isArray(payload.grids)) { settle(failed(OUTDATED)); return; }
+ if (!section) { settle(failed(WAKE_FAILED)); return; }
+ if (section.state !== 'waking') { settle(failed(OUTDATED)); return; }
+ waking = section;
+ } else if (!payload.error) {
+ const state = ending(section);
+ if (state) { ended(state); return; }
+ }
+ next = setTimeout(() => ask(false), pollMs);
+ } else if (!waking && ['error', 'connection_error', 'local_protocol_error', 'machine_link_required'].includes(type)) {
+ lost();
+ }
+ });
+ });
+}
diff --git a/store/agents/autonomous-grid/test/fakes.mjs b/store/agents/autonomous-grid/test/fakes.mjs
new file mode 100644
index 000000000..b277e3ccc
--- /dev/null
+++ b/store/agents/autonomous-grid/test/fakes.mjs
@@ -0,0 +1,111 @@
+// Stand-ins shared by the no-wake and wake tests: a `grid` binary that logs every argv it is run
+// with, and the Harness daemon's loopback bridge that the viewer's "Wake now" talks to.
+import { createHash, randomUUID } from 'node:crypto';
+import { createServer } from 'node:http';
+import { readFile, rename, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { device, reads, remoteNodes } from './fixtures.mjs';
+
+/** The per-grid reads a poll makes automatically, each of which must carry `--no-wake`. */
+export const READS = ['engines','models','stats'];
+
+/** A fake `grid` of one version, answering each verb from `verbs` and logging every argv it saw. An
+ * "old" one refuses `--no-wake` exactly as argparse does: a usage line on stderr and exit 2. */
+export async function fakeGrid(dir, name, plan, log) {
+ const file = join(dir, name);
+ await replan(file, plan);
+ await writeFile(file, `#!/usr/bin/env node
+const fs=require('fs');const plan=JSON.parse(fs.readFileSync(${JSON.stringify(`${file}.json`)},'utf8'));
+const argv=process.argv.slice(2);const log=${JSON.stringify(log)};
+fs.appendFileSync(log,JSON.stringify({binary:${JSON.stringify(name)},argv})+'\\n');
+if(plan.rejectsNoWake&&argv.includes('--no-wake')){process.stderr.write('usage: grid [-h] [--remote | --local] {models,engines,stats,info} ...\\ngrid: error: unrecognized arguments: --no-wake\\n');process.exit(2);}
+const verb=argv.find(a=>!a.startsWith('-'))||'';const turn=plan.verbs[verb];
+if(!turn){process.stdout.write('[]');process.exit(0);}
+if(turn.stdout!==undefined)process.stdout.write(typeof turn.stdout==='string'?turn.stdout:JSON.stringify(turn.stdout));
+if(turn.stderr)process.stderr.write(turn.stderr);process.exit(turn.exit??0);
+`, { mode: 0o755 });
+ return file;
+}
+/** What the fake `grid` at [file] answers from its next run on. Renamed into place: a poll may be
+ * running it at this moment, and a half-written plan would read as a grid that is down. */
+export async function replan(file, { rejectsNoWake = false, verbs = {} }) {
+ const temporary = `${file}.${randomUUID()}.tmp`;
+ await writeFile(temporary, JSON.stringify({ rejectsNoWake, verbs }));
+ await rename(temporary, `${file}.json`);
+}
+export const awakeVerbs = {
+ use:{stdout:{mode:'remote',active:'test-grid'}}, ls:{stdout:[{grid:'test-grid',type:'permissioned-public'}]},
+ info:{stdout:{grid:'test-grid',type:'permissioned-public',status:'running',grid_url:'https://relay.example'}},
+ engines:{stdout:remoteNodes}, models:{stdout:reads.models.value}, stats:{stdout:reads.stats.value}, 'device-info':{stdout:device},
+};
+// One line per call, APPENDED: the viewer runs several \`grid\` reads at once, and a read-modify-write of
+// one JSON document crashed a fake that caught it half written — which read as the grid being down.
+export const logged = async log => (await readFile(log,'utf8').catch(()=>'')).split('\n').filter(Boolean).map(line=>JSON.parse(line));
+export const verbOf = argv => argv.find(a=>!a.startsWith('-'));
+
+const ACCEPT_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
+function encode(opcode, payload = '') {
+ const data = Buffer.from(payload), length = data.length;
+ const head = length < 126 ? Buffer.from([0x80 | opcode, length])
+ : length < 65_536 ? Buffer.from([0x80 | opcode, 126, length >> 8, length & 255])
+ : Buffer.concat([Buffer.from([0x80 | opcode, 127]), Buffer.from(BigInt(length).toString(16).padStart(16, '0'), 'hex')]);
+ return Buffer.concat([head, data]);
+}
+function decode(buffer) {
+ if (buffer.length < 2) return null;
+ let length = buffer[1] & 0x7f, offset = 2;
+ if (length === 126) { if (buffer.length < 4) return null; length = buffer.readUInt16BE(2); offset = 4; }
+ else if (length === 127) { if (buffer.length < 10) return null; length = Number(buffer.readBigUInt64BE(2)); offset = 10; }
+ const masked = (buffer[1] & 0x80) !== 0, start = offset + (masked ? 4 : 0);
+ if (buffer.length < start + length) return null;
+ const data = Buffer.from(buffer.subarray(start, start + length));
+ if (masked) for (let i = 0; i < data.length; i++) data[i] ^= buffer[offset + (i % 4)];
+ return { opcode: buffer[0] & 0x0f, data, size: start + length };
+}
+
+/**
+ * The Harness daemon's loopback bridge (`ws://127.0.0.1:<port>/api/local-ws`), speaking just enough of
+ * RFC 6455 for Node's own WebSocket client: unfragmented text frames, ping and close. Every JSON frame a
+ * client sends is kept, per connection and in arrival order; `respond(frame, send)` answers it.
+ */
+export async function fakeBridge(respond = () => {}) {
+ const connections = [], sockets = new Set();
+ let closing = false;
+ const server = createServer((_req, res) => { res.writeHead(426); res.end(); });
+ server.on('upgrade', (req, socket) => {
+ // An upgrade that lands after close() began is never adopted: the server would wait on it forever.
+ if (closing || req.url !== '/api/local-ws') { socket.destroy(); return; }
+ sockets.add(socket);
+ const accept = createHash('sha1').update(`${req.headers['sec-websocket-key']}${ACCEPT_GUID}`).digest('base64');
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
+ const connection = { frames: [], closed: false };
+ connections.push(connection);
+ const send = frame => { if (!socket.destroyed) socket.write(encode(1, JSON.stringify(frame))); };
+ let pending = Buffer.alloc(0);
+ socket.on('data', chunk => {
+ pending = Buffer.concat([pending, chunk]);
+ for (let frame = decode(pending); frame; frame = decode(pending)) {
+ pending = pending.subarray(frame.size);
+ if (frame.opcode === 8) { connection.closed = true; socket.end(encode(8, frame.data.subarray(0, 2))); return; }
+ if (frame.opcode === 9) { socket.write(encode(10, frame.data)); continue; }
+ if (frame.opcode !== 1) continue;
+ const parsed = JSON.parse(frame.data.toString('utf8'));
+ connection.frames.push(parsed);
+ respond(parsed, send);
+ }
+ });
+ socket.on('close', () => { connection.closed = true; sockets.delete(socket); });
+ socket.on('error', () => {});
+ });
+ await new Promise(ready => server.listen(0, '127.0.0.1', ready));
+ return {
+ url: `ws://127.0.0.1:${server.address().port}/api/local-ws`,
+ connections,
+ frames: () => connections.flatMap(c => c.frames),
+ close: () => new Promise(done => {
+ closing = true;
+ for (const socket of sockets) socket.destroy();
+ server.close(() => done()); server.closeAllConnections();
+ }),
+ };
+}
diff --git a/store/agents/autonomous-grid/test/nowake.test.mjs b/store/agents/autonomous-grid/test/nowake.test.mjs
index 058e4ad4b..cfbfa24fd 100644
--- a/store/agents/autonomous-grid/test/nowake.test.mjs
+++ b/store/agents/autonomous-grid/test/nowake.test.mjs
@@ -3,7 +3,7 @@
// the last reading on screen, and a hidden page stops listening.
import test from 'node:test';
import assert from 'node:assert/strict';
-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { runInNewContext } from 'node:vm';
@@ -12,38 +12,11 @@ import { assemble, createCollector } from '../lib/telemetry.mjs';
import { initializeWorkspace } from '../lib/connect.mjs';
import { createViewer } from '../viewer.mjs';
import { config, device, reads, remoteNodes } from './fixtures.mjs';
+import { awakeVerbs, fakeGrid, logged, READS, verbOf } from './fakes.mjs';
const temporary = async t => { const dir=await mkdtemp(join(tmpdir(),'grid-nowake-'));t.after(()=>rm(dir,{recursive:true,force:true}));return dir; };
-const READS = ['engines','models','stats'];
const asleepEnvelope = JSON.stringify({error:{code:'grid_asleep',message:'Grid test-grid is asleep: this grid is resting',status:503}});
-/** A fake `grid` of one version, answering each verb from `verbs` and logging every argv it saw. An
- * "old" one refuses `--no-wake` exactly as argparse does: a usage line on stderr and exit 2. */
-async function fakeGrid(dir, name, { rejectsNoWake = false, verbs = {} }, log) {
- const file = join(dir, name), plan = join(dir, `${name}.json`);
- await writeFile(plan, JSON.stringify({ rejectsNoWake, verbs }));
- await writeFile(file, `#!/usr/bin/env node
-const fs=require('fs');const plan=JSON.parse(fs.readFileSync(${JSON.stringify(plan)},'utf8'));
-const argv=process.argv.slice(2);const log=${JSON.stringify(log)};
-fs.appendFileSync(log,JSON.stringify({binary:${JSON.stringify(name)},argv})+'\\n');
-if(plan.rejectsNoWake&&argv.includes('--no-wake')){process.stderr.write('usage: grid [-h] [--remote | --local] {models,engines,stats,info} ...\\ngrid: error: unrecognized arguments: --no-wake\\n');process.exit(2);}
-const verb=argv.find(a=>!a.startsWith('-'))||'';const turn=plan.verbs[verb];
-if(!turn){process.stdout.write('[]');process.exit(0);}
-if(turn.stdout!==undefined)process.stdout.write(typeof turn.stdout==='string'?turn.stdout:JSON.stringify(turn.stdout));
-if(turn.stderr)process.stderr.write(turn.stderr);process.exit(turn.exit??0);
-`, { mode: 0o755 });
- return file;
-}
-const awakeVerbs = {
- use:{stdout:{mode:'remote',active:'test-grid'}}, ls:{stdout:[{grid:'test-grid',type:'permissioned-public'}]},
- info:{stdout:{grid:'test-grid',type:'permissioned-public',status:'running',grid_url:'https://relay.example'}},
- engines:{stdout:remoteNodes}, models:{stdout:reads.models.value}, stats:{stdout:reads.stats.value}, 'device-info':{stdout:device},
-};
-// One line per call, APPENDED: the viewer runs several \`grid\` reads at once, and a read-modify-write of
-// one JSON document crashed a fake that caught it half written — which read as the grid being down.
-const logged = async log => (await readFile(log,'utf8').catch(()=>'')).split('\n').filter(Boolean).map(line=>JSON.parse(line));
-const verbOf = argv => argv.find(a=>!a.startsWith('-'));
-
test('gridJson carries the refusal code a program branches on, and tells an old grid from a failure',async t=>{
const dir=await temporary(t),log=join(dir,'calls.json');
const asleep=await fakeGrid(dir,'asleep',{verbs:{engines:{stderr:`${asleepEnvelope}\nGrid test-grid is asleep: this grid is resting\n`,exit:1}}},log);
diff --git a/store/agents/autonomous-grid/test/wake.test.mjs b/store/agents/autonomous-grid/test/wake.test.mjs
new file mode 100644
index 000000000..8f62494e1
--- /dev/null
+++ b/store/agents/autonomous-grid/test/wake.test.mjs
@@ -0,0 +1,244 @@
+// grid-reads-without-waking issue 03, the viewer's half: "Wake now" is the one thing in the viewer that
+// may start a sleeping grid, and only on a person's click. It asks the Harness daemon for its explicit
+// wake over the loopback bridge, answers the page at once, and shows how the wake ended — while every
+// automatic read stays credential-less (`--no-wake`) and never reaches the bridge at all.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer } from 'node:net';
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runInNewContext } from 'node:vm';
+import { atomicJson, PACKAGE } from '../lib/fleet.mjs';
+import { daemonWake } from '../lib/wake.mjs';
+import { createViewer } from '../viewer.mjs';
+import { config } from './fixtures.mjs';
+import { awakeVerbs, fakeBridge, fakeGrid, logged, READS, replan, verbOf } from './fakes.mjs';
+
+const MACHINE = 'this-computer';
+const WAKING = 'Starting up… usually 15–40 s';
+// Named as the desktop names them (resting_model_words.dart): the account's own grid is "your models",
+// a shared one goes by its name.
+const OWN_NOT_STARTED = "Couldn't start your models right now — it will start on your next message";
+const TEAM_NOT_STARTED = "Couldn't start team right now — it will start on your next message";
+const NOBODY = 'Nobody is serving a model here right now';
+const SERVING = [{ id:'Qwen3.5-27B', node:'Mac Studio' }];
+/** The fake `grid`'s answers for a workspace looking at [grid], its status [status]. */
+const verbsFor = (grid, status) => ({ ...awakeVerbs, use:{stdout:{mode:'remote',active:grid}}, ls:{stdout:[{grid,type:'permissioned-public'}]},
+ info:{stdout:{grid,type:'permissioned-public',status,grid_url:'https://relay.example'}} });
+// Retried: a poll that was already out when its viewer closed may still be writing into the workspace.
+const remove = dir => rm(dir,{recursive:true,force:true,maxRetries:10,retryDelay:50});
+const eventually = async (check, ms = 5000) => { const end=Date.now()+ms; while(!check()){ if(Date.now()>end)throw new Error('timed out'); await new Promise(r=>setTimeout(r,10)); } };
+const section = extra => ({ name:'test-grid', type:'permissioned-public', own:true, models:[], seenAt:null, lastKnownAge:null, ...extra });
+const shared = extra => section({ name:'team', type:'domain-restricted', own:false, ...extra });
+/** This ticket's sentences never say "grid" — whichever grid it is, and however the wake went. */
+const saysNoGrid = s => { for (const x of s.seen.snapshots) if (x.wake) assert.doesNotMatch(x.wake.message, /grid/i); };
+
+/** The daemon's side of 03-wire-contract.md: the wake's own reply says `waking` at once, and every later
+ * ask says `waking` until the test hands over how it ended (`ending()`, null while it runs). */
+function daemon({ ending = () => null, base = section, first = base({ state:'waking' }), handshakes = 1 } = {}) {
+ return (frame, send) => {
+ const { type, payload } = frame;
+ if (type === 'machine_select') for (let i = 0; i < handshakes; i++) send({ type:'connected', payload:{ machineId:payload.machineId, transport:'local', localProtocolVersion:1 } });
+ if (type !== 'grid_models_list') return;
+ const grid = payload.wake ? first : ending() || base({ state:'waking' });
+ send({ type:'grid_models_list_result', payload:{ requestId:payload.requestId, gridName:'test-grid', models:grid.models, grids:[grid] } });
+ };
+}
+
+/** The page's event stream, every snapshot kept in order, and a wait for the first that matches. */
+async function listen(t, base) {
+ const abort = new AbortController(); t.after(() => abort.abort());
+ const reader = (await fetch(`${base}/events`, { signal:abort.signal })).body.getReader(), decoder = new TextDecoder();
+ const snapshots = []; let buffer = '';
+ void (async () => { try { for (;;) {
+ const { value, done } = await reader.read(); if (done) return;
+ buffer += decoder.decode(value, { stream:true });
+ for (let cut = buffer.indexOf('\n\n'); cut >= 0; cut = buffer.indexOf('\n\n')) {
+ const data = buffer.slice(0, cut).split('\n').find(line => line.startsWith('data: ')); buffer = buffer.slice(cut + 2);
+ if (data) snapshots.push(JSON.parse(data.slice(6)));
+ }
+ } } catch { /* aborted */ } })();
+ const until = async (match, ms) => { await eventually(() => snapshots.some(match), ms); return snapshots.find(match); };
+ return { snapshots, until };
+}
+
+/** A viewer on a workspace looking at [grid], asleep, a fake `grid` it reads with, and a fake bridge. */
+async function setup(t, respond, { grid = 'test-grid', verbs = verbsFor(grid, 'asleep'), bridgeUrl, giveUpMs = 5000, intervalMs = 50 } = {}) {
+ const dir = await mkdtemp(join(tmpdir(), 'grid-wake-')), log = join(dir, 'calls.log');
+ const binary = await fakeGrid(dir, 'grid', { verbs }, log);
+ const workspace = join(dir, 'ws');
+ await atomicJson(join(workspace, 'grid-fleet.json'), { ...config, grid, machines:[{ ...config.machines[0], gridBinary:binary }] });
+ const bridge = await fakeBridge(respond);
+ const viewer = createViewer({ workspace, intervalMs, wakeOptions:{
+ env:{ HARNESS_GRID_BRIDGE_URL:bridgeUrl || bridge.url }, discover:async () => [{ machineId:'another', current:false }, { machineId:MACHINE, current:true }], pollMs:10, giveUpMs,
+ } });
+ // One hook, in this order (hooks run first-in-first-out, and a failed one skips the rest): a viewer
+ // left polling keeps the test process alive, and writes into the workspace being removed.
+ t.after(async () => { await viewer.close(); await bridge.close(); await remove(dir); });
+ const port = await viewer.start();
+ const base = `http://127.0.0.1:${port}`;
+ const seen = await listen(t, base);
+ const click = (headers = {}) => fetch(`${base}/api/wake`, { method:'POST', headers:{ 'content-type':'application/json', ...headers }, body:'{}' });
+ return { base, bridge, seen, click, awaken: () => replan(binary, { verbs:verbsFor(grid, 'running') }), calls: () => logged(log) };
+}
+const wakeFrames = bridge => bridge.frames().filter(f => f.type === 'grid_models_list' && 'wake' in f.payload);
+
+test('Wake now asks the daemon once, answers "waking" at once, and a woken grid shows its engines', async t => {
+ let ending = null;
+ const s = await setup(t, daemon({ ending: () => ending }));
+ await s.seen.until(x => x.status === 'asleep');
+
+ const response = await s.click();
+ assert.equal(response.status, 202);
+ const { wake } = await response.json();
+ assert.equal(wake.state, 'waking'); assert.equal(wake.message, WAKING); assert.equal(wake.grid, 'test-grid');
+ await s.seen.until(x => x.wake?.state === 'waking');
+ // The daemon is still starting it: asked again, each time without a wake, and nothing has ended.
+ await eventually(() => s.bridge.frames().filter(f => f.type === 'grid_models_list').length >= 3);
+ assert.ok(s.seen.snapshots.every(x => !x.wake || x.wake.state === 'waking'), 'the POST answered before the wake finished');
+
+ await s.awaken();
+ ending = section({ state:'awake', models:SERVING, seenAt:new Date().toISOString(), lastKnownAge:0 });
+ const ended = await s.seen.until(x => x.wake && x.wake.state !== 'waking');
+ assert.equal(ended.wake.state, 'awake'); assert.equal(ended.wake.message, 'Your models started');
+ // Read at once, not at the resting pace (30 s): the woken grid's engines are drawn from that read.
+ const live = await s.seen.until(x => x.status === 'live');
+ assert.ok(live.nodes.length > 0); assert.equal(live.wake, undefined, 'a grid seen serving has had its start');
+
+ assert.equal(s.bridge.connections.length, 1, 'one connection for the whole wake');
+ const [connection] = s.bridge.connections;
+ assert.deepEqual(connection.frames[0], { type:'machine_select', payload:{ machineId:MACHINE, localProtocolVersion:1, relayIsolation:true } });
+ const lists = connection.frames.filter(f => f.type === 'grid_models_list');
+ assert.deepEqual(wakeFrames(s.bridge).map(f => f.payload.wake), [['test-grid']], 'exactly one wake');
+ assert.equal(lists[0], wakeFrames(s.bridge)[0], 'the wake is the first ask');
+ assert.ok(lists.every(f => f.payload.rowState === true && typeof f.payload.requestId === 'string'));
+ await eventually(() => connection.closed);
+ const reads = (await s.calls()).filter(c => READS.includes(verbOf(c.argv)));
+ assert.ok(reads.length > 0);
+ for (const call of reads) assert.ok(call.argv.includes('--no-wake'), `ran ${call.argv.join(' ')} without --no-wake`);
+ saysNoGrid(s);
+});
+
+test('each way a wake can end is shown in the published snapshot, naming the grid as the desktop does', async t => {
+ // The daemon's own section says whose it is: the viewer's label for a grid can be "Your grid".
+ const endings = [
+ ['your own did not come up', section, section({ state:'asleep', wakeOutcome:'not_started' }), 'not_started', OWN_NOT_STARTED],
+ ['a shared one did not come up', shared, shared({ state:'asleep', wakeOutcome:'not_started' }), 'not_started', TEAM_NOT_STARTED],
+ ['it came up and nobody serves', section, section({ state:'awake', wakeOutcome:'nobody_serving' }), 'nobody_serving', NOBODY],
+ ['your own started', section, section({ state:'awake', models:SERVING }), 'awake', 'Your models started'],
+ ['a shared one started', shared, shared({ state:'awake', models:SERVING }), 'awake', 'team started'],
+ ['the daemon never said, for your own (the viewer gives up)', section, null, 'not_started', OWN_NOT_STARTED],
+ ['the daemon never said, for a shared one', shared, null, 'not_started', TEAM_NOT_STARTED],
+ ];
+ for (const [name, base, ending, state, message] of endings) {
+ await t.test(name, async t => {
+ const s = await setup(t, daemon({ ending: () => ending, base }), { grid:base({}).name, giveUpMs:ending ? 5000 : 200 });
+ await s.seen.until(x => x.status === 'asleep');
+ assert.equal((await (await s.click()).json()).wake.state, 'waking');
+ const ended = await s.seen.until(x => x.wake && x.wake.state !== 'waking');
+ assert.equal(ended.wake.state, state); assert.equal(ended.wake.message, message);
+ assert.deepEqual(wakeFrames(s.bridge).map(f => f.payload.wake), [[base({}).name]]);
+ await eventually(() => s.bridge.connections[0].closed);
+ saysNoGrid(s);
+ });
+ }
+});
+
+test('a second click while a wake runs joins it, and a repeated handshake sends no second wake', async t => {
+ let ending = null;
+ const s = await setup(t, daemon({ ending: () => ending, handshakes:2 }));
+ await s.seen.until(x => x.status === 'asleep');
+ const answers = await Promise.all([s.click(), s.click()]);
+ await eventually(() => wakeFrames(s.bridge).length === 1);
+ answers.push(await s.click());
+ for (const answer of answers) { assert.equal(answer.status, 202); assert.equal((await answer.json()).wake.state, 'waking'); }
+ ending = section({ state:'asleep', wakeOutcome:'not_started' });
+ await s.seen.until(x => x.wake?.state === 'not_started');
+ assert.equal(s.bridge.connections.length, 1); assert.equal(wakeFrames(s.bridge).length, 1);
+ saysNoGrid(s);
+});
+
+test('a bridge that is not there, or a daemon too old for the wake, is said plainly — nothing else is tried', async t => {
+ await t.test('no bridge to connect to', async t => {
+ const closed = createServer(); await new Promise(r => closed.listen(0, '127.0.0.1', r)); const { port } = closed.address(); await new Promise(r => closed.close(r));
+ const s = await setup(t, daemon(), { bridgeUrl:`ws://127.0.0.1:${port}/api/local-ws` });
+ await s.seen.until(x => x.status === 'asleep');
+ assert.equal((await (await s.click()).json()).wake.state, 'waking');
+ const ended = await s.seen.until(x => x.wake && x.wake.state !== 'waking');
+ assert.equal(ended.wake.state, 'failed'); assert.match(ended.wake.message, /^Couldn't reach Harness, so nothing was started/);
+ saysNoGrid(s);
+ });
+ await t.test('a daemon that answers without "waking" (it predates the wake)', async t => {
+ const s = await setup(t, daemon({ first:section({ state:'asleep' }) }));
+ await s.seen.until(x => x.status === 'asleep');
+ await s.click();
+ const ended = await s.seen.until(x => x.wake && x.wake.state !== 'waking');
+ assert.equal(ended.wake.state, 'failed'); assert.match(ended.wake.message, /^Update Harness to start it from here/);
+ await eventually(() => s.bridge.connections[0].closed);
+ assert.equal(s.bridge.frames().filter(f => f.type === 'grid_models_list').length, 1, 'asked once, never again');
+ saysNoGrid(s);
+ });
+ await t.test('a controller reached over SSH, or a computer Harness cannot name, has no daemon to ask', async t => {
+ const bridge = await fakeBridge(daemon()); t.after(() => bridge.close());
+ const options = { grid:'test-grid', env:{ HARNESS_GRID_BRIDGE_URL:bridge.url }, pollMs:10, giveUpMs:300 };
+ const ssh = await daemonWake({ ...options, controller:{ id:'rig', name:'Rig', transport:'ssh', host:'rig.example' } });
+ assert.equal(ssh.state, 'failed'); assert.match(ssh.message, /^Couldn't start it from here/);
+ const unnamed = await daemonWake({ ...options, controller:{ id:'local', name:'This machine', transport:'local' }, discover:async () => { throw new Error('harness: not found'); } });
+ assert.equal(unnamed.state, 'failed'); assert.match(unnamed.message, /^Couldn't reach Harness/);
+ assert.equal(bridge.connections.length, 0);
+ // A Harness-linked controller is asked by its own machine id, relayed by this computer's bridge.
+ const linked = await daemonWake({ ...options, controller:{ id:'rig', name:'Rig', transport:'harness', machineId:'rig-id' }, discover:async () => assert.fail('a linked machine names itself') });
+ assert.equal(linked.state, 'not_started'); assert.equal(linked.message, OWN_NOT_STARTED);
+ assert.equal(bridge.frames()[0].payload.machineId, 'rig-id');
+ for (const { message } of [ssh, unnamed, linked]) assert.doesNotMatch(message, /grid/i);
+ });
+});
+
+test('no automatic read reaches the bridge, and the wake is refused unless a resting grid is on screen', async t => {
+ const s = await setup(t, daemon(), { verbs:awakeVerbs, intervalMs:20 });
+ await s.seen.until(x => x.status === 'live');
+ await eventually(() => s.seen.snapshots.filter(x => x.status === 'live').length >= 4);
+ for (let i = 0; i < 3; i++) await (await fetch(`${s.base}/api/snapshot`)).json();
+ assert.equal((await s.click()).status, 409, 'nothing to start on an awake grid');
+ assert.equal((await s.click({ origin:'https://evil.example' })).status, 403);
+ assert.equal(s.bridge.connections.length, 0, 'polls never open the bridge');
+ const reads = (await s.calls()).filter(c => READS.includes(verbOf(c.argv)));
+ assert.ok(reads.length >= 3);
+ for (const call of reads) assert.ok(call.argv.includes('--no-wake'), `ran ${call.argv.join(' ')} without --no-wake`);
+});
+
+/** viewer/wake.js in a sandbox — the shipped file, not a copy. Views go through JSON: they are objects
+ * of another realm. */
+async function loadWake() {
+ const sandbox = {}; runInNewContext(await readFile(join(PACKAGE, 'viewer', 'wake.js'), 'utf8'), sandbox);
+ const api = sandbox.harnessViewerWake;
+ return { RESTING:api.RESTING, view:snapshot => JSON.parse(JSON.stringify(api.wakeView(snapshot))) };
+}
+
+test('the page offers Wake now while asleep, holds it while waking, and says how the wake ended', async t => {
+ const { RESTING, view } = await loadWake();
+ const ended = (state, message) => ({ grid:'test-grid', state, message, at:new Date().toISOString() });
+ assert.equal(RESTING, 'Resting to save resources. It starts by itself when you send a message.');
+ assert.deepEqual(view({ status:'asleep' }), { hidden:false, message:RESTING, button:true, disabled:false });
+ assert.deepEqual(view({ status:'asleep', wake:ended('waking', WAKING) }), { hidden:false, message:WAKING, button:true, disabled:true });
+ assert.deepEqual(view({ status:'asleep', wake:ended('not_started', OWN_NOT_STARTED) }), { hidden:false, message:OWN_NOT_STARTED, button:true, disabled:false });
+ assert.deepEqual(view({ status:'asleep', wake:ended('failed', 'Update Harness') }), { hidden:false, message:'Update Harness', button:true, disabled:false });
+ assert.deepEqual(view({ status:'live', wake:ended('nobody_serving', NOBODY) }), { hidden:false, message:NOBODY, button:false, disabled:false });
+ // Started: the engines on the map are the answer. Until the read that draws them lands, say it.
+ assert.deepEqual(view({ status:'asleep', wake:ended('awake', 'Your models started') }), { hidden:false, message:'Your models started', button:false, disabled:true });
+ assert.deepEqual(view({ status:'live', wake:ended('awake', 'Your models started') }), { hidden:true });
+ assert.deepEqual(view({ status:'live' }), { hidden:true });
+ assert.deepEqual(view(null), { hidden:true });
+
+ // Wired: the page loads it before app.js, has the button, and the button posts to the wake route.
+ const dir = await mkdtemp(join(tmpdir(), 'grid-wake-'));
+ const viewer = createViewer({ workspace:dir, intervalMs:1000, collect:async () => ({ spec:1, status:'asleep', grid:'test-grid', nodes:[], machines:[], models:[], events:[], operations:[], history:{}, sources:{}, summary:{}, pollIntervalMs:30_000 }) });
+ t.after(async () => { await viewer.close(); await remove(dir); });
+ const port = await viewer.start();
+ const page = await (await fetch(`http://127.0.0.1:${port}/`)).text();
+ assert.ok(page.indexOf('src="wake.js"') > 0 && page.indexOf('src="wake.js"') < page.indexOf('src="app.js"'));
+ assert.match(page, /<button[^>]*id="wake-now"[^>]*>Wake now<\/button>/);
+ assert.equal((await fetch(`http://127.0.0.1:${port}/wake.js`)).status, 200);
+ assert.match(await readFile(join(PACKAGE, 'viewer', 'app.js'), 'utf8'), /fetch\('api\/wake',\{method:'POST'/);
+});
diff --git a/store/agents/autonomous-grid/viewer.mjs b/store/agents/autonomous-grid/viewer.mjs
index 44e639efa..6a52e9fa1 100644
--- a/store/agents/autonomous-grid/viewer.mjs
+++ b/store/agents/autonomous-grid/viewer.mjs
@@ -4,13 +4,16 @@ import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { atomicJson, gridSelect, now, operations, PACKAGE, readConfig } from './lib/fleet.mjs';
import { createCollector } from './lib/telemetry.mjs';
+import { daemonWake, WAKE_FAILED, WAKE_OUTCOME_MS, WAKING } from './lib/wake.mjs';
-export function createViewer({ workspace, port = 0, intervalMs = 8000, collect = createCollector(workspace, { intervalMs }), select = gridSelect, timer = setTimeout }) {
+export function createViewer({ workspace, port = 0, intervalMs = 8000, collect = createCollector(workspace, { intervalMs }), select = gridSelect, timer = setTimeout, startWake = daemonWake, wakeOptions = {} }) {
const clients = new Set();
let snapshot = { spec: 1, status: 'connecting', grid: 'Your grid', nodes: [], machines: [], models: [], events: [], operations: [], history: {}, sources: {}, summary: {}, observedAt: null, pollIntervalMs: intervalMs };
- let stopped = false, pollTimer, opTimer, heartbeat, inFlight = false, lastPollAt = 0;
+ let stopped = false, pollTimer, opTimer, heartbeat, inFlight = false, lastPollAt = 0, readAgain = false;
+ // "Wake now" (lib/wake.mjs): the one run in flight, and what the page is told about the latest one.
+ let waking = null, wakeState = null;
// The next tick is booked only while a pane is connected: a viewer nobody is looking at must not keep
- // running the grid CLI every few seconds. A request for the observation still wakes one read if the
+ // running the grid CLI every few seconds. A request for the observation still starts one read if the
// one on hand has gone stale. The observation names its own pace — a sleeping grid is looked at every
// 30 s rather than every few (lib/telemetry.mjs) — and a stale-read request honours the same pace.
const pace = () => snapshot.pollIntervalMs || intervalMs;
@@ -19,15 +22,27 @@ export function createViewer({ workspace, port = 0, intervalMs = 8000, collect =
if (stopped || clients.size === 0) return;
pollTimer = timer(poll, pace());
};
- const wake = () => {
+ const readIfStale = () => {
if (stopped || inFlight || Date.now() - lastPollAt < pace()) return;
clearTimeout(pollTimer); pollTimer = null;
void poll();
};
+ // A read that must land now, not at the next booked tick: a wake just ended. One already out may have
+ // started before it did, so another follows that one.
+ const readNow = () => {
+ if (stopped) return;
+ if (inFlight) { readAgain = true; return; }
+ clearTimeout(pollTimer); pollTimer = null;
+ void poll();
+ };
+ // What the page is sent: the observation, with the wake beside it while that grid is the one on
+ // screen — a run still going, or an ending young enough to still be true.
+ const current = () => wakeState && wakeState.grid === snapshot.grid
+ && (wakeState.state === 'waking' || Date.now() - Date.parse(wakeState.at) < WAKE_OUTCOME_MS) ? { ...snapshot, wake: wakeState } : snapshot;
const headers = { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer' };
const json = (res, code, value) => { res.writeHead(code, { ...headers, 'content-type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(value)); };
const publish = () => {
- const body = `event: snapshot\ndata: ${JSON.stringify(snapshot)}\n\n`;
+ const body = `event: snapshot\ndata: ${JSON.stringify(current())}\n\n`;
for (const client of clients) {
if (client.writableLength > 256 * 1024) { client.destroy(); clients.delete(client); }
else client.write(body);
@@ -41,7 +56,7 @@ export function createViewer({ workspace, port = 0, intervalMs = 8000, collect =
const url = new URL(req.url, `http://${req.headers.host}`);
const origin = req.headers.origin;
if (origin && origin !== url.origin) { json(res, 403, { error: 'Cross-origin requests are not allowed.' }); return; }
- // The one write the viewer takes: which grid to look at. It is the CLI's own selection
+ // One of the viewer's two writes: which grid to look at. It is the CLI's own selection
// (`grid use`), so the agent and a terminal see the same choice, and the next poll is run at
// once so the screen changes with the click rather than up to a poll later.
if (req.method === 'POST' && url.pathname === '/api/select') {
@@ -51,21 +66,27 @@ export function createViewer({ workspace, port = 0, intervalMs = 8000, collect =
try { await selectGrid(grid); json(res, 200, { ok: true, grid }); } catch (err) { json(res, 409, { error: err.message }); }
return;
}
+ // The other: a person asked the resting grid on screen to start. Answered at once; the daemon does
+ // the waking, and how it went arrives on the stream the map already listens on.
+ if (req.method === 'POST' && url.pathname === '/api/wake') {
+ try { json(res, 202, { ok: true, wake: requestWake() }); } catch (err) { json(res, 409, { error: err.message }); }
+ return;
+ }
if (!['GET', 'HEAD'].includes(req.method)) { res.setHeader('allow', 'GET, HEAD, POST'); json(res, 405, { error: 'This viewer is read-only. Talk to the Model Manager to make changes.' }); return; }
if (url.pathname === '/health') { json(res, 200, { ok: true }); return; }
- if (url.pathname === '/api/snapshot') { json(res, 200, snapshot); wake(); return; }
+ if (url.pathname === '/api/snapshot') { json(res, 200, current()); readIfStale(); return; }
if (url.pathname === '/events') {
if (req.method === 'HEAD') { res.writeHead(200, headers); res.end(); return; }
if (clients.size >= 32) { json(res, 503, { error: 'Too many viewer connections.' }); return; }
res.writeHead(200, { ...headers, 'content-type': 'text/event-stream', connection: 'keep-alive', 'x-accel-buffering': 'no' });
- res.write(`event: snapshot\ndata: ${JSON.stringify(snapshot)}\n\n`);
+ res.write(`event: snapshot\ndata: ${JSON.stringify(current())}\n\n`);
clients.add(res);
res.on('close', () => { clients.delete(res); if (clients.size === 0) { clearTimeout(pollTimer); pollTimer = null; } });
- wake();
+ readIfStale();
if (!pollTimer && !inFlight) schedule();
return;
}
- const assets = { '/': ['index.html', 'text/html; charset=utf-8'], '/stream.js': ['stream.js', 'text/javascript; charset=utf-8'], '/app.js': ['app.js', 'text/javascript; charset=utf-8'], '/app.css': ['app.css', 'text/css; charset=utf-8'] };
+ const assets = { '/': ['index.html', 'text/html; charset=utf-8'], '/stream.js': ['stream.js', 'text/javascript; charset=utf-8'], '/wake.js': ['wake.js', 'text/javascript; charset=utf-8'], '/app.js': ['app.js', 'text/javascript; charset=utf-8'], '/app.css': ['app.css', 'text/css; charset=utf-8'] };
if (!assets[url.pathname]) { json(res, 404, { error: 'Not found' }); return; }
const [file, contentType] = assets[url.pathname];
const content = await readFile(join(PACKAGE, 'viewer', file));
@@ -91,6 +112,39 @@ export function createViewer({ workspace, port = 0, intervalMs = 8000, collect =
poll(); // not awaited — its own errors are already caught inside poll()
}
+ /**
+ * Start the resting grid on screen through the daemon, or join the start already running for it: a
+ * second click is not a second wake. Anything but a resting grid is refused — an awake one has
+ * nothing to start, and no automatic path ever gets here.
+ */
+ function requestWake() {
+ const label = snapshot.grid;
+ if (waking) {
+ if (waking.grid === label) return wakeState;
+ throw new Error('Still starting the one before. Try again in a moment.');
+ }
+ if (snapshot.status !== 'asleep') throw new Error('It is not resting right now.');
+ waking = { grid: label, abort: new AbortController() };
+ wakeState = { grid: label, state: 'waking', message: WAKING, at: now() };
+ publish();
+ void runWake(label, waking.abort.signal);
+ return wakeState;
+ }
+ async function runWake(label, signal) {
+ let outcome;
+ try {
+ const config = await readConfig(workspace);
+ outcome = await startWake({ ...wakeOptions, controller: config.machines.find(m => m.id === config.controller), grid: config.grid, signal });
+ } catch { outcome = { state: 'failed', message: WAKE_FAILED }; }
+ waking = null;
+ if (stopped) return;
+ wakeState = { grid: label, state: outcome.state, message: outcome.message, at: now() };
+ publish();
+ // However it ended, look again now rather than at the resting pace: a woken grid's engines are
+ // drawn from this read — and, like every read, it carries NO_WAKE.
+ readNow();
+ }
+
async function poll() {
inFlight = true;
try { snapshot = await collect(); }
@@ -100,7 +154,13 @@ export function createViewer({ workspace, port = 0, intervalMs = 8000, collect =
}
inFlight = false; lastPollAt = Date.now();
if (stopped) return;
- publish(); schedule();
+ // The daemon keeps a wake's ending until a read finds the grid serving; so does the page — a
+ // "started" line must not come back over a later sleep.
+ if (wakeState && wakeState.state !== 'waking' && wakeState.grid === snapshot.grid
+ && ['live', 'partial'].includes(snapshot.status) && snapshot.summary?.modelsServing > 0) wakeState = null;
+ publish();
+ if (readAgain) { readAgain = false; void poll(); return; }
+ schedule();
}
async function pollOperations() {
const latest = await operations(workspace).catch(() => []);
@@ -117,7 +177,7 @@ export function createViewer({ workspace, port = 0, intervalMs = 8000, collect =
ok(server.address().port);
});
}),
- close: async () => { stopped = true; clearTimeout(pollTimer); clearTimeout(opTimer); clearInterval(heartbeat); for (const client of clients) client.end(); server.closeAllConnections(); await new Promise(done => server.close(done)); },
+ close: async () => { stopped = true; waking?.abort.abort(); clearTimeout(pollTimer); clearTimeout(opTimer); clearInterval(heartbeat); for (const client of clients) client.end(); server.closeAllConnections(); await new Promise(done => server.close(done)); },
};
}
diff --git a/store/agents/autonomous-grid/viewer/app.css b/store/agents/autonomous-grid/viewer/app.css
index d321dc287..1f6e42fdb 100644
--- a/store/agents/autonomous-grid/viewer/app.css
+++ b/store/agents/autonomous-grid/viewer/app.css
@@ -132,6 +132,10 @@
.menu-row .row-title{flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.menu-row .row-detail{font-size:11px;color:var(--ink-2);white-space:nowrap}
.menu-empty{padding:5px 14px 6px;font-size:11px;color:var(--ink-3)}
+.wake-bar{display:flex;align-items:center;justify-content:space-between;gap:14px;margin:8px 26px 0;padding:8px 8px 8px 13px;border:1px solid var(--notice-border);border-radius:8px;background:var(--notice-bg);color:var(--notice-ink);font-size:12px;line-height:1.5}
+.wake-bar p{min-width:0}
+.wake-bar button{flex-shrink:0;background:transparent;border:1px solid var(--notice-border);border-radius:6px;padding:5px 11px;color:var(--gold);font-size:12px;white-space:nowrap}
+.wake-bar button:hover:not(:disabled){background:var(--overlay-hover)}
.topology{flex:1;min-height:0;position:relative;isolation:isolate;overflow:hidden;background:radial-gradient(ellipse at 52% 49%,var(--nebula-1),transparent 48%),radial-gradient(ellipse at 97% 50%,var(--nebula-2),transparent 55%)}
#connections{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
.map-heading{position:absolute;left:26px;top:14px;display:flex;flex-direction:column;gap:5px;pointer-events:none}
@@ -235,7 +239,7 @@
.gpu-detail+.gpu-detail{margin-top:18px}
@media(min-width:1051px){.topology[data-density=spacious] .node{min-width:210px;max-width:250px}}
@media(min-width:1500px){.workspace{grid-template-columns:minmax(0,1fr) 340px}.inspector{padding:24px 28px}.node{min-width:166px;padding:16px}.node-name{font-size:14px}.node-model{font-size:11px}}
-@media(max-width:1050px){.workspace{grid-template-columns:minmax(0,1fr) 270px}.inspector{padding:16px 18px}.node{min-width:126px;max-width:158px;padding:10px}.node-hardware{max-width:140px}.view-toolbar{padding-left:23px;padding-right:23px}.map-heading{left:23px}.map-controls{left:23px;right:23px}.fleet-totals{gap:30px}.total-label{letter-spacing:1px}.fleet-totals strong{font-size:20px}}
+@media(max-width:1050px){.workspace{grid-template-columns:minmax(0,1fr) 270px}.wake-bar{margin-left:23px;margin-right:23px}.inspector{padding:16px 18px}.node{min-width:126px;max-width:158px;padding:10px}.node-hardware{max-width:140px}.view-toolbar{padding-left:23px;padding-right:23px}.map-heading{left:23px}.map-controls{left:23px;right:23px}.fleet-totals{gap:30px}.total-label{letter-spacing:1px}.fleet-totals strong{font-size:20px}}
@media(max-width:820px){.workspace{position:relative;grid-template-columns:minmax(0,1fr)}.inspector{position:absolute;top:0;right:0;bottom:0;width:min(300px,92%);padding:18px 20px;box-shadow:-12px 0 32px var(--scrim);display:none}.inspector.open{display:block}.inspector-head{margin-bottom:12px}.inspector .detail-section{margin-top:19px;padding-top:19px}.node{min-width:134px}}
-@media(max-width:540px){.view-toolbar{padding:10px 16px 0;gap:8px}.menu-button{gap:5px;padding:5px 7px}.menu-value{max-width:96px}.segmented button{padding:7px 10px;font-size:11px}.map-heading{left:18px;top:23px}.map-subtitle{font-size:10px}.eyebrow{font-size:9px}.node{min-width:111px;max-width:142px;padding:10px;border-radius:8px}.node-name{font-size:11px}.node-model{font-size:9px}.node-reading{font-size:16px;margin-top:8px}.node-reading small,.node-hardware{font-size:9px}.node-hardware{max-width:127px;bottom:-18px}.hub{width:110px;padding:11px 5px}.hub-name{font-size:20px}.hub-kicker{font-size:7px}.map-controls{left:18px;right:18px;font-size:9px;gap:8px}.map-controls button{font-size:10px}.fleet-totals{gap:20px;padding:6px 18px 8px;justify-content:space-between}.total-label{font-size:8px;letter-spacing:.7px}.fleet-totals strong{font-size:20px}.fleet-totals>div>span:last-child{font-size:9px;max-width:94px;line-height:1.5}.activity{padding:10px 18px}.rack{padding:12px 18px}}
+@media(max-width:540px){.view-toolbar{padding:10px 16px 0;gap:8px}.wake-bar{margin:8px 16px 0;font-size:11px}.menu-button{gap:5px;padding:5px 7px}.menu-value{max-width:96px}.segmented button{padding:7px 10px;font-size:11px}.map-heading{left:18px;top:23px}.map-subtitle{font-size:10px}.eyebrow{font-size:9px}.node{min-width:111px;max-width:142px;padding:10px;border-radius:8px}.node-name{font-size:11px}.node-model{font-size:9px}.node-reading{font-size:16px;margin-top:8px}.node-reading small,.node-hardware{font-size:9px}.node-hardware{max-width:127px;bottom:-18px}.hub{width:110px;padding:11px 5px}.hub-name{font-size:20px}.hub-kicker{font-size:7px}.map-controls{left:18px;right:18px;font-size:9px;gap:8px}.map-controls button{font-size:10px}.fleet-totals{gap:20px;padding:6px 18px 8px;justify-content:space-between}.total-label{font-size:8px;letter-spacing:.7px}.fleet-totals strong{font-size:20px}.fleet-totals>div>span:last-child{font-size:9px;max-width:94px;line-height:1.5}.activity{padding:10px 18px}.rack{padding:12px 18px}}
@media(prefers-reduced-motion:reduce){*{transition:none!important}}
diff --git a/store/agents/autonomous-grid/viewer/app.js b/store/agents/autonomous-grid/viewer/app.js
index c21f7d5a8..e315d2de5 100644
--- a/store/agents/autonomous-grid/viewer/app.js
+++ b/store/agents/autonomous-grid/viewer/app.js
@@ -59,7 +59,7 @@
$('map-subtitle').textContent=snapshot.nodes.length>12?`12 of ${snapshot.nodes.length} engines · see every engine in Rack`:'Every machine has a place.';
$('map-empty').hidden=graphNodes.length>0;
$('hub').hidden=graphNodes.length===0;
- $('empty-message').textContent=snapshot.status==='asleep'?'Resting to save resources. It starts by itself when you send a message.':snapshot.status==='unconfigured'?'Ask the Model Manager to connect one of your existing grids, or help you create your first fleet.':snapshot.status==='unavailable'?'Grid isn’t reachable yet. Ask the agent to check your connection, choose a grid, or start one.':'Ask the Model Manager to discover this machine and deploy your first model.';
+ $('empty-message').textContent=snapshot.status==='asleep'?window.harnessViewerWake.RESTING:snapshot.status==='unconfigured'?'Ask the Model Manager to connect one of your existing grids, or help you create your first fleet.':snapshot.status==='unavailable'?'Grid isn’t reachable yet. Ask the agent to check your connection, choose a grid, or start one.':'Ask the Model Manager to discover this machine and deploy your first model.';
$('hub-status').textContent=snapshot.status==='asleep'?'asleep':snapshot.status==='updating'?'earlier reading':available?`${snapshot.summary.enginesOnline || 0} engines online`:'awaiting connection';
const ids=new Set(graphNodes.map(n=>n.id));
for (const [id,b] of nodeButtons) if (!ids.has(id)) { b.remove();nodeButtons.delete(id); }
@@ -86,8 +86,31 @@
const usage=finite(n.memoryUsedGb)&&n.memoryTotalGb>0?Math.min(100,n.memoryUsedGb/n.memoryTotalGb*100):null;
b.innerHTML=`<span class="node-head"><span class="node-name">${escape(n.name)}</span><span class="node-dot"></span></span><span class="node-model" style="display:block">${escape(n.models[0] || 'No models')}${n.models.length>1?` +${n.models.length-1}`:''}</span><span class="node-reading">${metricMarkup(n)}</span>${usage!==null?`<span class="node-bar" style="display:block"><span style="width:${usage}%"></span></span>`:''}<span class="node-hardware">${escape(n.hardware || n.engine)}</span>`;
}
- renderRack();renderInspector();renderActivity();resize();status();
+ renderRack();renderInspector();renderActivity();renderWake();resize();status();
}
+ // The asleep view's "Wake now" — the one control on this page that may start a grid. The daemon does
+ // the starting (viewer.mjs, lib/wake.mjs); this draws what the snapshot says about it (wake.js).
+ let wakeShown=null;
+ function renderWake() {
+ const view=window.harnessViewerWake.wakeView(snapshot);
+ $('wake-bar').hidden=view.hidden;
+ if(!view.hidden){$('wake-message').textContent=view.message;$('wake-now').hidden=!view.button;$('wake-now').disabled=view.disabled;}
+ // Started and seen serving, the bar is gone: the toast is what says the click worked.
+ const state=snapshot?.wake?.state||null;
+ if(wakeShown==='waking'&&state==='awake')toast(snapshot.wake.message);
+ wakeShown=state;
+ }
+ $('wake-now').addEventListener('click',async()=>{
+ $('wake-now').disabled=true;
+ try{
+ const r=await fetch('api/wake',{method:'POST',headers:{'content-type':'application/json'},body:'{}',signal:AbortSignal.timeout(12_000)});
+ const body=await r.json().catch(()=>({}));
+ if(!r.ok)throw new Error(body.error||'Could not start it right now.');
+ // The answer carries the run; the stream brings the same a moment later (or already has).
+ if(body.wake&&snapshot&&snapshot.grid===body.wake.grid)snapshot={...snapshot,wake:body.wake};
+ }catch(err){toast(err.message||'Could not start it right now.');}
+ finally{renderWake();}
+ });
function select(id) {selected=selected===id?null:id;for(const [key,b]of nodeButtons)b.setAttribute('aria-pressed',String(key===selected));renderInspector();renderRack();draw();}
function renderRack() {
if(!snapshot)return;
diff --git a/store/agents/autonomous-grid/viewer/index.html b/store/agents/autonomous-grid/viewer/index.html
index e0074013c..461455d38 100644
--- a/store/agents/autonomous-grid/viewer/index.html
+++ b/store/agents/autonomous-grid/viewer/index.html
@@ -7,6 +7,7 @@
<title>Model Manager</title>
<link rel="stylesheet" href="app.css">
<script src="stream.js" defer></script>
+ <script src="wake.js" defer></script>
<script src="app.js" defer></script>
</head>
<body>
@@ -17,6 +18,7 @@
<div class="segmented" aria-label="Fleet view"><button id="topology-button" type="button" aria-pressed="true">Topology</button><button id="rack-button" type="button" aria-pressed="false">Rack</button></div>
<div class="toolbar-selects"><div class="menu"><button type="button" class="menu-button" id="grid-select" aria-haspopup="listbox" aria-expanded="false"><span class="menu-kicker">Grid</span><span class="menu-value" id="grid-value">Choose your grid</span><span class="menu-chevron" aria-hidden="true">▾</span></button><div class="menu-list" id="grid-list" role="listbox" aria-label="Grid" hidden></div></div><div class="menu"><button type="button" class="menu-button" id="metric" aria-haspopup="listbox" aria-expanded="false"><span class="menu-kicker">Show</span><span class="menu-value" id="metric-value">Decode speed</span><span class="menu-chevron" aria-hidden="true">▾</span></button><div class="menu-list" id="metric-list" role="listbox" aria-label="Show" hidden></div></div></div>
</div>
+ <div class="wake-bar" id="wake-bar" role="status" hidden><p id="wake-message"></p><button type="button" id="wake-now">Wake now</button></div>
<div class="topology" id="topology">
<canvas id="connections" aria-hidden="true"></canvas>
<div class="map-heading"><span class="eyebrow">YOUR COMPUTE, CONNECTED</span><span class="map-subtitle" id="map-subtitle">Every machine has a place.</span></div>
diff --git a/store/agents/autonomous-grid/viewer/wake.js b/store/agents/autonomous-grid/viewer/wake.js
new file mode 100644
index 000000000..f581f446d
--- /dev/null
+++ b/store/agents/autonomous-grid/viewer/wake.js
@@ -0,0 +1,19 @@
+// What the page's wake bar shows for a snapshot: the asleep view's "Wake now", held while the daemon
+// starts the grid, and the sentence it ended with (viewer.mjs publishes it as `snapshot.wake`).
+//
+// A file of its own, loaded before app.js, so a test can run exactly this code without a browser
+// (test/wake.test.mjs) — the same arrangement as stream.js.
+(root => {
+ 'use strict';
+ const RESTING = 'Resting to save resources. It starts by itself when you send a message.';
+ function wakeView(snapshot) {
+ const asleep = snapshot?.status === 'asleep', wake = snapshot?.wake || null;
+ if (wake?.state === 'waking') return { hidden: false, message: wake.message, button: true, disabled: true };
+ // Started: the engines on the map are the answer. Until the read that draws them lands, say so.
+ if (wake?.state === 'awake') return asleep ? { hidden: false, message: wake.message, button: false, disabled: true } : { hidden: true };
+ // Any other ending stands where it happened; a grid still asleep can be asked again.
+ if (wake) return { hidden: false, message: wake.message, button: asleep, disabled: false };
+ return asleep ? { hidden: false, message: RESTING, button: true, disabled: false } : { hidden: true };
+ }
+ root.harnessViewerWake = { RESTING, wakeView };
+})(globalThis);