diff --git a/src/cli/commands/lease.ts b/src/cli/commands/lease.ts index 100caef30..bac0a4aca 100644 --- a/src/cli/commands/lease.ts +++ b/src/cli/commands/lease.ts @@ -76,6 +76,7 @@ async function runLease( help: { type: "boolean", short: "h" }, "image-tag": { type: "string" }, "lease-id": { type: "string" }, + label: { type: "string" }, meta: { type: "string", multiple: true }, mode: { type: "string" }, "no-wait": { type: "boolean" }, @@ -93,7 +94,7 @@ async function runLease( " [--except ] [--baseline ]\n" + " [--timeout ] [--lease-id ] [--physical]\n" + " [--no-wait] [--detach] [--ttl ] [--allow-download]\n" + - " [--run ] [--meta ]... [--export-env] [--bind-pid ]\n", + " [--run ] [--label ] [--meta ]... [--export-env] [--bind-pid ]\n", ); return 0; } @@ -323,6 +324,7 @@ async function runLease( ...(baseline === undefined ? {} : { baseline }), ...(runId === undefined ? {} : { runId }), ...(typeof values["lease-id"] === "string" ? { leaseId: values["lease-id"] } : {}), + ...(typeof values.label === "string" ? { label: values.label } : {}), ...(metadata === undefined ? {} : { metadata }), ...(timeoutMs === undefined ? {} : { timeoutMs }), ...(ttlMs === undefined ? {} : { ttlMs }), diff --git a/src/cli/format.ts b/src/cli/format.ts index cf097e825..bd52c90e8 100644 --- a/src/cli/format.ts +++ b/src/cli/format.ts @@ -318,7 +318,7 @@ export function formatStatus(status: StatusGetOutput, now: number, cliVersion?: }); const leaseLines = leases.map( (lease) => - `Lease ${esc(lease.id)}: ${esc(lease.requesterId)}${lease.workerId === undefined ? "" : ` on ${esc(lease.workerId)}`}${lease.runId === undefined ? "" : `, run ${esc(lease.runId)}`} since ${lease.grantedAt}, last renewed ${lease.lastRenewedAt}`, + `Lease ${esc(lease.id)}: ${esc(lease.requesterId)}${lease.workerId === undefined ? "" : ` on ${esc(lease.workerId)}`}${lease.runId === undefined ? "" : `, run ${esc(lease.runId)}`}${lease.label === undefined ? "" : `, label ${esc(lease.label)}`} since ${lease.grantedAt}, last renewed ${lease.lastRenewedAt}`, ); return [ ...daemonLines(daemon, cliVersion), diff --git a/src/cli/index-lease-label.test.ts b/src/cli/index-lease-label.test.ts new file mode 100644 index 000000000..567d9ebf6 --- /dev/null +++ b/src/cli/index-lease-label.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from "vitest"; +import { SimlockError } from "../contract/index.js"; +import { runCli } from "./index.js"; +import { fakeClient, outputCapture } from "./test-index.js"; + +const grant = { + device: { + physical: false, + driverDeviceId: "dev_1", + id: "dev_1", + mode: "full" as const, + spec: { physical: false, model: "iPhone 17", osVersion: "26.5", platform: "ios" as const }, + }, + environment: {}, + lease: { + deviceId: "dev_1", + grantedAt: 0, + id: "lse_1", + lastRenewedAt: 0, + idChosenByRequester: false, + ownerId: "test-requester", + requesterId: "test-requester", + ttlDeadline: 60_000, + ttlMs: 60_000, + }, + timing: { + estimatedBootMs: 0, + estimatedProvisionMs: 0, + estimatedReadyMs: 0, + estimatedReclaimMs: 0, + }, +}; + +describe("simlock lease: the label a lease carries", () => { + it("sends --label as given, sends none without it, and prints the daemon's refusal of a bad one instead of a local usage error", async () => { + const sentWith = async (flags: readonly string[]) => { + let sent: Record | undefined; + const exitCode = await runCli( + ["lease", "--platform", "ios", "--detach", ...flags], + outputCapture().environmentWith({ + connectAdmin: async () => + fakeClient({ + requestLease: (input) => { + sent = input as unknown as Record; + return Promise.resolve(grant); + }, + }), + }), + ); + return { exitCode, sent }; + }; + + const labelled = await sentWith(["--label", "feature-x", "--run", "nightly-7"]); + expect(labelled.exitCode).toBe(0); + expect(labelled.sent).toMatchObject({ label: "feature-x", runId: "nightly-7" }); + const plain = await sentWith([]); + expect(plain.exitCode).toBe(0); + expect(plain.sent).not.toHaveProperty("label"); + + const refusal = "label must be 1 to 64 characters"; + let sent: Record | undefined; + const output = outputCapture(); + const exitCode = await runCli( + ["lease", "--platform", "ios", "--detach", "--label", ""], + output.environmentWith({ + connectAdmin: async () => + fakeClient({ + requestLease: (input) => { + sent = input as unknown as Record; + return Promise.reject( + new SimlockError("BAD_REQUEST", "protocol", refusal, {} as never), + ); + }, + }), + }), + ); + expect(sent).toMatchObject({ label: "" }); + expect(exitCode).toBe(2); + expect(output.stderr).toContain(refusal); + expect(output.stderr).toContain("BAD_REQUEST"); + expect(output.stderr).not.toContain("USAGE"); + }); +}); diff --git a/src/cli/index-lease-requests.test.ts b/src/cli/index-lease-requests.test.ts index 16335b666..065a88130 100644 --- a/src/cli/index-lease-requests.test.ts +++ b/src/cli/index-lease-requests.test.ts @@ -867,7 +867,7 @@ describe("simlock lease: a request names a model, a class, or nothing", () => { " [--except ] [--baseline ]\n" + " [--timeout ] [--lease-id ] [--physical]\n" + " [--no-wait] [--detach] [--ttl ] [--allow-download]\n" + - " [--run ] [--meta ]... [--export-env] [--bind-pid ]\n", + " [--run ] [--label ] [--meta ]... [--export-env] [--bind-pid ]\n", ); }); diff --git a/src/cli/index-status-daemon-lines.test.ts b/src/cli/index-status-daemon-lines.test.ts index fc8c0d654..23d88f3fa 100644 --- a/src/cli/index-status-daemon-lines.test.ts +++ b/src/cli/index-status-daemon-lines.test.ts @@ -444,7 +444,7 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = expect(output.stdout).toContain("Install android 35 on wrk_1: waiting for 0s, 3 waiters\n"); }); - it("prints a lease's run id after its worker on the lease line, and the line as before for a lease with none", async () => { + it("prints a lease's run id after its worker and its label after the run id on the lease line, and the line as before for a lease with neither", async () => { const output = outputCapture(); const lease = { deviceId: "dev_1", @@ -461,6 +461,9 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = leases: [ { ...lease, id: "lse_run", runId: "123-1", workerId: "w1" }, { ...lease, id: "lse_local", runId: "123-1" }, + { ...lease, id: "lse_labelled", label: "feature-x", runId: "123-1", workerId: "w1" }, + { ...lease, id: "lse_label_only", label: "feature-x" }, + { ...lease, id: "lse_escaped", label: "a\u001b[31mb" }, { ...lease, id: "lse_plain" }, ], }; @@ -478,6 +481,16 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = expect(output.stdout).toContain( "Lease lse_local: ci-job-42, run 123-1 since 100, last renewed 200\n", ); + expect(output.stdout).toContain( + "Lease lse_labelled: ci-job-42 on w1, run 123-1, label feature-x since 100, last renewed 200\n", + ); + expect(output.stdout).toContain( + "Lease lse_label_only: ci-job-42, label feature-x since 100, last renewed 200\n", + ); + expect(output.stdout).toContain( + "Lease lse_escaped: ci-job-42, label a\\u001b[31mb since 100, last renewed 200\n", + ); + expect(output.stdout).not.toContain("\u001b"); expect(output.stdout).toContain("Lease lse_plain: ci-job-42 since 100, last renewed 200\n"); }); diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index 1880bb056..2ae1ef699 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -11,6 +11,7 @@ Shapes: - `config.get` carries a driver's own keys under `ios` and `android`, and a module's under `capabilities`, as sent: a new one is no shape change. - `lease.request` holds `except` (a slim iOS simulator lease keeping slim categories running, ADR 0066) to one object-level refinement with no path (`exceptRefusal`, `operations-lease-request.ts`), so every transport answers `BAD_REQUEST` with the message as written: 1 to 16 names matching `EXCEPT_NAME_PATTERN`, none twice, never with `physical`, a platform but iOS or `mode: full`. The worker's default mode and a baseline's mode are checked in leasing. - `lease.request`'s `runId` is held to `RUN_ID_PATTERN` by one object-level refinement with no path (`refuseBadRunId`), and the HTTP body by the same one: the same words on every transport. A gateway hands it on as sent; MCP's `lease_simulator` leaves it out. +- `lease.request`'s `label` (1 to 64 UTF-16 units, no `Cc` character, U+2028 or U+2029) is held the same way (`refuseBadLabel`), the HTTP body by the same one. A gateway hands it on as sent, and MCP's `lease_simulator` keeps it. - `lease.request`'s `metadata` (ADR 0074 §3) is held to one object-level refinement too (`refuseBadMetadata`): the same words on every transport. A gateway hands it to its admission command alone; nothing else may read it. - Wire input is a claim: every field a gateway parses from a worker is bounded here (`fit*`, `CONSOLE_URL_MAX_LENGTH`, `relay.ts`). - One OS grammar (`os-range.ts`), one duration parser (`duration.ts`), one usage window (`usageWindow`, `usage-window.ts`), one events page query (`eventsPageQuery`, `events-page.ts`). Nobody else parses. diff --git a/src/contract/errors.ts b/src/contract/errors.ts index e07f0ee58..93b0044b2 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -50,9 +50,8 @@ export interface ErrorDetailsMap { QUEUE_TIMEOUT: { readonly requestId: string }; PROVISION_FAILED: Record; REQUESTER_ALREADY_LEASED: { readonly requesterId: string; readonly existingLeaseId?: string }; - /** `lease.request` repeated an `idempotencyKey` its requester already used for a different - * device or a different `leaseId` (a missing one on either side counts as different). The - * stored request is untouched; a new request needs a new key. */ + /** why: a missing `leaseId`, `runId` or `label` on either side counts as different, so a retry + * that adds or drops one conflicts instead of replaying. */ IDEMPOTENCY_CONFLICT: Record; /** `lease.request` named a `leaseId` an active lease or a waiting request already holds * (ADR 0020). The daemon stores nothing for it; a gateway can also meet it after storing the diff --git a/src/contract/lease-schemas.ts b/src/contract/lease-schemas.ts index 2225c1f49..2feffbffb 100644 --- a/src/contract/lease-schemas.ts +++ b/src/contract/lease-schemas.ts @@ -44,6 +44,7 @@ export const leaseRecordSchema = z.object({ lastRenewedAt: z.number(), idChosenByRequester: z.boolean(), runId: z.string().max(128).optional(), + label: z.string().max(64).optional(), worker: z.object({ id: z.string(), label: z.string().optional() }).optional(), }); diff --git a/src/contract/operations-lease-request.ts b/src/contract/operations-lease-request.ts index c5ce74871..582d27fd5 100644 --- a/src/contract/operations-lease-request.ts +++ b/src/contract/operations-lease-request.ts @@ -65,6 +65,8 @@ const leaseRequestBaseSchema = z idempotencyKey: z.string().min(1).max(200).optional(), // why: A plain string, bounded by `refuseBadRunId` as the one object-level check, like `osVersion`: a refined field would be checked by the MCP SDK before the handler. runId: z.string().optional(), + // why: A plain string, bounded by `refuseBadLabel` as the one object-level check, like `runId`: a refined field would be checked by the MCP SDK before the handler. + label: z.string().optional(), leaseId: leaseIdSchema.optional(), fleetRequestId: z.string().min(1).max(200).optional(), // why: A plain record of plain strings, bounded by `refuseBadMetadata` as one object-level check, like `except`: a bound on the field itself would be checked by the MCP SDK before the handler. @@ -251,6 +253,24 @@ export function refuseBadRunId(): ( + input: T, + context: z.RefinementCtx, +) => void { + return (input, context) => { + const { label } = input; + if (label === undefined) return; + if (label.length < 1 || label.length > 64) { + context.addIssue({ code: "custom", message: LABEL_LENGTH_REFUSAL }); + } else if (/[\p{Cc}\u2028\u2029]/u.test(label)) { + context.addIssue({ code: "custom", message: LABEL_CONTROL_REFUSAL }); + } + }; +} + function refuseBadOsVersion(): ( input: T, context: z.RefinementCtx, @@ -288,6 +308,7 @@ const leaseRequestInputSchema = leaseRequestBaseSchema .superRefine(refuseBadExcept()) .superRefine(refuseBadMetadata()) .superRefine(refuseBadRunId()) + .superRefine(refuseBadLabel()) .superRefine(refusePhysicalWithImageFields()) .superRefine(refuseRequiresWithIdempotencyKey()); diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 7f978a16a..9ef72a78b 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -76,6 +76,7 @@ export { LEASE_ID_PATTERN, leaseIdSchema, refuseModelWithClass, + refuseBadLabel, refuseBadRunId, RUN_ID_PATTERN, leaseRequestFields, diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 4a6a6a8b4..48c2d82af 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: 100, max: 100 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 101, max: 101 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/core/domain.ts b/src/core/domain.ts index c7c47a1be..d4e2c13e2 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -442,6 +442,7 @@ export interface LeaseRecord { readonly idChosenByRequester: boolean; // why: `| undefined` because a lease read from a worker (the contract's type) is projected as this type by a gateway. readonly runId?: string | undefined; + readonly label?: string | undefined; } export interface LeaseTiming { @@ -500,6 +501,7 @@ export interface LeaseRequestRecord { */ readonly leaseId?: string; readonly runId?: string; + readonly label?: string; /** * The gateway's request id (ADR 0021) when this request is a gateway dispatch, a probe. Kept so * a probe settled at the next start still names it. diff --git a/src/core/lease-request-store.ts b/src/core/lease-request-store.ts index c0d7020c3..14886d89a 100644 --- a/src/core/lease-request-store.ts +++ b/src/core/lease-request-store.ts @@ -1,6 +1,7 @@ import type { IdGenerator } from "../ports/index.js"; import { isSettled, type LeaseRequestFailure, type LeaseRequestRecord } from "./domain.js"; import type { DeviceRequest } from "./driver.js"; +import { presentFields } from "./present-fields.js"; /** `lease.requestRetentionMs` and `lease.maxRequestRecords`, as a store applies them. */ export interface LeaseRequestLimits { @@ -21,6 +22,7 @@ export interface NewLeaseRequest { readonly idempotencyKey?: string; readonly leaseId?: string; readonly runId?: string; + readonly label?: string; readonly fleetRequestId?: string; readonly request: DeviceRequest; } @@ -103,10 +105,13 @@ export function newLeaseRequestRecord( return { createdAt: now, id, - ...(input.idempotencyKey === undefined ? {} : { idempotencyKey: input.idempotencyKey }), - ...(input.leaseId === undefined ? {} : { leaseId: input.leaseId }), - ...(input.runId === undefined ? {} : { runId: input.runId }), - ...(input.fleetRequestId === undefined ? {} : { fleetRequestId: input.fleetRequestId }), + ...presentFields({ + idempotencyKey: input.idempotencyKey, + leaseId: input.leaseId, + runId: input.runId, + label: input.label, + fleetRequestId: input.fleetRequestId, + }), ownerId: input.ownerId, request: { ...input.request }, requesterId: input.requesterId, diff --git a/src/core/present-fields.ts b/src/core/present-fields.ts new file mode 100644 index 000000000..036521163 --- /dev/null +++ b/src/core/present-fields.ts @@ -0,0 +1,8 @@ +// why: a field that is absent stays absent on a stored record (never `undefined`), as `exactOptionalPropertyTypes` needs. +export function presentFields( + fields: T, +): { [K in keyof T]?: Exclude } { + return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined)) as { + [K in keyof T]?: Exclude; + }; +} diff --git a/src/core/registry-rows.ts b/src/core/registry-rows.ts index 5f6531da7..6ae29ac3c 100644 --- a/src/core/registry-rows.ts +++ b/src/core/registry-rows.ts @@ -186,6 +186,7 @@ const LEASE_COLUMNS = [ "last_renewed_at", "id_chosen_by_requester", "run_id", + "label", ] as const; const REQUEST_COLUMNS = [ @@ -196,6 +197,7 @@ const REQUEST_COLUMNS = [ "lease_id", "fleet_request_id", "run_id", + "label", "platform", "model", "os_version", @@ -224,6 +226,7 @@ const GRANT_COLUMNS = [ "last_renewed_at", "id_chosen_by_requester", "run_id", + "label", "estimated_provision_ms", "estimated_boot_ms", "estimated_reclaim_ms", @@ -329,6 +332,7 @@ function leaseValues(lease: LeaseRecord): SqliteValue[] { lease.lastRenewedAt, flagValue(lease.idChosenByRequester), lease.runId ?? null, + lease.label ?? null, ]; } @@ -380,6 +384,7 @@ export function writeLeaseRequest(database: SqliteDatabase, record: LeaseRequest record.leaseId ?? null, record.fleetRequestId ?? null, nullable(record.runId), + nullable(record.label), request.platform, request.model ?? null, request.osVersion ?? null, @@ -412,6 +417,7 @@ export function writeLeaseRequest(database: SqliteDatabase, record: LeaseRequest lease.lastRenewedAt, flagValue(lease.idChosenByRequester), nullable(lease.runId), + nullable(lease.label), grant.timing.estimatedProvisionMs, grant.timing.estimatedBootMs, grant.timing.estimatedReclaimMs, @@ -609,6 +615,7 @@ function leaseFromRow(table: string, key: string, row: Row, idColumn: string): L ownerId: reader.text("owner_id"), requesterId: reader.text("requester_id"), ...present("runId", reader.optText("run_id")), + ...present("label", reader.optText("label")), ttlDeadline: reader.int("ttl_deadline"), ttlMs: reader.int("ttl_ms"), }; @@ -650,6 +657,7 @@ function loadLeaseRequests( ...present("leaseId", reader.optText("lease_id")), ...present("fleetRequestId", reader.optText("fleet_request_id")), ...present("runId", reader.optText("run_id")), + ...present("label", reader.optText("label")), ownerId: reader.text("owner_id"), request: requestFromRow(reader), requesterId: reader.text("requester_id"), diff --git a/src/core/registry-schema.ts b/src/core/registry-schema.ts index c5f5f7b58..eaeff9596 100644 --- a/src/core/registry-schema.ts +++ b/src/core/registry-schema.ts @@ -150,6 +150,12 @@ ALTER TABLE lease_requests ADD COLUMN run_id TEXT; ALTER TABLE lease_grants ADD COLUMN run_id TEXT; `; +const REGISTRY_V9 = ` +ALTER TABLE leases ADD COLUMN label TEXT; +ALTER TABLE lease_requests ADD COLUMN label TEXT; +ALTER TABLE lease_grants ADD COLUMN label TEXT; +`; + export const registryOwner: SqliteSchemaOwner = { migrations: [ REGISTRY_V1, @@ -160,7 +166,8 @@ export const registryOwner: SqliteSchemaOwner = { REGISTRY_V6, REGISTRY_V7, REGISTRY_V8, + REGISTRY_V9, ], name: "registry", - version: 8, + version: 9, }; diff --git a/src/core/registry-types.ts b/src/core/registry-types.ts index 0a05d9a86..2736c9632 100644 --- a/src/core/registry-types.ts +++ b/src/core/registry-types.ts @@ -91,6 +91,7 @@ export interface CreateLeaseInput { /** why: the caller has already refused an ID that is in use: one place enforces that rule. */ readonly leaseId?: string; readonly runId?: string; + readonly label?: string; /** why: the categories the lease keeps running, written to the device in the commit that leases it (ADR 0066 §4). */ readonly except?: readonly string[]; /** diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index 864bf97a0..a56f03ba4 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -257,6 +257,113 @@ describe("Registry", () => { } }); + it("a state.db at registry version 8 migrates to 9, loads its leases with no label, and then keeps the label of a labelled lease across a reopen", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-registry-")); + try { + const clock = new FakeClock(1_000); + let next = 0; + const deviceData = new Map([ + ["android", fakeDeviceDataTable], + ["ios", fakeDeviceDataTable], + ]); + const openState = (owner: typeof registryOwner) => + openStateDatabase({ + dataDirectory: directory, + filesystem: new NodeFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners: [owner, fakeDeviceDataTable], + sqlite: new NodeSqliteOpener(), + upgradeStep: "remove it.", + }); + const loadRegistry = (state: StateDatabase) => + Registry.load({ + clock, + deviceData, + eventBus: new EventBus(clock), + idGenerator: { generate: () => String((next += 1)) }, + state, + }); + const old = await openState({ + ...registryOwner, + migrations: registryOwner.migrations.slice(0, 8), + version: 8, + }); + old.database + .prepare( + "INSERT INTO devices (id, platform, physical, driver_device_id, state, model, os_version, class, created_at) VALUES ('dev_old', 'android', 1, 'R58Y61A60HN', 'leased', 'Pixel 8', '15', 'phone', 5)", + ) + .run(); + old.database + .prepare( + "INSERT INTO leases (id, device_id, requester_id, owner_id, granted_at, ttl_ms, ttl_deadline, last_renewed_at, id_chosen_by_requester, run_id) VALUES ('lse_old', 'dev_old', 'r', 'o', 5, 10, 15, 5, 0, '7-1')", + ) + .run(); + old.close(); + + const migrated = await openState(registryOwner); + const registry = await loadRegistry(migrated); + expect(registry.snapshot.leases.map((lease) => lease.id)).toEqual(["lse_old"]); + expect(registry.snapshot.leases[0]).not.toHaveProperty("label"); + expect(registry.snapshot.leases[0]).toMatchObject({ runId: "7-1" }); + + const timing = { + estimatedBootMs: 2, + estimatedProvisionMs: 1, + estimatedReadyMs: 4, + estimatedReclaimMs: 3, + }; + const lease = async (name: string, label: string | undefined) => { + const device = await registry.registerDevice({ + driverData: { fakeDeviceId: name }, + driverDeviceId: name, + provisionDuration: 5, + spec, + }); + await registry.transitionDevice(device.id, "ready", { + event: "device.ready", + payload: { bootDuration: 7, deviceId: device.id }, + }); + const labelOption = label === undefined ? {} : { label }; + await registry.createLeaseRequest({ + id: `req_${name}`, + ownerId: "o", + request: { platform: "ios" }, + requesterId: name, + ...labelOption, + }); + return registry.createLease({ + deviceId: device.id, + ownerId: "o", + request: { environment: {}, id: `req_${name}`, timing }, + requesterId: name, + ttlDeadline: 2_000, + ttlMs: 1_000, + ...labelOption, + }); + }; + const labelled = await lease("labelled", "feature-x"); + const plain = await lease("plain", undefined); + migrated.close(); + + const reopened = await loadRegistry(await openState(registryOwner)); + const byId = (id: string) => + reopened.snapshot.leases.find((candidate) => candidate.id === id); + expect(byId(labelled.id)).toMatchObject({ label: "feature-x" }); + expect(byId(plain.id)).not.toHaveProperty("label"); + expect(byId("lse_old")).not.toHaveProperty("label"); + const stored = (id: string) => + reopened.leaseRequests().find((record) => record.id === `req_${id}`); + expect(stored("labelled")).toMatchObject({ + label: "feature-x", + grant: { lease: { label: "feature-x" } }, + }); + expect(stored("plain")?.grant?.lease).not.toHaveProperty("label"); + } finally { + await rm(directory, { force: true, recursive: true }); + } + }); + it("a registry restarted on the same state.db returns every record as committed, optional fields set and absent", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-registry-")); try { diff --git a/src/core/registry.ts b/src/core/registry.ts index 7d9759798..315c70617 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -45,6 +45,7 @@ import { writeLease, writeLeaseRequest, } from "./registry-rows.js"; +import { presentFields } from "./present-fields.js"; import { RegistryEventError, UnknownDeviceError, UnknownLeaseError } from "./registry-errors.js"; import type { ComponentRecord, @@ -693,6 +694,7 @@ export class Registry implements LeaseRequestStore { ttlDeadline, leaseId, runId, + label, except, request, }: CreateLeaseInput): Promise { @@ -722,7 +724,7 @@ export class Registry implements LeaseRequestStore { lastRenewedAt: grantedAt, ownerId, requesterId, - ...(runId === undefined ? {} : { runId }), + ...presentFields({ runId, label }), ttlMs, ttlDeadline, }; diff --git a/src/daemon/dispatcher-leases-label.test.ts b/src/daemon/dispatcher-leases-label.test.ts new file mode 100644 index 000000000..11677a076 --- /dev/null +++ b/src/daemon/dispatcher-leases-label.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from "vitest"; + +import { FakeDriver } from "../core/testing.js"; +import { FakeClock } from "../ports/index.js"; +import { classifyError } from "./error-code.js"; +import { buildDispatcher, session } from "./test-dispatcher.js"; + +describe("Dispatcher: lease.request with a label", () => { + it("a lease requested with a label carries it in the grant and in every later read, and a request without one carries none", async () => { + const { dispatcher, driver, engine } = await buildDispatcher({ + extraDrivers: [ + new FakeDriver({ + availableOsVersions: ["36"], + clock: new FakeClock(1_000), + platform: "android", + }), + ], + physicalDevices: [ + { + createdAt: 1, + driverDeviceId: "00008110-001A2B3C4D5E", + enrolledApps: [], + id: "dev_phys", + spec: { class: "phone", model: "iPhone 15", osVersion: "18.4" }, + state: "ready", + }, + ], + }); + await engine.convergeRunningCapacity(); + driver.setPhysicalPresence("00008110-001A2B3C4D5E", true); + const agent = session({ principal: "tok_owner" }); + const ios = { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" } as const; + const android = { model: "Pixel 8", osVersion: "36", platform: "android" } as const; + const phone = { model: "iPhone 15", physical: true, platform: "ios" } as const; + + const cases = [ + ["an iOS simulator", ios, "feature-x"], + ["an Android emulator", android, "feature-x"], + ["a physical phone", phone, "feature-x"], + ["64 characters", ios, "a".repeat(64)], + ["non-ASCII text", ios, "café 🚀"], + ["a slash and a space", ios, "fix/login sheet"], + ["no label", ios, undefined], + ] as const; + for (const [name, ask, label] of cases) { + const granted = await dispatcher.dispatch( + "lease.request", + { ...ask, ...(label === undefined ? {} : { label }), requesterId: name }, + agent, + ); + const id = granted.lease.id; + const listed = (await dispatcher.dispatch("lease.list", {}, agent)).leases; + const status = (await dispatcher.dispatch("status.get", {}, agent)).leases; + const got = (await dispatcher.dispatch("lease.get", { leaseId: id }, agent)).lease; + const reads = [ + granted.lease, + got, + listed.find((lease) => lease.id === id), + status?.find((lease) => lease.id === id), + ]; + for (const read of reads) { + if (label === undefined) { + expect(read, name).not.toHaveProperty("label"); + } else { + expect(read?.label, name).toBe(label); + } + } + await dispatcher.dispatch("lease.release", { leaseId: id }, agent); + } + }); + + it("a bad label is refused BAD_REQUEST with the same words, and grants nothing", async () => { + const { dispatcher } = await buildDispatcher(); + const ask = { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" } as const; + const agent = session({ principal: "tok_owner" }); + const length = "label must be 1 to 64 characters"; + const control = "label must not contain control characters"; + + const refused = [ + ["empty", "", length], + ["65 characters", "a".repeat(65), length], + ["a newline", "a\nb", control], + ["a tab", "\t", control], + ["NUL", "a\u0000b", control], + ["U+2028", "a\u2028b", control], + ["U+2029", "a\u2029b", control], + ] as const; + for (const [name, label, message] of refused) { + const error = await dispatcher + .dispatch("lease.request", { ...ask, label, noWait: true, requesterId: "bad" }, agent) + .catch((caught: unknown) => caught); + expect(classifyError(error), name).toBe("BAD_REQUEST"); + expect((error as Error).message, name).toBe(message); + } + + const accepted = await dispatcher.dispatch( + "lease.request", + { ...ask, label: "a".repeat(64), requesterId: "good" }, + agent, + ); + expect(accepted.lease.label).toBe("a".repeat(64)); + const held = (await dispatcher.dispatch("status.get", {}, agent)).leases; + expect(held).toHaveLength(1); + }); + + it("an idempotent repeat replays when the labels match and is an IDEMPOTENCY_CONFLICT when they differ", async () => { + const { dispatcher } = await buildDispatcher(); + const ask = { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" } as const; + const agent = session({ principal: "tok_owner" }); + + const cases = [ + ["same label", "feature-x", "feature-x", "replay"], + ["other label", "feature-x", "feature-y", "conflict"], + ["label on the repeat only", undefined, "feature-x", "conflict"], + ["label on the first only", "feature-x", undefined, "conflict"], + ["neither", undefined, undefined, "replay"], + ] as const; + for (const [name, first, repeat, outcome] of cases) { + const base = { ...ask, idempotencyKey: name, requesterId: name }; + const granted = await dispatcher.dispatch( + "lease.request", + { ...base, ...(first === undefined ? {} : { label: first }) }, + agent, + ); + const again = await dispatcher + .dispatch( + "lease.request", + { ...base, ...(repeat === undefined ? {} : { label: repeat }) }, + agent, + ) + .catch((caught: unknown) => caught); + if (outcome === "replay") { + expect((again as typeof granted).lease, name).toEqual(granted.lease); + } else { + expect(classifyError(again), name).toBe("IDEMPOTENCY_CONFLICT"); + } + await dispatcher.dispatch("lease.release", { leaseId: granted.lease.id }, agent); + } + }); +}); diff --git a/src/daemon/dispatcher-leases.ts b/src/daemon/dispatcher-leases.ts index 3f94d3585..a7bcc8f80 100644 --- a/src/daemon/dispatcher-leases.ts +++ b/src/daemon/dispatcher-leases.ts @@ -62,6 +62,7 @@ export class LeaseHandlers { ...(input.idempotencyKey === undefined ? {} : { idempotencyKey: input.idempotencyKey }), ...(input.leaseId === undefined ? {} : { leaseId: input.leaseId }), ...(input.runId === undefined ? {} : { runId: input.runId }), + ...(input.label === undefined ? {} : { label: input.label }), ...(input.fleetRequestId === undefined ? {} : { fleetRequestId: input.fleetRequestId }), ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }), ...(input.ttlMs === undefined ? {} : { ttlMs: input.ttlMs }), diff --git a/src/gateway/dispatcher-leases-label.test.ts b/src/gateway/dispatcher-leases-label.test.ts new file mode 100644 index 000000000..0b9956dde --- /dev/null +++ b/src/gateway/dispatcher-leases-label.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { grantFixture, leaseFixture, ScriptedWorkerClient } from "./test-support.js"; +import { GATEWAY_REQUESTER_PREFIX, harness, session } from "./test-dispatcher.js"; +import { connectWorker } from "./test-fleet.js"; + +describe("GatewayDispatcher: lease.request with a label", () => { + it("a label reaches the worker as sent, a request without one forwards none, and the gateway's lease.get, lease.list and status.get carry the worker's label", async () => { + const { dispatcher, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + const lease = { ...leaseFixture("lse_1", "dev_1"), ownerId: "tok_7f3a" }; + client.requestLeaseQueue.push({ grant: grantFixture({ lease }), kind: "grant" }); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + const agent = session({ principal: "tok_7f3a", role: "agent" }); + + await dispatcher.dispatch( + "lease.request", + { label: "feature-x", model: "iPhone 17", noWait: true, platform: "ios" }, + agent, + ); + expect(client.lastRequestLeaseInput).toMatchObject({ label: "feature-x" }); + + workers.refresh("wrk_a", { + leases: [ + { ...lease, label: "feature-x", requesterId: `${GATEWAY_REQUESTER_PREFIX}tok_7f3a` }, + ], + }); + const listed = await dispatcher.dispatch("lease.list", {}, agent); + expect(listed.leases).toMatchObject([{ id: "wrk_a.lse_1", label: "feature-x" }]); + const got = await dispatcher.dispatch("lease.get", { leaseId: "wrk_a.lse_1" }, agent); + expect(got.lease).toMatchObject({ label: "feature-x" }); + const status = await dispatcher.dispatch("status.get", {}, agent); + expect(status.leases).toMatchObject([{ id: "wrk_a.lse_1", label: "feature-x" }]); + + const plain = harness(); + const plainClient = new ScriptedWorkerClient(); + plainClient.requestLeaseQueue.push({ grant: grantFixture({ lease }), kind: "grant" }); + plain.directory.add("wrk_a", plainClient); + connectWorker(plain.workers, "wrk_a"); + await plain.dispatcher.dispatch( + "lease.request", + { model: "iPhone 17", noWait: true, platform: "ios" }, + agent, + ); + expect(plainClient.lastRequestLeaseInput).not.toHaveProperty("label"); + }); +}); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 26378b72d..e853a2e13 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -735,6 +735,7 @@ export class GatewayDispatcher { ...(input.idempotencyKey === undefined ? {} : { idempotencyKey: input.idempotencyKey }), ...(input.leaseId === undefined ? {} : { leaseId: input.leaseId }), ...(input.runId === undefined ? {} : { runId: input.runId }), + ...(input.label === undefined ? {} : { label: input.label }), ...(input.requires === undefined ? {} : { requires: input.requires }), ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }), // why: Always explicit past this point (§15): a request that named none is filled in here, diff --git a/src/gateway/fleet-dispatch.ts b/src/gateway/fleet-dispatch.ts index 362d6fd24..973b3fa3f 100644 --- a/src/gateway/fleet-dispatch.ts +++ b/src/gateway/fleet-dispatch.ts @@ -384,6 +384,7 @@ export class FleetDispatch { // its refusal (`LEASE_ID_TAKEN`) is the caller's answer: no other worker is tried. ...(waiter.options.leaseId === undefined ? {} : { leaseId: waiter.options.leaseId }), ...(waiter.options.runId === undefined ? {} : { runId: waiter.options.runId }), + ...(waiter.options.label === undefined ? {} : { label: waiter.options.label }), // why: ADR 0021: this gateway's id for the request marks the dispatch a probe. The worker // declines a probe it refuses (`lease.declined`) rather than rejecting it, and names // the id on the lease events of the dispatch. diff --git a/src/http/app-helpers.ts b/src/http/app-helpers.ts index 141d7636d..c173f9339 100644 --- a/src/http/app-helpers.ts +++ b/src/http/app-helpers.ts @@ -28,6 +28,7 @@ function leaseRequestNameFields(body: z.infer) { ...(body.owner === undefined ? {} : { owner: body.owner }), ...(body.leaseId === undefined ? {} : { leaseId: body.leaseId }), ...(body.runId === undefined ? {} : { runId: body.runId }), + ...(body.label === undefined ? {} : { label: body.label }), ...(body.metadata === undefined ? {} : { metadata: body.metadata }), }; } diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index 63a004238..4d1041b45 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -378,6 +378,51 @@ describe("POST /v1/lease-requests runId", () => { }); }); +describe("POST /v1/lease-requests label", () => { + it("passes a body's label onto the dispatch input and names it on the granted lease, on GET /v1/leases/{id} and on GET /v1/leases, and refuses a bad one with the contract's words before dispatching", async () => { + const { app, dispatcher, registry } = buildHarness(); + type Reply = { request: { lease: Record } }; + const labelled = postLeaseRequest(app, { ...defaultBody, label: "feature-x" }); + const call = await waitForDispatch(dispatcher, "lease.request"); + expect(call.input).toMatchObject({ label: "feature-x" }); + call.resolve(makeGrant({ lease: { id: "lse_1", label: "feature-x" } })); + expect(((await (await labelled).json()) as Reply).request.lease).toMatchObject({ + label: "feature-x", + }); + + registry.devices = [makeDevice({ id: "dev_1" })]; + registry.leases = [makeLease({ deviceId: "dev_1", id: "lse_1", label: "feature-x" })]; + const got = await app.request("/v1/leases/lse_1", { headers: agentAuth }); + expect(((await got.json()) as { lease: Record }).lease).toMatchObject({ + label: "feature-x", + }); + const listed = await app.request("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/v1/leases", { headers: agentAuth }); + expect(((await listed.json()) as { leases: Record[] }).leases).toMatchObject([ + { id: "lse_1", label: "feature-x" }, + ]); + + const plain = postLeaseRequest(app, defaultBody, otherAgentAuth); + const second = await waitForDispatch(dispatcher, "lease.request", 1); + expect(second.input).not.toHaveProperty("label"); + second.resolve(makeGrant({ lease: { id: "lse_2" } })); + expect(((await (await plain).json()) as Reply).request.lease).not.toHaveProperty("label"); + + const calls = dispatcher.calls.length; + for (const [label, message] of [ + ["", "label must be 1 to 64 characters"], + ["a".repeat(65), "label must be 1 to 64 characters"], + ["a\nb", "label must not contain control characters"], + ] as const) { + const refused = await postLeaseRequest(app, { ...defaultBody, label }); + expect(refused.status, label).toBe(400); + expect(await refused.json(), label).toMatchObject({ + error: { code: "BAD_REQUEST", message: expect.stringContaining(message) }, + }); + } + expect(dispatcher.calls).toHaveLength(calls); + }); +}); + describe("POST /v1/lease-requests leaseId", () => { it("passes a caller-chosen leaseId onto the dispatch input as sent, and no leaseId key when the body names none", async () => { const { app, dispatcher } = buildHarness(); diff --git a/src/http/lease-declarations.ts b/src/http/lease-declarations.ts index b7d953c30..ff907b915 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -11,6 +11,7 @@ import { INPUT_ORIENTATIONS, leaseIdSchema, OPERATIONS, + refuseBadLabel, refuseBadRunId, refuseModelWithClass, requesterIdSchema, @@ -37,6 +38,7 @@ const leasePayloadSchema = z.object({ platform: z.string(), requestId: z.string().optional(), runId: z.string().max(128).optional(), + label: z.string().max(64).optional(), ttlMs: z.number(), udid: z.string(), worker: z.object({ id: z.string(), label: z.string().optional() }).optional(), @@ -231,6 +233,8 @@ export const leaseRequestBodySchema = z platform: z.enum(["ios", "android"]), // why: A plain string, bounded by `refuseBadRunId` below as the one check, like `lease.request`'s: the same words on every transport. runId: z.string().optional(), + // why: A plain string, bounded by `refuseBadLabel` below as the one check, like `lease.request`'s: the same words on every transport. + label: z.string().optional(), timeoutMs: z.number().int().positive().optional(), ttlMs: z.number().int().positive().optional(), }) @@ -238,7 +242,8 @@ export const leaseRequestBodySchema = z .superRefine((body, context) => refuseModelWithClass("device")({ model: body.device, class: body.class }, context), ) - .superRefine(refuseBadRunId()); + .superRefine(refuseBadRunId()) + .superRefine(refuseBadLabel()); export const leaseRequestCreateRoute = declareRoute({ method: "post", diff --git a/src/http/tracker.ts b/src/http/tracker.ts index ed77a77c5..3db19f928 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -24,6 +24,7 @@ export interface LeaseRequestInput { readonly owner?: string; readonly leaseId?: string; readonly runId?: string; + readonly label?: string; readonly metadata?: Readonly>; } @@ -82,6 +83,7 @@ export function buildLeasePayload( expiresAt: new Date(lease.ttlDeadline).toISOString(), ttlMs: lease.ttlMs, ...(lease.runId === undefined ? {} : { runId: lease.runId }), + ...(lease.label === undefined ? {} : { label: lease.label }), dataPlane: null, ...(device.mode === undefined ? {} : { mode: device.mode }), ...(device.except === undefined ? {} : { except: device.except }), @@ -120,9 +122,16 @@ function requestOptions(body: LeaseRequestInput) { ...(body.allowDownload === undefined ? {} : { allowDownload: body.allowDownload }), ...(body.timeoutMs === undefined ? {} : { timeoutMs: body.timeoutMs }), ...(body.ttlMs === undefined ? {} : { ttlMs: body.ttlMs }), + ...requestNameOptions(body), + }; +} + +function requestNameOptions(body: LeaseRequestInput) { + return { ...(body.owner === undefined ? {} : { owner: body.owner }), ...(body.leaseId === undefined ? {} : { leaseId: body.leaseId }), ...(body.runId === undefined ? {} : { runId: body.runId }), + ...(body.label === undefined ? {} : { label: body.label }), ...(body.metadata === undefined ? {} : { metadata: body.metadata }), }; } @@ -420,6 +429,7 @@ interface HttpLeaseRecord { readonly ttlMs: number; readonly ttlDeadline: number; readonly runId?: string | undefined; + readonly label?: string | undefined; /** ADR 0005 §18: set on a lease a gateway issued, naming the worker it lives on. */ readonly worker?: { readonly id: string; readonly label?: string | undefined } | undefined; } diff --git a/src/leasing/lease-lifecycle.ts b/src/leasing/lease-lifecycle.ts index fc91bb2a9..bcb0e5276 100644 --- a/src/leasing/lease-lifecycle.ts +++ b/src/leasing/lease-lifecycle.ts @@ -22,6 +22,7 @@ export interface LeaseLifecycleRegistry { readonly ttlDeadline: number; readonly leaseId?: string; readonly runId?: string; + readonly label?: string; readonly except?: readonly string[]; readonly request?: { readonly id: string; @@ -81,6 +82,7 @@ export class LeaseLifecycle { * that is in use. */ readonly leaseId?: string; readonly runId?: string; + readonly label?: string; /** why: the categories a slim lease keeps running, written to the device in the grant commit (ADR 0066 §4). */ readonly except?: readonly string[]; /** ADR 0021: the gateway's request id, when the request is a gateway dispatch, carried on diff --git a/src/leasing/lease-request-book.test.ts b/src/leasing/lease-request-book.test.ts index 81894674f..345355739 100644 --- a/src/leasing/lease-request-book.test.ts +++ b/src/leasing/lease-request-book.test.ts @@ -281,7 +281,7 @@ describe("LeaseRequestBook", () => { await book.admit(request, { ...keyed, leaseId: "myid" }, () => granted("myid")); await settled(); - expect(() => book.replay(request, keyed)).toThrow(/different device request or lease ID/); + expect(() => book.replay(request, keyed)).toThrow(/different device request, lease ID/); }); it.each([ diff --git a/src/leasing/lease-request-book.ts b/src/leasing/lease-request-book.ts index 0ada27986..f6db635c1 100644 --- a/src/leasing/lease-request-book.ts +++ b/src/leasing/lease-request-book.ts @@ -101,7 +101,7 @@ export class IdempotencyConflictError extends Error { readonly idempotencyKey: string, ) { super( - `Idempotency key ${idempotencyKey} was already used by requester ${requesterId} for a different device request or lease ID, or run ID`, + `Idempotency key ${idempotencyKey} was already used by requester ${requesterId} for a different device request, lease ID, run ID or label`, ); this.name = "IdempotencyConflictError"; } @@ -222,7 +222,8 @@ export class LeaseRequestBook { } }); + it("the lease tool lists label and sends the label a call names, and none when it names none", async () => { + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant()); + const { mcpClient, close } = await connectedServer(client); + try { + const tools = await mcpClient.request({ method: "tools/list" }, ListToolsResultSchema); + const leaseTool = tools.tools.find((tool) => tool.name === "lease_simulator"); + expect(Object.keys(leaseTool?.inputSchema.properties ?? {})).toContain("label"); + + const ask = { model: "iPhone 17 Pro", platform: "ios" } as const; + expect( + (await call(mcpClient, "lease_simulator", { ...ask, label: "feature-x" })).isError, + ).not.toBe(true); + const sent = client.calls.filter((entry) => entry.method === "requestLease"); + expect(sent[0]?.input).toMatchObject({ label: "feature-x" }); + await call(mcpClient, "release_simulator", { leaseId: "lease-1" }); + expect((await call(mcpClient, "lease_simulator", ask)).isError).not.toBe(true); + const again = client.calls.filter((entry) => entry.method === "requestLease"); + expect(again[1]?.input).not.toHaveProperty("label"); + } finally { + await close(); + } + }); + it("surfaces a daemon FORBIDDEN as-is when releasing a lease this session does not own -- no client-side pre-check", async () => { const client = new FakeSimlockClient(); client.releaseLeaseImpl = () => diff --git a/website/src/content/docs/docs/getting-started/connect-your-agent.mdx b/website/src/content/docs/docs/getting-started/connect-your-agent.mdx index 52f3664d7..ccb688045 100644 --- a/website/src/content/docs/docs/getting-started/connect-your-agent.mdx +++ b/website/src/content/docs/docs/getting-started/connect-your-agent.mdx @@ -125,7 +125,7 @@ The server starts the daemon if it is not running. It renews the agent's lease w | Tool | What it does | | --- | --- | | `list_devices` | Lists the models, OS versions and Android system images you can lease here, and, as `physicalDevices`, the enrolled phones and tablets with their state (`ready`, `leased`, `absent`), why an absent one is absent, and, through a gateway, which worker holds it. It never downloads anything, never says who holds a phone, and `physicalDevices` is empty while the daemon is still starting. | -| `lease_simulator` | Leases one simulator or emulator for this session. Takes `platform` and, optionally, `model` or `class`, `osVersion`, `mode`, `except`, `ttlMs`, `noWait`, `timeoutMs` and `allowDownload`, the same options as `simlock lease`. Returns the same lease the CLI prints. | +| `lease_simulator` | Leases one simulator or emulator for this session. Takes `platform` and, optionally, `model` or `class`, `osVersion`, `mode`, `except`, `ttlMs`, `noWait`, `timeoutMs`, `allowDownload` and `label` (a display-only name for the lease, 1 to 64 characters; on Android and physical devices it shows on the lease only), the same options as `simlock lease`. Returns the same lease the CLI prints. | | `release_simulator` | Releases this session's lease. | | `lease_status` | Reports this session's lease, or `held: false` when it has none. Safe to call any time, for example after the agent's context was compacted. | | `run_on_device` | Runs one `simctl`, `adb` or `devicectl` command on this session's device. Takes `tool`, `args` and, optionally, `stdin` (at most 8,388,608 characters; a longer one fails the tool's input validation, before Simlock sees it). | diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index 32f7ca090..e700d40ba 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -119,7 +119,7 @@ simlock lease --platform [--device | --class ] [--except ] [--baseline ] [--timeout ] [--lease-id ] [--physical] [--no-wait] [--detach] [--ttl ] [--allow-download] - [--run ] [--meta ]... [--export-env] [--bind-pid ] + [--run ] [--label ] [--meta ]... [--export-env] [--bind-pid ] ``` | Flag | Meaning | Default | @@ -136,6 +136,7 @@ simlock lease --platform [--device | --class ] | `--timeout ` | How long to wait in the queue before failing with `QUEUE_TIMEOUT` (exit 10). | No limit: waits until a device is free | | `--lease-id ` | The ID the lease gets, in place of a generated one. 1 to 64 letters, digits, `-` and `_`, starting with a letter or digit. | A generated ID | | `--run ` | The run id the lease carries: a name a CI job gives every lease it takes, 1 to 128 letters, digits, `.`, `_` or `-`, such as `123-1`. A gateway passes it to its worker and its admission command. `simlock status` shows it on the lease line. A bad value exits 2, before the command connects. The `SIMLOCK_RUN` environment variable sets it when the flag is absent; an empty value is unset. | `SIMLOCK_RUN`, else on GitHub Actions `$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT` (`-1` when the attempt is unset), else none | +| `--label ` | A name for the lease, such as `feature-x`: 1 to 64 characters, none of them a control character. It is display-only: nothing routes or limits by it. `simlock status` shows it on the lease line after the run id, and every lease read answers it as `label`. On Android and physical devices it shows on the lease only. A bad value is refused by the daemon with `BAD_REQUEST` (exit 2). | None | | `--meta ` | Repeatable. Context for the gateway's admission command, such as `--meta project=checkout-app --meta role=ci`. The key is the text before the first `=`; the value is everything after it. The same key twice keeps the last. At most 16 keys; a key is 1 to 64 characters, a value 0 to 256, and keys and values together at most 2048. A gateway passes it to its admission command only: it is stored nowhere, in no event, and a worker ignores it. A flag with no `=`, or a bound broken, exits 2. | None | | `--physical` | Lease an enrolled physical device. Cannot be combined with `--mode`, `--image-tag`, `--baseline` or `--allow-download`. | Off: simulators and emulators only | | `--no-wait` | Fail with `NO_CAPACITY` (exit 11) instead of waiting in the queue. | Off | @@ -364,6 +365,8 @@ While an update runs, the line below `CLI:` reads `Updating to : waitin A lease that carries a run id (`simlock lease --run`) shows it on its line: `Lease : on , run since …`. `--json` carries it as the lease's `runId`. +A lease that carries a label (`simlock lease --label`) shows it after the run id: `Lease : on , run , label