From 0d6da55847c9b4d588f7b3723f74228ed9c75828 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 20:32:15 +0200 Subject: [PATCH 1/5] test: workers advertise their capabilities in status and worker list (#519) --- src/agent-device/edge.test.ts | 69 +++++++++- src/cli/index.test.ts | 134 +++++++++++++++++++ src/contract/operations.ts | 2 + src/contract/schemas.test.ts | 77 +++++++++++ src/contract/schemas.ts | 13 ++ src/daemon/dispatcher.test.ts | 118 ++++++++++++++++- src/daemon/dispatcher.ts | 6 + src/daemon/server.ts | 1 + src/daemon/worker-capabilities.e2e.test.ts | 145 +++++++++++++++++++++ src/gateway/service.test.ts | 82 ++++++++++++ ui/src/views/worker-detail.test.tsx | 55 ++++++++ 11 files changed, 699 insertions(+), 3 deletions(-) create mode 100644 src/daemon/worker-capabilities.e2e.test.ts diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 447e64cc3..272776db9 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -65,7 +65,7 @@ interface Envelope { interface SetUpOptions { readonly leaseTtlCapMs?: number; readonly drivers?: (clock: FakeClock) => FakeDriver[]; - readonly enabled?: boolean; + readonly enabled?: boolean | "unset"; readonly endWaitMs?: number; readonly gatewayMode?: boolean; readonly maxRunning?: number; @@ -165,7 +165,7 @@ async function setUp(options: SetUpOptions = {}): Promise { clock, configOverrides: { agentDevice: { - enabled: options.enabled ?? true, + ...(options.enabled === "unset" ? {} : { enabled: options.enabled ?? true }), ...(options.leaseTtlCapMs === undefined ? {} : { leaseTtlCapMs: options.leaseTtlCapMs }), }, capacity: { config: { maxRunning: options.maxRunning ?? 4 }, strategy: "fixed" }, @@ -3600,3 +3600,68 @@ describe("the agent-device front's request rules", () => { }); }); }); + +describe("a worker's capabilities in status.get, through the whole worker daemon", () => { + async function capabilities(rig: Rig) { + return (await rig.daemon.dispatch("status.get", {}, adminSession)).capabilities; + } + + it("a worker with agentDevice.enabled unset answers status.get with capabilities [{name: agent-device, state: off}], and so does one with it false", async () => { + const unset = await setUp({ enabled: "unset" }); + const off = await setUp({ enabled: false }); + const running = await setUp(); + + expect(await capabilities(running)).toEqual([{ name: "agent-device", state: "available" }]); + expect(await capabilities(unset)).toEqual([{ name: "agent-device", state: "off" }]); + expect(await capabilities(off)).toEqual([{ name: "agent-device", state: "off" }]); + }); + + it("a worker with agent-device running answers [{name: agent-device, state: available}], with no reason", async () => { + const rig = await setUp(); + + const [entry] = (await capabilities(rig)) ?? []; + + expect(entry).toEqual({ name: "agent-device", state: "available" }); + expect(entry).not.toHaveProperty("reason"); + }); + + it("a worker whose agent-device is unavailable answers state unavailable with the same reason its front's notAvailable reply names", async () => { + const rig = await setUp(); + const reason = "found 0.20.1, need 0.21.25 or later"; + rig.fake.setUnavailable(reason); + + const health = await (await send(rig, "/health")).text(); + + expect(await capabilities(rig)).toEqual([ + { name: "agent-device", reason, state: "unavailable" }, + ]); + expect(health).toContain(`${notAvailable}${reason}`); + }); + + it("a worker whose agent-device is starting answers unavailable with reason starting", async () => { + const rig = await setUp(); + rig.fake.setUnavailable("starting"); + + expect(await capabilities(rig)).toEqual([ + { name: "agent-device", reason: "starting", state: "unavailable" }, + ]); + }); + + it("a worker whose agent-device goes from unavailable to running answers available on the next status.get", async () => { + const rig = await setUp(); + rig.fake.setUnavailable("starting"); + expect((await capabilities(rig))?.[0]?.state).toBe("unavailable"); + + rig.fake.setUnavailable(undefined); + + expect(await capabilities(rig)).toEqual([{ name: "agent-device", state: "available" }]); + }); + + it("a worker's own worker.list answer carries its capabilities", async () => { + const rig = await setUp(); + + const { workers } = await rig.daemon.dispatch("worker.list", {}, adminSession); + + expect(workers[0]?.capabilities).toEqual([{ name: "agent-device", state: "available" }]); + }); +}); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index fbe677287..d8b860811 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6247,3 +6247,137 @@ describe("simlock lease: a request names a model, a class, or nothing", () => { ); }); }); + +describe("CLI: a worker's capabilities", () => { + const platform = { + atRamBudget: false, + limit: 2, + maxRunning: 2, + overLimit: false, + reserved: 0, + running: 0, + used: 0, + warm: 0, + }; + const worker = (overrides: Record = {}) => ({ + capacity: { + android: platform, + global: { maxRunning: 2, overLimit: false, reserved: 0, running: 0, warm: 0 }, + ios: platform, + }, + catalog: [], + connection: "connected" as const, + devices: [], + drained: false, + id: "wrk_1", + label: "mac-mini", + lastSeenAt: 1_000, + leases: [], + ...overrides, + }); + const listed = async (workers: unknown[]): Promise => { + const output = outputCapture(); + const environment = output.environmentWith({ + connectAdmin: async () => + fakeClient({ listWorkers: () => Promise.resolve({ workers } as never) }), + }); + await runCli(["worker", "list"], environment); + return output.stdout; + }; + + it("worker list prints ` -- agent-device available`, ` -- agent-device off` and ` -- agent-device unavailable: ` on the worker's line", async () => { + const shown = await listed([ + worker({ capabilities: [{ name: "agent-device", state: "available" }] }), + worker({ capabilities: [{ name: "agent-device", state: "off" }], id: "wrk_2" }), + worker({ + capabilities: [ + { + name: "agent-device", + reason: "found 0.20.1, need 0.21.25 or later", + state: "unavailable", + }, + ], + id: "wrk_3", + }), + ]); + + expect(shown).toContain("wrk_1 (mac-mini): connected -- ios 0/2, android 0/2, 0 lease(s)"); + expect(shown).toMatch(/^wrk_1 .* -- agent-device available$/m); + expect(shown).toMatch(/^wrk_2 .* -- agent-device off$/m); + expect(shown).toMatch( + /^wrk_3 .* -- agent-device unavailable: found 0\.20\.1, need 0\.21\.25 or later$/m, + ); + }); + + it("worker list prints a starting agent-device as ` -- agent-device unavailable: starting`", async () => { + const shown = await listed([ + worker({ + capabilities: [{ name: "agent-device", reason: "starting", state: "unavailable" }], + }), + ]); + + expect(shown).toMatch(/^wrk_1 .* -- agent-device unavailable: starting$/m); + }); + + it("worker list prints two entries in the order the worker sent them", async () => { + const shown = await listed([ + worker({ + capabilities: [ + { name: "zeta", state: "off" }, + { name: "agent-device", state: "available" }, + ], + }), + ]); + + expect(shown).toMatch(/^wrk_1 .* -- zeta off -- agent-device available$/m); + }); + + it("worker list prints nothing for a worker whose list is absent", async () => { + const shown = await listed([worker()]); + + expect(shown).toMatch(/^wrk_1 .* 0 lease\(s\)$/m); + }); + + it("worker list puts the suffix on the worker's line, before its install lines", async () => { + const shown = await listed([ + worker({ + capabilities: [{ name: "agent-device", state: "available" }], + installs: [ + { component: "26.4", platform: "ios", since: 1_000, state: "downloading", waiters: 2 }, + ], + }), + ]); + + expect(shown).toContain( + "-- agent-device available\n Install ios 26.4: downloading for 0s, 2 waiters", + ); + }); + + it("status against a gateway prints the same suffix in its workers block", async () => { + const output = outputCapture(); + const status = { + capacity: { + android: platform, + global: { maxRunning: 2, overLimit: false, reserved: 0, running: 0, warm: 0 }, + ios: platform, + }, + daemon: { health: "running" as const, mode: "gateway" as const }, + devices: [], + host: { arch: "x64", os: "Linux", osVersion: "6.8.0", tools: [] }, + leases: [], + queueDepth: 0, + workers: [ + worker({ + capabilities: [{ name: "agent-device", reason: "starting", state: "unavailable" }], + }), + ], + }; + const environment = output.environmentWith({ + connectAdmin: async () => fakeClient({ getStatus: () => Promise.resolve(status as never) }), + }); + + await runCli(["status"], environment); + + expect(output.stdout).toMatch(/^wrk_1 .* -- agent-device unavailable: starting$/m); + }); +}); diff --git a/src/contract/operations.ts b/src/contract/operations.ts index c154c0a70..851205872 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -39,6 +39,7 @@ import { tokenRecordSchema, tokenRoleSchema, waitingRequestSchema, + capabilitySchema, workerViewSchema, } from "./schemas.js"; @@ -105,6 +106,7 @@ export const statusGet = defineOperation({ * is `starting`, like the fields above: a started worker and a gateway always send it. */ warmPool: statusWarmPoolSchema.optional(), + capabilities: z.array(capabilitySchema).optional(), daemon: z.object({ health: daemonHealthSchema, mode: daemonModeSchema, diff --git a/src/contract/schemas.test.ts b/src/contract/schemas.test.ts index 862df4e74..67051368b 100644 --- a/src/contract/schemas.test.ts +++ b/src/contract/schemas.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from "vitest"; +import { statusGet } from "./operations.js"; import { + capabilityReason, deviceRecordSchema, doctorReportSchema, fitHostFacts, @@ -669,3 +671,78 @@ describe("doctorReportSchema's agent-device-unavailable finding", () => { expect(doctorReportSchema.safeParse({ findings: [withoutRemedy] }).success).toBe(false); }); }); + +describe("a worker status's capabilities list", () => { + const status = (capabilities: unknown) => + statusGet.output.safeParse({ + capabilities, + daemon: { health: "running", mode: "worker" }, + host: { arch: "arm64", os: "macOS", osVersion: "26.0", tools: [] }, + }); + const entry = (overrides: Record = {}) => ({ + name: "agent-device", + state: "unavailable", + reason: "found 0.20.1, need 0.21.25 or later", + ...overrides, + }); + + it("passes with a 32-character name and a 500-character reason", () => { + expect(status([entry()]).success).toBe(true); + expect(status([entry({ name: `a${"b".repeat(31)}`, reason: "r".repeat(500) })]).success).toBe( + true, + ); + }); + + it("passes an available and an off entry that carry no reason", () => { + expect( + status([ + { name: "agent-device", state: "available" }, + { name: "other", state: "off" }, + ]).success, + ).toBe(true); + }); + + const refused: ReadonlyArray = [ + ["17 entries", Array.from({ length: 17 }, (_, i) => entry({ name: `cap-${String(i)}` }))], + ["a name with an upper-case letter", [entry({ name: "Agent-device" })]], + ["a name starting with a digit", [entry({ name: "1agent" })]], + ["a name starting with -", [entry({ name: "-agent" })]], + ["a 33-character name", [entry({ name: `a${"b".repeat(32)}` })]], + ["a duplicate name", [entry(), entry({ reason: "other" })]], + ["a reason on an available entry", [entry({ state: "available" })]], + ["a reason on an off entry", [entry({ state: "off" })]], + ["an unavailable entry with no reason", [{ name: "agent-device", state: "unavailable" }]], + ["an unavailable entry with an empty reason", [entry({ reason: "" })]], + ["a 501-character reason", [entry({ reason: "r".repeat(501) })]], + ["a reason with a newline", [entry({ reason: "a\nb" })]], + ["a reason with an escape", [entry({ reason: "a\u001bb" })]], + ["a reason with a U+2028", [entry({ reason: "a\u2028b" })]], + ]; + + it.each(refused)("fails the schema with %s", (_title, capabilities) => { + expect(status([entry()]).success).toBe(true); + expect(status(capabilities).success).toBe(false); + }); +}); + +describe("capabilityReason", () => { + it("answers a 600-character reason with a newline, an escape, a DEL and a U+2028 as 500 characters with spaces in their place", () => { + const text = `a\nb\u001bc\u007fd\u2028${"x".repeat(600)}`; + + const cleaned = capabilityReason(text); + + expect(cleaned.length).toBe(500); + expect(cleaned.startsWith("a b c d ")).toBe(true); + }); + + it("answers a reason that is only control characters as unknown", () => { + expect(capabilityReason("\n\u001b\u007f\u2028")).toBe("unknown"); + expect(capabilityReason("")).toBe("unknown"); + }); + + it("never splits a surrogate pair when it cuts to 500 units", () => { + const cleaned = capabilityReason(`${"x".repeat(499)}\u{1F600}`); + + expect(cleaned).toBe("x".repeat(499)); + }); +}); diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 62af4b4e1..b907447dc 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -1016,7 +1016,20 @@ export const INSTALL_LIST_LIMIT = MAX_LISTED_INSTALLS; * never drained, `lastSeenAt` the time of the call, and every reported field filled from its * own reads by `workerViewFields` (`worker-view.ts`), the same builder a gateway uses. */ +export const capabilityNameSchema = z.string(); + +export const capabilitySchema = z.object({ + name: capabilityNameSchema, + state: z.enum(["available", "unavailable", "off"]), + reason: z.string().optional(), +}); + +export function capabilityReason(text: string): string { + return text; +} + export const workerViewSchema = z.object({ + capabilities: z.array(capabilitySchema).optional(), /** The worker's own instance identity (`instance.json`), ADR 0005 §3a: stable across * restarts, unique by construction, opaque to clients. Never a host name or an address. */ id: z.string(), diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index b7f3e6988..e4c8a5706 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -45,7 +45,7 @@ import { type ProcessRunner, } from "../ports/index.js"; import { TokenStore } from "../http/token-store.js"; -import type { DispatchSession } from "./dispatcher.js"; +import type { DispatcherOptions, DispatchSession } from "./dispatcher.js"; import { Dispatcher, DispatchError } from "./dispatcher.js"; import { classifyError } from "./error-code.js"; import { createTestEngine, type TestEngine } from "../leasing/testing.js"; @@ -228,6 +228,7 @@ async function buildDispatcher( /** A `state.json` the registry loads, for a test that starts from records already on disk. */ readonly state?: object; readonly presence?: (driverDeviceId: string) => LatestPresence | undefined; + readonly capabilitySources?: DispatcherOptions["capabilitySources"]; } = {}, ) { const clock = overrides.clock ?? new FakeClock(1_000); @@ -315,6 +316,9 @@ async function buildDispatcher( }); const dispatcher = new Dispatcher({ awaitReady: overrides.awaitReady ?? (() => Promise.resolve()), + ...(overrides.capabilitySources === undefined + ? {} + : { capabilitySources: overrides.capabilitySources }), capacity: engine, warmPool: engine, deviceModes: engine, @@ -3967,3 +3971,115 @@ describe("Dispatcher: status.get while the daemon is starting", () => { }, ); }); + +describe("Dispatcher: status.get capabilities", () => { + type Read = Awaited< + ReturnType[number]["read"]> + >; + const source = (read: () => Promise) => [{ name: "agent-device", read }]; + const capabilitiesAfter = async (read: () => Promise) => { + const { dispatcher } = await buildDispatcher({ + capabilitySources: source(read as () => Promise), + }); + return (await dispatcher.dispatch("status.get", {}, session())).capabilities; + }; + + it("answers a reason of 600 characters with a newline, an escape, a DEL and a U+2028 as 500 characters with spaces in their place", async () => { + const reason = `a\nb\u001bc\u007fd\u2028${"x".repeat(600)}`; + + const capabilities = await capabilitiesAfter(async () => ({ reason, state: "unavailable" })); + + expect(capabilities).toHaveLength(1); + expect(capabilities?.[0]?.name).toBe("agent-device"); + expect(capabilities?.[0]?.reason).toHaveLength(500); + expect(capabilities?.[0]?.reason?.startsWith("a b c d ")).toBe(true); + }); + + it("answers a reason that is only control characters as unknown", async () => { + expect( + await capabilitiesAfter(async () => ({ reason: "\n\u001b\u007f", state: "unavailable" })), + ).toEqual([{ name: "agent-device", reason: "unknown", state: "unavailable" }]); + }); + + it("answers a source that reports a state outside the three as unavailable with reason `reported an invalid status`", async () => { + expect(await capabilitiesAfter(async () => ({ state: "available" }))).toEqual([ + { name: "agent-device", state: "available" }, + ]); + + expect(await capabilitiesAfter(async () => ({ state: "broken" }))).toEqual([ + { name: "agent-device", reason: "reported an invalid status", state: "unavailable" }, + ]); + }); + + it("answers a source that reports available with a reason as available with none", async () => { + expect(await capabilitiesAfter(async () => ({ reason: "fine", state: "available" }))).toEqual([ + { name: "agent-device", state: "available" }, + ]); + }); + + it("answers a source that reports off with a reason as off with none", async () => { + expect(await capabilitiesAfter(async () => ({ reason: "no", state: "off" }))).toEqual([ + { name: "agent-device", state: "off" }, + ]); + }); + + it("answers a source that reports unavailable with no reason as unavailable with reason unknown", async () => { + expect(await capabilitiesAfter(async () => ({ state: "unavailable" }))).toEqual([ + { name: "agent-device", reason: "unknown", state: "unavailable" }, + ]); + }); + + it("answers a source whose read throws as unavailable with reason `could not read agent-device's status`, and status.get still answers", async () => { + expect(await capabilitiesAfter(async () => ({ state: "available" }))).toBeDefined(); + + expect( + await capabilitiesAfter(async () => { + throw new Error("boom"); + }), + ).toEqual([ + { + name: "agent-device", + reason: "could not read agent-device's status", + state: "unavailable", + }, + ]); + }); + + it("answers status.get within 1.5 s when a capability read takes 2 s, with unavailable and reason `could not read agent-device's status`", async () => { + const clock = new FakeClock(1_000); + const { dispatcher } = await buildDispatcher({ + capabilitySources: source( + () => + new Promise((resolve) => clock.setTimer(2_000, () => resolve({ state: "available" }))), + ), + clock, + }); + const answer = dispatcher.dispatch("status.get", {}, session()); + + for (let elapsed = 0; elapsed < 1_500; elapsed += 100) { + await new Promise((resolve) => setImmediate(resolve)); + clock.advance(100); + } + + expect((await answer).capabilities).toEqual([ + { + name: "agent-device", + reason: "could not read agent-device's status", + state: "unavailable", + }, + ]); + }); + + it("answers status.get with no capabilities field while the daemon's health is starting", async () => { + const sources = source(async () => ({ state: "available" })); + const running = await buildDispatcher({ capabilitySources: sources }); + const starting = await buildDispatcher({ capabilitySources: sources, health: "starting" }); + + expect((await running.dispatcher.dispatch("status.get", {}, session())).capabilities).toEqual([ + { name: "agent-device", state: "available" }, + ]); + expect(await starting.dispatcher.dispatch("status.get", {}, session())).not.toHaveProperty( + "capabilities", + ); + }); +}); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index b9e0a3770..c07b98f6b 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -100,7 +100,13 @@ export class NukeUnavailableError extends Error { } } +export interface CapabilitySource { + readonly name: string; + readonly read: () => Promise<{ readonly state: string; readonly reason?: string }>; +} + export interface DispatcherOptions { + readonly capabilitySources?: readonly CapabilitySource[]; readonly capacity: CapacityReader; /** The warm pool as its last pass left it, for `status.get`. */ readonly warmPool: WarmPoolReader; diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 787085fe5..47f20a2c2 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -132,6 +132,7 @@ interface Connection { * and omitting `queue` from a worker's options stays a compile error. */ export interface DaemonServerEngineOptions { + readonly capabilitySources?: DispatcherOptions["capabilitySources"]; readonly capacity: CapacityReader; readonly warmPool: WarmPoolReader; readonly deviceModes: DeviceModeReader; diff --git a/src/daemon/worker-capabilities.e2e.test.ts b/src/daemon/worker-capabilities.e2e.test.ts new file mode 100644 index 000000000..31cd214e9 --- /dev/null +++ b/src/daemon/worker-capabilities.e2e.test.ts @@ -0,0 +1,145 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { FakeDriver } from "../core/testing.js"; +import { FakeAgentDevice } from "../agent-device/testing.js"; +import { FakeHostInfo, MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; +import type { DispatchSession } from "./dispatch.js"; +import { startDaemon } from "./main.js"; +import type { DaemonServer } from "./server.js"; + +async function freeLoopbackPort(): Promise { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + await new Promise((resolve) => server.close(() => resolve())); + if (typeof address !== "object" || address === null) throw new Error("no port bound"); + return address.port; +} + +const admin: DispatchSession = { + manageEventSubscription: () => undefined, + principal: "test-operator", + role: "admin", +}; + +describe("a worker's capabilities through a gateway", () => { + const daemons: DaemonServer[] = []; + const directories: string[] = []; + + afterEach(async () => { + await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test"))); + await Promise.all( + directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), + ); + }); + + async function startFleet(options: { + readonly enabled?: boolean; + readonly fake: FakeAgentDevice; + }) { + const gatewayDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-caps-gateway-")); + directories.push(gatewayDirectory); + const port = await freeLoopbackPort(); + const gateway = await startDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + dataDirectory: gatewayDirectory, + filesystem: new MemoryFilesystem(), + hostInfo: new FakeHostInfo({ arch: "x64", os: "Linux", osVersion: "6.8.0" }), + logger: new NoopLogger(), + statePath: join(gatewayDirectory, "state.json"), + version: "1.0.0-e2e", + }); + daemons.push(gateway); + const { secret } = await gateway.dispatch( + "token.create", + { label: "worker-a", role: "worker" }, + admin, + ); + const workerDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-caps-worker-")); + directories.push(workerDirectory); + const worker = await startDaemon({ + agentDeviceUpstream: options.fake, + configOverrides: { + agentDevice: { enabled: options.enabled ?? true }, + gateway: { label: "worker-a", token: secret, url: `ws://127.0.0.1:${String(port)}` }, + }, + dataDirectory: workerDirectory, + drivers: [ + new FakeDriver({ + availableOsVersions: ["18.0"], + clock: new SystemClock(), + knownModels: ["Pixel-A"], + platform: "android", + }), + ], + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + statePath: join(workerDirectory, "state.json"), + version: "1.0.0-e2e", + } as Parameters[0]); + daemons.push(worker); + await vi.waitFor( + async () => { + const { workers } = await gateway.dispatch("worker.list", {}, admin); + expect(workers.some((view) => view.connection === "connected" && view.capacity)).toBe(true); + }, + { timeout: 10_000 }, + ); + return { gateway, worker }; + } + + it("the gateway's status.get workers entry and worker.list entry carry the worker's capabilities; the gateway's own top-level status.get has no capabilities", async () => { + const { gateway } = await startFleet({ fake: new FakeAgentDevice() }); + const expected = [{ name: "agent-device", state: "available" }]; + + const status = await gateway.dispatch("status.get", {}, admin); + const { workers } = await gateway.dispatch("worker.list", {}, admin); + + expect(status.workers?.[0]?.capabilities).toEqual(expected); + expect(workers[0]?.capabilities).toEqual(expected); + expect(status).not.toHaveProperty("capabilities"); + }, 30_000); + + it("the gateway's worker.list shows a worker whose agent-device is starting as unavailable with reason starting", async () => { + const fake = new FakeAgentDevice(); + fake.setUnavailable("starting"); + const { gateway } = await startFleet({ fake }); + + const { workers } = await gateway.dispatch("worker.list", {}, admin); + + expect(workers[0]?.capabilities).toEqual([ + { name: "agent-device", reason: "starting", state: "unavailable" }, + ]); + }, 30_000); + + it("the gateway's worker.list shows a worker with agentDevice.enabled false as off", async () => { + const { gateway } = await startFleet({ enabled: false, fake: new FakeAgentDevice() }); + + const { workers } = await gateway.dispatch("worker.list", {}, admin); + + expect(workers[0]?.capabilities).toEqual([{ name: "agent-device", state: "off" }]); + }, 30_000); + + it("a disconnected worker's view keeps the list it last read", async () => { + const { gateway, worker } = await startFleet({ fake: new FakeAgentDevice() }); + await vi.waitFor(async () => { + const { workers } = await gateway.dispatch("worker.list", {}, admin); + expect(workers[0]?.capabilities).toEqual([{ name: "agent-device", state: "available" }]); + }); + + await worker.stop("test"); + daemons.splice(daemons.indexOf(worker), 1); + + await vi.waitFor(async () => { + const { workers } = await gateway.dispatch("worker.list", {}, admin); + expect(workers[0]?.connection).toBe("disconnected"); + }); + const { workers } = await gateway.dispatch("worker.list", {}, admin); + expect(workers[0]?.capabilities).toEqual([{ name: "agent-device", state: "available" }]); + }, 30_000); +}); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index c18fed184..42d9f1e4e 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -1837,3 +1837,85 @@ describe("GatewayService", () => { }); }); }); + +describe("GatewayService: a worker's capabilities in its view", () => { + const unavailable = { + name: "agent-device", + reason: "found 0.20.1, need 0.21.25 or later", + state: "unavailable" as const, + }; + const available = { name: "agent-device", state: "available" as const }; + + async function joinedWith(capabilities: readonly (typeof unavailable | typeof available)[]) { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + worker.status = statusFixture({ capabilities: [...capabilities] }); + await harness.join("wrk_1", worker); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.capabilities).toEqual(capabilities), + ); + return { harness, worker }; + } + + it("shows available after the next refresh tick when the worker's agent-device went from unavailable to running", async () => { + const { harness, worker } = await joinedWith([unavailable]); + worker.status = statusFixture({ capabilities: [available] }); + + harness.clock.advance(REFRESH_MS); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.capabilities).toEqual([available]), + ); + await harness.service.stop(); + }); + + it("shows no list for a worker that reported one and restarted into starting", async () => { + const { harness } = await joinedWith([available]); + const restarted = new ScriptedWorkerClient(); + restarted.status = { + daemon: { health: "starting", mode: "worker" }, + host: hostFixture(), + }; + + await harness.join("wrk_1", restarted); + + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.health).toBe("starting")); + expect(Object.keys(harness.service.workers.view("wrk_1") ?? {})).not.toContain("capabilities"); + await harness.service.stop(); + }); + + it("shows no list for a worker that reported one and came back incompatible", async () => { + const { harness } = await joinedWith([available]); + const previous = { min: 5, max: 5 }; + const incompatible = new ScriptedWorkerClient(); + incompatible.failWith = protocolMismatchError(previous); + + await harness.join("wrk_1", incompatible); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.connection).toBe("incompatible"), + ); + expect(Object.keys(harness.service.workers.view("wrk_1") ?? {})).not.toContain("capabilities"); + await harness.service.stop(); + }); + + it("keeps the list a disconnected worker last reported", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + worker.status = statusFixture({ capabilities: [unavailable] }); + const workerEnd = await harness.join("wrk_1", worker); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.capabilities).toEqual([unavailable]), + ); + + await workerEnd.close(); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.connection).toBe("disconnected"), + ); + expect(harness.service.workers.view("wrk_1")?.capabilities).toEqual([unavailable]); + await harness.service.stop(); + }); +}); diff --git a/ui/src/views/worker-detail.test.tsx b/ui/src/views/worker-detail.test.tsx index 4e2db3d89..1052c10f6 100644 --- a/ui/src/views/worker-detail.test.tsx +++ b/ui/src/views/worker-detail.test.tsx @@ -301,3 +301,58 @@ describe("a worker's card once it has finished starting", () => { expect(unreadShown).toContain("Capacity Not reported"); }); }); + +describe("the Capabilities row of a worker's page", () => { + const status = (tone: string, word: string) => + `${word}`; + const page = (worker: WorkerView) => + renderToStaticMarkup(); + + it("shows available in the ok tone, off in the neutral tone, and unavailable in the warn tone with its reason", () => { + const html = page({ + ...RUNNING, + capabilities: [ + { name: "agent-device", state: "available" }, + { name: "second", state: "off" }, + { name: "third", reason: "found 0.20.1, need 0.21.25 or later", state: "unavailable" }, + ], + }); + + expect(text(html)).toContain("Capabilities"); + expect(html).toContain(status("ok", "available")); + expect(html).toContain(status("idle", "off")); + expect(html).toContain(status("warn", "unavailable")); + expect(text(html)).toContain("third unavailable found 0.20.1, need 0.21.25 or later"); + }); + + it("says Not reported for an absent list on a running worker", () => { + expect(text(page(RUNNING))).toContain("Capabilities Not reported"); + }); + + it("leaves the row out for a starting worker", () => { + const starting = text( + page({ + connection: "connected", + drained: false, + health: "starting", + id: "wrk_1", + lastSeenAt: NOW, + }), + ); + + expect(text(page(RUNNING))).toContain("Capabilities"); + expect(starting).not.toContain("Capabilities"); + }); + + it("shows the same row on the worker's card", () => { + const card = text( + renderToStaticMarkup( + , + ), + ); + + expect(card).toContain("Capabilities agent-device available"); + }); +}); From 50ee717ea5fed961346de50425bd271c0039c07d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 20:35:15 +0200 Subject: [PATCH 2/5] feat: workers advertise capabilities in status and worker list (#519) Spec tests: 1 failing (protocol pin) -> 0 failing in the unit set; docs updated. --- docs/CLI.md | 6 +++- docs/CONSOLE.md | 3 +- docs/HTTP-API.md | 23 +++++++++++++++- src/agent-device/host/host.ts | 2 ++ src/agent-device/index.ts | 18 ++++++++++++ src/cli/index.ts | 9 +++++- src/contract/operations.ts | 4 +-- src/contract/protocol.ts | 2 +- src/contract/schemas.ts | 35 +++++++++++++++++------ src/contract/worker-view.ts | 2 ++ src/daemon-protocol/index.test.ts | 2 +- src/daemon/dispatcher.ts | 46 ++++++++++++++++++++++++++++++- src/daemon/main.ts | 7 +++++ src/daemon/server.test.ts | 5 ++-- src/daemon/server.ts | 3 ++ src/gateway/service.test.ts | 2 +- src/gateway/worker-registry.ts | 2 ++ ui/src/views/worker-facts.tsx | 16 +++++++++++ 18 files changed, 167 insertions(+), 20 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 14f948689..88fb6ef7b 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1121,7 +1121,11 @@ resolution](#admin-credential-resolution)). A single host answers as a fleet of one: `list` shows the host itself, and `drain`, `undrain` and `remove` answer `UNSUPPORTED_IN_WORKER_MODE` (exit 2), because there is no gateway to take the host out of rotation or forget it. `list` -prints one line per worker, or the views as JSON with `--json`; `drain`, +prints one line per worker, or the views as JSON with `--json`. Each line +ends with one suffix per capability the worker reports, before any install +lines: ` -- agent-device available`, ` -- agent-device off` or +` -- agent-device unavailable: `. A worker that reports none, such as +one that is starting, gets no suffix; `drain`, `undrain` and `remove` print JSON on stdout, unconditionally — `--json` is a usage error (exit 2) for those three. diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index 7f648cace..90f660d56 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -137,10 +137,11 @@ Each worker shows: | Version | The worker's Simlock version | | Devices | How many devices are running, and how many are leased | | Capacity | Devices running out of the limit, per platform | +| Capabilities | Each optional module the worker knows of, such as agent-device: `available`, `off`, or `unavailable` with its reason | A worker the gateway could not read from yet says "Not reported" where it has nothing to show. A worker that is still starting shows its health as -`starting`, and leaves out its devices and capacity: they appear once it has +`starting`, and leaves out its devices, capacity and capabilities: they appear once it has finished starting. Its page shows the status and the host, and says that devices, leases and capacity appear once startup finishes. diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 0323e174e..da5e710ac 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -158,7 +158,7 @@ is on its entry in `workers`. While the daemon is starting (`daemon.health` is `starting`), the answer is `200` with the `daemon` block and `host` only: it has not yet checked what it -holds, so `devices`, `leases`, `capacity`, `queueDepth`, `physicalQueueDepth`, `installs`, +holds, so `capabilities`, `devices`, `leases`, `capacity`, `queueDepth`, `physicalQueueDepth`, `installs`, `waiting`, `warmPool` and `workers` are absent, not empty. They are all there once `health` is `running`, and also when it is `failed`. @@ -245,6 +245,21 @@ device, oldest first, in the shape [`GET /v1/lease-requests`](#get-v1lease-requests) answers. A worker always sends it, empty when nothing waits; an older daemon leaves it out. +**`capabilities`** lists each optional module the daemon knows of, with its +state, in the order it sends them (at most 16, no name twice): + +```json +[{ "name": "agent-device", "state": "unavailable", "reason": "found 0.20.1, need 0.21.25 or later" }] +``` + +`name` is lower-case letters, digits and `-`, starting with a letter, up to 32 +characters. `state` is `available`, `unavailable` or `off`. `reason` is there +for `unavailable` only: 1 to 500 characters, with control characters replaced +by spaces. A worker with `agentDevice.enabled` `false` or unset sends +`agent-device` as `off`. A status read that takes over 1 s or fails shows +`unavailable` with `could not read 's status`. A gateway's own answer +leaves `capabilities` out: each worker's list is on its entry in `workers`. + A device in `devices` that is `provisioning` or `reclaiming` carries `transitionAgeMs`, how long it has been in that state. One that has been there past its threshold with nothing working on it also carries @@ -1287,6 +1302,12 @@ install queued behind another may appear only then. A worker that does not send one shows an empty list; a disconnected or incompatible worker shows none. +`capabilities` is the worker's own `capabilities` list from its +[`GET /v1/status`](#get-v1status): which optional modules it serves, such as +agent-device. It is re-read on every refresh, so a change shows at the next +periodic refresh at the latest. A starting or incompatible worker shows none; +a disconnected worker keeps the list it last read. + `waiting` is the worker's own `waiting` list from its [`GET /v1/status`](#get-v1status): the requests waiting in that worker's queue. It is re-read on every lease event on that worker. A worker that does diff --git a/src/agent-device/host/host.ts b/src/agent-device/host/host.ts index e8b68ced8..d3b9a0725 100644 --- a/src/agent-device/host/host.ts +++ b/src/agent-device/host/host.ts @@ -42,6 +42,8 @@ export class AgentDeviceHost { record: ReleaseScopeRecord = new ReleaseScopeRecord(), ) { this.#upstreamFetch = recordingFetch(upstream, record); + // why: the gateway's first status.get reads this host's status, and must not pay for the proxy module's load. + void this.#load(); } async status(): Promise { diff --git a/src/agent-device/index.ts b/src/agent-device/index.ts index 36340cb70..6c939faf5 100644 --- a/src/agent-device/index.ts +++ b/src/agent-device/index.ts @@ -39,6 +39,24 @@ export function createAgentDeviceEdgeParts( }; } +export function agentDeviceCapabilitySource(parts: AgentDeviceEdgeParts): { + readonly name: string; + readonly read: () => Promise<{ + readonly state: "available" | "unavailable"; + readonly reason?: string; + }>; +} { + return { + name: "agent-device", + read: async () => { + const status = await parts.link.status(); + return status.state === "running" + ? { state: "available" } + : { reason: status.reason, state: "unavailable" }; + }, + }; +} + // why: a stop ends the gateway's sockets, so the calls that end then must send no renewal that races leasing teardown. export function disposeAgentDeviceEdge(parts: AgentDeviceEdgeParts): void { parts.renewals.dispose(); diff --git a/src/cli/index.ts b/src/cli/index.ts index 8bde4dd2c..4f310bb1b 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -2221,7 +2221,14 @@ function formatWorkers( : ` protocol ${worker.protocol.worker.min}-${worker.protocol.worker.max}` + ` vs gateway ${worker.protocol.gateway.min}-${worker.protocol.gateway.max}`; const host = worker.host === undefined ? "" : ` -- ${formatHost(worker.host)}`; - return `${label}: ${state} -- ${capacity}, ${leaseCount(worker)}${skew}${host}${installs}`; + const capabilities = (worker.capabilities ?? []) + .map((entry) => + entry.state === "unavailable" + ? ` -- ${entry.name} unavailable: ${entry.reason ?? "unknown"}` + : ` -- ${entry.name} ${entry.state}`, + ) + .join(""); + return `${label}: ${state} -- ${capacity}, ${leaseCount(worker)}${skew}${host}${capabilities}${installs}`; }) .join("\n"); } diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 851205872..57d9cdd3f 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -39,7 +39,7 @@ import { tokenRecordSchema, tokenRoleSchema, waitingRequestSchema, - capabilitySchema, + capabilityListSchema, workerViewSchema, } from "./schemas.js"; @@ -106,7 +106,7 @@ export const statusGet = defineOperation({ * is `starting`, like the fields above: a started worker and a gateway always send it. */ warmPool: statusWarmPoolSchema.optional(), - capabilities: z.array(capabilitySchema).optional(), + capabilities: capabilityListSchema.optional(), daemon: z.object({ health: daemonHealthSchema, mode: daemonModeSchema, diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index ceab5b3f5..4eca8d816 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 32, max: 32 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 33, max: 33 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index b907447dc..d3fed3aa9 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -1016,20 +1016,39 @@ export const INSTALL_LIST_LIMIT = MAX_LISTED_INSTALLS; * never drained, `lastSeenAt` the time of the call, and every reported field filled from its * own reads by `workerViewFields` (`worker-view.ts`), the same builder a gateway uses. */ -export const capabilityNameSchema = z.string(); +export const capabilityNameSchema = z.string().regex(/^[a-z][a-z0-9-]{0,31}$/); -export const capabilitySchema = z.object({ - name: capabilityNameSchema, - state: z.enum(["available", "unavailable", "off"]), - reason: z.string().optional(), -}); +// why: \p{Cc} is exactly U+0000-U+001F and U+007F-U+009F, the spec's control characters. +const CONTROL_CHARACTERS = /[\p{Cc}\u2028\u2029]/gu; +const CAPABILITY_REASON_MAX = 500; + +export const capabilitySchema = z + .object({ + name: capabilityNameSchema, + state: z.enum(["available", "unavailable", "off"]), + reason: z + .string() + .min(1) + .max(CAPABILITY_REASON_MAX) + .refine((text) => !/[\p{Cc}\u2028\u2029]/u.test(text)) + .optional(), + }) + .refine((entry) => (entry.state === "unavailable") === (entry.reason !== undefined)); + +export const capabilityListSchema = z + .array(capabilitySchema) + .max(16) + .refine((list) => new Set(list.map((entry) => entry.name)).size === list.length); export function capabilityReason(text: string): string { - return text; + let cut = text.replace(CONTROL_CHARACTERS, " ").trim().slice(0, CAPABILITY_REASON_MAX); + const last = cut.charCodeAt(cut.length - 1); + if (last >= 0xd800 && last <= 0xdbff) cut = cut.slice(0, -1); + return cut === "" ? "unknown" : cut; } export const workerViewSchema = z.object({ - capabilities: z.array(capabilitySchema).optional(), + capabilities: capabilityListSchema.optional(), /** The worker's own instance identity (`instance.json`), ADR 0005 §3a: stable across * restarts, unique by construction, opaque to clients. Never a host name or an address. */ id: z.string(), diff --git a/src/contract/worker-view.ts b/src/contract/worker-view.ts index a9218d078..cbd9c5bd2 100644 --- a/src/contract/worker-view.ts +++ b/src/contract/worker-view.ts @@ -48,6 +48,7 @@ export type WorkerViewReport = Pick & Partial< Pick< WorkerView, + | "capabilities" | "capacity" | "catalog" | "devices" @@ -75,6 +76,7 @@ export function workerViewFields(reads: WorkerReads): WorkerViewReport { host: status.host, installs: status.installs ?? [], waiting: status.waiting ?? [], + ...(status.capabilities === undefined ? {} : { capabilities: status.capabilities }), ...(status.capacity === undefined ? {} : { capacity: status.capacity }), ...(status.warmPool === undefined ? {} : { warmPool: status.warmPool }), ...(status.leases === undefined ? {} : { leases: status.leases }), diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index df045eb4e..b4e3a092d 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(32); + expect(DAEMON_PROTOCOL_VERSION).toBe(33); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index c07b98f6b..163a9835a 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -48,6 +48,8 @@ import type { } from "../ports/index.js"; import { exitCodeOf, NoopLogger } from "../ports/index.js"; import { + capabilityReason, + type capabilitySchema, consoleUrlField, fitPlatformCatalog, OPERATIONS, @@ -100,6 +102,10 @@ export class NukeUnavailableError extends Error { } } +const CAPABILITY_READ_BUDGET_MS = 1_000; + +type CapabilityEntry = z.infer; + export interface CapabilitySource { readonly name: string; readonly read: () => Promise<{ readonly state: string; readonly reason?: string }>; @@ -341,7 +347,7 @@ export class Dispatcher { platforms: (await this.options.catalog.listCatalog(input.platform)).map(fitPlatformCatalog), }); - #statusGet: Handler<"status.get"> = () => { + #statusGet: Handler<"status.get"> = async () => { const daemon = { health: this.options.health(), mode: this.options.config.mode, @@ -351,8 +357,10 @@ export class Dispatcher { // While starting, the registry has not been checked against the machine: what it holds is // a claim nobody has looked at, so the answer is the daemon and its host and nothing else. if (daemon.health === "starting") return { daemon, host }; + const capabilities = await this.#readCapabilities(); const snapshot = this.options.registry.snapshot; return { + ...(capabilities === undefined ? {} : { capabilities }), capacity: buildCapacityFigures(snapshot.virtualDevices, this.options.capacity), devices: snapshot.devices.map((device) => this.#decorateDevice(device)), daemon, @@ -366,6 +374,42 @@ export class Dispatcher { }; }; + // why: a module can never make status.get fail or hang, which would cut the worker off from its gateway. + async #readCapabilities(): Promise { + const sources = this.options.capabilitySources; + if (sources === undefined || sources.length === 0) return undefined; + return Promise.all(sources.map((source) => this.#readCapability(source))); + } + + async #readCapability(source: CapabilitySource): Promise { + const unreadable: CapabilityEntry = { + name: source.name, + reason: capabilityReason(`could not read ${source.name}'s status`), + state: "unavailable", + }; + let timer: TimerHandle | undefined; + const expired = new Promise((resolve) => { + timer = this.options.clock.setTimer(CAPABILITY_READ_BUDGET_MS, () => resolve(undefined)); + }); + try { + const answer = await Promise.race([source.read().catch((): undefined => undefined), expired]); + if (answer === undefined) return unreadable; + if (answer.state === "available" || answer.state === "off") { + return { name: source.name, state: answer.state }; + } + if (answer.state !== "unavailable") { + return { name: source.name, reason: "reported an invalid status", state: "unavailable" }; + } + return { + name: source.name, + reason: capabilityReason(answer.reason ?? ""), + state: "unavailable", + }; + } finally { + if (timer !== undefined) this.options.clock.cancel(timer); + } + } + // fallow-ignore-next-line complexity -- lease payload assembly and the download-policy rewrite are one transaction, moved verbatim from DaemonServer's former #requestLease. #leaseRequest: Handler<"lease.request"> = async (input, session) => { const request: DeviceRequest = requestedDevice(input); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 344ea41b0..4befd98c0 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -3,6 +3,7 @@ import { join, resolve } from "node:path"; import { pathToFileURL } from "node:url"; import { + agentDeviceCapabilitySource, agentDeviceFindings, AgentDeviceSupervisor, cancelWaitingAllocates, @@ -446,6 +447,12 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise core.closeWarmPool(), + // why: the source's name is the config key's; the core names no module, so the composition supplies it. + capabilitySources: [ + agentDeviceParts === undefined + ? { name: "agent-device", read: async () => ({ state: "off" }) } + : agentDeviceCapabilitySource(agentDeviceParts), + ], capacity: core.capacityReader, warmPool: core.warmPoolReader, catalog: core.catalog, diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index c73d49309..92171ba66 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -193,8 +193,9 @@ describe("DaemonServer", () => { [28, "cannot read config.get's lease.endWaitMs"], [29, "cannot read config.get's agentDevice"], [30, "cannot read the agent-device-unavailable finding in doctor.run"], + [32, "cannot read status.get's capabilities"], ])( - "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 32, to a client on protocol %i, which %s", + "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 33, to a client on protocol %i, which %s", async (version) => { const harness = await createHarness(); const previous = await createClient(harness.socketPath); @@ -204,7 +205,7 @@ describe("DaemonServer", () => { ).resolves.toMatchObject({ error: { code: "PROTOCOL_VERSION_UNSUPPORTED", - details: { client: { min: version, max: version }, daemon: { min: 32, max: 32 } }, + details: { client: { min: version, max: version }, daemon: { min: 33, max: 33 } }, }, ok: false, }); diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 47f20a2c2..040c36d64 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -278,6 +278,9 @@ function buildDispatcher( ): Dispatcher { return new Dispatcher({ awaitReady: hooks.awaitReady, + ...(options.capabilitySources === undefined + ? {} + : { capabilitySources: options.capabilitySources }), capacity: options.capacity, warmPool: options.warmPool, catalog: options.catalog, diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 42d9f1e4e..6250c3d47 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -1207,7 +1207,7 @@ describe("GatewayService", () => { min: PROTOCOL_VERSION_RANGE.max - 1, max: PROTOCOL_VERSION_RANGE.max - 1, }; - expect(PROTOCOL_VERSION_RANGE.max).toBe(32); + expect(PROTOCOL_VERSION_RANGE.max).toBe(33); expect(negotiateProtocolVersion(PROTOCOL_VERSION_RANGE, previous)).toBeUndefined(); const harness = fleet(); await harness.service.start(); diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index 7494e2877..d1839a42c 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -91,6 +91,7 @@ export interface WorkerRegistryOptions { */ function withoutReadFields(view: WorkerView): WorkerView { const { + capabilities: _capabilities, capacity: _capacity, catalog: _catalog, catalogReadAt: _catalogReadAt, @@ -287,6 +288,7 @@ export class WorkerRegistry { // asked. A view left over from an earlier, compatible session must not keep showing them, // nor the installs or waiting requests that status listed (ADR 0010 §7). const { + capabilities: _staleCapabilities, host: _stale, installs: _staleInstalls, waiting: _staleWaiting, diff --git a/ui/src/views/worker-facts.tsx b/ui/src/views/worker-facts.tsx index cded60f94..a3e2e7a39 100644 --- a/ui/src/views/worker-facts.tsx +++ b/ui/src/views/worker-facts.tsx @@ -1,6 +1,8 @@ import { connectionStatus, healthStatus, Status } from "../status"; import { capacityByPlatform, deviceCounts, platformName, type WorkerView } from "./workers-model"; +const capabilityTone = { available: "ok", off: "idle", unavailable: "warn" } as const; + /** What the list says about a worker, and what its detail page starts with. */ export function WorkerFacts({ worker }: { readonly worker: WorkerView }) { const connection = connectionStatus(worker.connection); @@ -60,6 +62,20 @@ export function WorkerFacts({ worker }: { readonly worker: WorkerView }) { .join(", ")} +
+
Capabilities
+
+ {worker.capabilities === undefined + ? "Not reported" + : worker.capabilities.map((entry, index) => ( + + {index === 0 ? "" : ", "} + {entry.name} {entry.state} + {entry.reason === undefined ? null : ` ${entry.reason}`} + + ))} +
+
)} From 2f4772abd3f72e8bbc9f351b9c5300a613f6bc29 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 20:37:30 +0200 Subject: [PATCH 3/5] chore: fallow entries for capability schemas (#519) 0 failing --- src/contract/operations.ts | 1 - src/contract/schemas.ts | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 57d9cdd3f..bd3004f75 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -87,7 +87,6 @@ export const catalogGet = defineOperation({ // ---- status.get --------------------------------------------------------------------------- -// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. export const statusGet = defineOperation({ name: "status.get", role: "agent", diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index d3fed3aa9..8175188ef 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -1016,6 +1016,7 @@ export const INSTALL_LIST_LIMIT = MAX_LISTED_INSTALLS; * never drained, `lastSeenAt` the time of the call, and every reported field filled from its * own reads by `workerViewFields` (`worker-view.ts`), the same builder a gateway uses. */ +// fallow-ignore-next-line unused-export -- exported on its own so the tasks that name a capability reuse it (#513). export const capabilityNameSchema = z.string().regex(/^[a-z][a-z0-9-]{0,31}$/); // why: \p{Cc} is exactly U+0000-U+001F and U+007F-U+009F, the spec's control characters. From b597d7a9afc7386db9c63c47adf3e400eb588d39 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 20:39:22 +0200 Subject: [PATCH 4/5] docs: workerViewSchema keeps its doc comment (#519) --- src/contract/schemas.ts | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 8175188ef..d50ece814 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -997,25 +997,6 @@ export const statusInstallsSchema = boundedInstalls( */ export const INSTALL_LIST_LIMIT = MAX_LISTED_INSTALLS; -/** - * What the gateway currently knows about one worker (ADR 0005's vocabulary table, §7, §31). - * Rebuilt over the uplink, never persisted: a gateway restart re-derives every field from the - * workers that reconnect (§30). - * - * The optional fields are exactly the ones that come from a `status.get`/`catalog.get` round - * trip the gateway may not have been able to make: an `incompatible` worker is never asked - * anything, and a `disconnected` view keeps whatever the last successful refresh saw. They are - * absent rather than zeroed on purpose -- "no capacity reported" and "no capacity free" are - * different facts, and a console that dims one must not read the other as a full machine. - * The same holds for a worker whose health is `starting`: it answers `status.get` with `daemon` - * and `host` only, so its view has `health` and `host` and none of `capacity`, `catalog`, - * `devices`, `installs`, `leases`, `queueDepth` or `waiting` -- never empty ones, which would - * read as "nothing is leased" about a registry nobody has checked yet. - * - * A worker answers `worker.list` with one of these about itself (ADR 0012 §1): `connected`, - * never drained, `lastSeenAt` the time of the call, and every reported field filled from its - * own reads by `workerViewFields` (`worker-view.ts`), the same builder a gateway uses. - */ // fallow-ignore-next-line unused-export -- exported on its own so the tasks that name a capability reuse it (#513). export const capabilityNameSchema = z.string().regex(/^[a-z][a-z0-9-]{0,31}$/); @@ -1048,6 +1029,25 @@ export function capabilityReason(text: string): string { return cut === "" ? "unknown" : cut; } +/** + * What the gateway currently knows about one worker (ADR 0005's vocabulary table, §7, §31). + * Rebuilt over the uplink, never persisted: a gateway restart re-derives every field from the + * workers that reconnect (§30). + * + * The optional fields are exactly the ones that come from a `status.get`/`catalog.get` round + * trip the gateway may not have been able to make: an `incompatible` worker is never asked + * anything, and a `disconnected` view keeps whatever the last successful refresh saw. They are + * absent rather than zeroed on purpose -- "no capacity reported" and "no capacity free" are + * different facts, and a console that dims one must not read the other as a full machine. + * The same holds for a worker whose health is `starting`: it answers `status.get` with `daemon` + * and `host` only, so its view has `health` and `host` and none of `capacity`, `catalog`, + * `devices`, `installs`, `leases`, `queueDepth` or `waiting` -- never empty ones, which would + * read as "nothing is leased" about a registry nobody has checked yet. + * + * A worker answers `worker.list` with one of these about itself (ADR 0012 §1): `connected`, + * never drained, `lastSeenAt` the time of the call, and every reported field filled from its + * own reads by `workerViewFields` (`worker-view.ts`), the same builder a gateway uses. + */ export const workerViewSchema = z.object({ capabilities: capabilityListSchema.optional(), /** The worker's own instance identity (`instance.json`), ADR 0005 §3a: stable across From db0a9f749b14c77aeb4f56ca1b296d60655a065b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 20:44:26 +0200 Subject: [PATCH 5/5] docs(contract): the starting-worker view comment lists every field it lacks --- src/contract/schemas.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index d50ece814..a080b5cc6 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -1040,8 +1040,9 @@ export function capabilityReason(text: string): string { * absent rather than zeroed on purpose -- "no capacity reported" and "no capacity free" are * different facts, and a console that dims one must not read the other as a full machine. * The same holds for a worker whose health is `starting`: it answers `status.get` with `daemon` - * and `host` only, so its view has `health` and `host` and none of `capacity`, `catalog`, - * `devices`, `installs`, `leases`, `queueDepth` or `waiting` -- never empty ones, which would + * and `host` only, so its view has `health` and `host` and none of `capabilities`, + * `capacity`, `catalog`, `catalogReadAt`, `devices`, `installs`, `leases`, `physicalQueueDepth`, + * `queueDepth`, `waiting` or `warmPool` -- never empty ones, which would * read as "nothing is leased" about a registry nobody has checked yet. * * A worker answers `worker.list` with one of these about itself (ADR 0012 §1): `connected`,