Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(node-services): relay Local models between Computers and TeamHub
Dongdong Chendad795b5fe20
diff --git a/apps/node-services/src/agent/AGENTS.md b/apps/node-services/src/agent/AGENTS.mdindex a001ec2a..e0d0ee75 100644--- a/apps/node-services/src/agent/AGENTS.md+++ b/apps/node-services/src/agent/AGENTS.md@@ -101,6 +101,21 @@ take precedence.service-wide native home or shared app-server, E2B, or the Kubernetes cloudsandbox. Every Agent registration, update, and stored Ghost carries a Localplacement; one without it is rejected.+- A Computer's model library is the Daemon's; Agent Service stores none of it+ (`runner-gateway/runner-local-models.ts`). It records each+ `runner.local_models` snapshot in TeamHub (`recordAgentRuntimeLocalModels`),+ drops a revision at or below the connection's last, and keeps one snapshot+ per Computer in flight, sending only the newest after it, so TeamHub never+ stores an older one last. A failed record is logged, the connection stays,+ and the unsaved snapshot is written again after a backoff of 1 to 60+ seconds (at once when a newer one arrives) until TeamHub stores it or+ answers that it never will (a 4xx). `actOnLocalComputerModels` sends `execute` `local_models` only to a+ connection that has reported a library (an older Daemon would treat the+ command as a protocol error), and answers with the Computer's+ accept or refusal, `LOCAL_MODELS_ACTION_TIMEOUT` past the command's+ `expires_at` (at most 30 seconds; the Daemon never answers after that+ deadline, so the outcome is unknown, not refused), or+ `LOCAL_COMPUTER_OFFLINE`.- Default unit, integration, and fixture smoke tests use deterministic adaptersand do not call a live model provider. Explicitly named live suites such as`smoke:local-runner:live` may use an authenticated provider and must remaindiff --git a/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts b/apps/node-services/src/agent/executor/http/agent-manager-http-server.tsindex 93cef775..c764bac7 100644--- a/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts+++ b/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts@@ -27,6 +27,7 @@ import {createLocalComputerRouteHandlers,LocalComputerHttpError,registerLocalComputerCompatibilityRoutes,+ registerLocalComputerModelRoutes,registerLocalComputerPermissionRoutes,} from "./local-computer-http.js";import {@@ -649,6 +650,7 @@ const createAgentManagerHttpApp = <TRuntimeSettings>(app.post("/v1/local-computer-tools:call", handlers.callLocalComputerTool);registerLocalComputerCompatibilityRoutes(app, handlers);registerLocalComputerPermissionRoutes(app, handlers);+ registerLocalComputerModelRoutes(app, handlers);app.notFound((context) =>writeProtocolError(context, 404, "not_found", "Not found"),diff --git a/apps/node-services/src/agent/executor/http/local-computer-http.ts b/apps/node-services/src/agent/executor/http/local-computer-http.tsindex 4f9310ee..52a94017 100644--- a/apps/node-services/src/agent/executor/http/local-computer-http.ts+++ b/apps/node-services/src/agent/executor/http/local-computer-http.ts@@ -13,6 +13,10 @@ import {type LocalComputerPermissionCommand,type LocalComputerManagement,} from "../../runner-gateway/local-computer-management.js";+import {+ LocalModelsActionTimeoutError,+ type LocalModelActionCommand,+} from "../../runner-gateway/runner-local-models.js";import { isRecord } from "@linger/service-kit";type LocalComputerHttpStatus = 400 | 404 | 405 | 409 | 410 | 502 | 503;@@ -42,6 +46,7 @@ export interface LocalComputerRouteHandlers {): Promise<Response> | Response;getLocalComputerPermissions(context: Context): Promise<Response> | Response;actOnLocalComputerPermission(context: Context): Promise<Response> | Response;+ actOnLocalComputerModels(context: Context): Promise<Response> | Response;}export const createLocalComputerRouteHandlers = (options: {@@ -176,6 +181,41 @@ export const createLocalComputerRouteHandlers = (options: {context,parseComputerPermissionAction(await options.readJsonBody(context)),),+ actOnLocalComputerModels: async (context) => {+ const management = requireLocalComputerManagement(+ options.localComputerManagement,+ );+ if (!management.actOnLocalModels) {+ throw new LocalComputerHttpError(+ 503,+ "LOCAL_MODELS_UNAVAILABLE",+ "Local models are unavailable",+ );+ }+ const body = parseLocalModelActionCommand(+ await options.readJsonBody(context),+ );+ try {+ const ack = await management.actOnLocalModels({+ tenantId: options.pathId(context, "tenantId"),+ ownerActorId: options.pathId(context, "ownerActorId"),+ computerId: options.pathId(context, "computerId"),+ action: body.action,+ ...(body.model_id === undefined ? {} : { modelId: body.model_id }),+ ...(body.unload_first === undefined+ ? {}+ : { unloadFirst: body.unload_first }),+ expiresAt: body.expires_at,+ signal: context.req.raw.signal,+ });+ return writeJson(context, 200, {+ request_id: body.request_id,+ ...ack,+ });+ } catch (error) {+ throw localModelsRequestError(error);+ }+ },});const computerPermissions = async (@@ -231,6 +271,109 @@ export const registerLocalComputerPermissionRoutes = (app.all(path, (context) => methodNotAllowed(context, "GET, POST"));};+/**+ * Mounts the local-models action route next to the generated Agent+ * management routes, which do not own this path yet.+ */+export const registerLocalComputerModelRoutes = (+ app: Hono,+ handlers: Pick<LocalComputerRouteHandlers, "actOnLocalComputerModels">,+): void => {+ const path =+ "/v1/tenants/:tenantId/owners/:ownerActorId/local-computers/:computerId/local-model-actions";+ app.post(path, handlers.actOnLocalComputerModels);+ app.all(path, (context) => methodNotAllowed(context, "POST"));+};++const LOCAL_MODEL_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/u;+const LOCAL_MODEL_ACTIONS: ReadonlySet<unknown> = new Set([+ "download",+ "cancel",+ "load",+ "unload",+ "remove",+ "refresh",+]);++const isLocalModelId = (value: unknown): value is string =>+ typeof value === "string" && LOCAL_MODEL_ID_PATTERN.test(value);++const parseLocalModelActionCommand = (value: unknown) => {+ const unloadFirst = isRecord(value) ? value.unload_first : undefined;+ if (+ !isRecord(value) ||+ Object.keys(value).some(+ (key) =>+ ![+ "request_id",+ "action",+ "model_id",+ "unload_first",+ "expires_at",+ ].includes(key),+ ) ||+ !isProtocolId(value.request_id) ||+ !LOCAL_MODEL_ACTIONS.has(value.action) ||+ !isTimestamp(value.expires_at) ||+ // refresh names no model; every other action names one.+ (value.action === "refresh") !== (value.model_id === undefined) ||+ (value.model_id !== undefined && !isLocalModelId(value.model_id)) ||+ (unloadFirst !== undefined &&+ (value.action !== "load" ||+ !Array.isArray(unloadFirst) ||+ unloadFirst.length > 64 ||+ !unloadFirst.every(isLocalModelId) ||+ new Set(unloadFirst).size !== unloadFirst.length))+ ) {+ throw new LocalComputerHttpError(+ 400,+ "INVALID_LOCAL_MODEL_ACTION",+ "Local model action is invalid",+ );+ }+ return value as {+ readonly request_id: string;+ readonly action: LocalModelActionCommand["action"];+ readonly model_id?: string;+ readonly unload_first?: readonly string[];+ readonly expires_at: string;+ };+};++const localModelsRequestError = (error: unknown): Error => {+ if (error instanceof LocalComputerNotFoundError) {+ return new LocalComputerHttpError(+ 404,+ "LOCAL_COMPUTER_NOT_FOUND",+ error.message,+ );+ }+ if (error instanceof LocalComputerOfflineError) {+ return new LocalComputerHttpError(+ 503,+ "LOCAL_COMPUTER_OFFLINE",+ error.message,+ );+ }+ if (error instanceof LocalComputerCapabilityError) {+ return new LocalComputerHttpError(+ 409,+ "LOCAL_MODELS_UNSUPPORTED",+ error.message,+ );+ }+ if (error instanceof LocalModelsActionTimeoutError) {+ return new LocalComputerHttpError(+ 503,+ "LOCAL_MODELS_ACTION_TIMEOUT",+ error.message,+ );+ }+ return error instanceof Error+ ? error+ : new Error("Local models action failed");+};+const browserConnection = async (options: {readonly localComputerManagement: LocalComputerManagement | undefined;diff --git a/apps/node-services/src/agent/executor/teamhub-runtime-state-client.ts b/apps/node-services/src/agent/executor/teamhub-runtime-state-client.tsindex 5c6488a4..911ede55 100644--- a/apps/node-services/src/agent/executor/teamhub-runtime-state-client.ts+++ b/apps/node-services/src/agent/executor/teamhub-runtime-state-client.ts@@ -179,6 +179,10 @@ export interface TeamHubRuntimeStateClient {body: RuntimeStateSchemas["AgentRuntimeLocalComputerCredentialRequest"],signal?: AbortSignal,): Promise<RuntimeStateSchemas["AgentRuntimeLocalComputerRemovalResult"]>;+ recordLocalModels(+ body: RuntimeStateSchemas["RecordLocalModelsRequest"],+ signal?: AbortSignal,+ ): Promise<void>;recordRunOperation(body: RuntimeStateSchemas["RecordAgentLocalRunOperationRequest"],signal?: AbortSignal,@@ -264,6 +268,7 @@ export const createTeamHubRuntimeStateClient = (responsesAfterUnknownAttempt.has(response),);}+ if (response.status === 204) return undefined as T;try {return (await response.json()) as T;} catch (error) {@@ -430,6 +435,8 @@ export const createTeamHubRuntimeStateClient = (raw.removeLocalComputer(body, signal),signal,),+ recordLocalModels: (body, signal) =>+ request<void>(raw.recordLocalModels(body, signal), signal),recordRunOperation: (body, signal) =>request<RuntimeStateSchemas["AgentRuntimeSuccessResult"]>(raw.recordRunOperation(body, signal),diff --git a/apps/node-services/src/agent/runner-gateway/local-computer-management.ts b/apps/node-services/src/agent/runner-gateway/local-computer-management.tsindex 396cd3a0..7c48c6b5 100644--- a/apps/node-services/src/agent/runner-gateway/local-computer-management.ts+++ b/apps/node-services/src/agent/runner-gateway/local-computer-management.ts@@ -1,4 +1,8 @@import type { RuntimeExecutionFailure } from "../executor/provider.js";+import type {+ LocalModelActionAck,+ LocalModelActionCommand,+} from "./runner-local-models.js";import type {BrowserConnectionStatus,ComputerPermissionStatus,@@ -127,6 +131,10 @@ export interface LocalComputerManagement {command: LocalComputerPermissionCommand,): Promise<LocalComputerPermissionStatus>;+ actOnLocalModels?(+ command: LocalModelActionCommand,+ ): Promise<LocalModelActionAck>;+/** Returns the placed model as the connected Computer reports it. */requireLocalPlacement(requirement: LocalPlacementRequirement,diff --git a/apps/node-services/src/agent/runner-gateway/local-computer-registry.ts b/apps/node-services/src/agent/runner-gateway/local-computer-registry.tsindex 2ec98aed..c67f3b00 100644--- a/apps/node-services/src/agent/runner-gateway/local-computer-registry.ts+++ b/apps/node-services/src/agent/runner-gateway/local-computer-registry.ts@@ -1,6 +1,7 @@import { createHash } from "node:crypto";import type {+ LocalModelsSnapshot,RunnerHello,RuntimeDiagnostics,} from "@linger/wire-contracts/runner-gateway/types";@@ -74,6 +75,11 @@ export interface LocalComputerRegistry {connection: LocalComputerConnection,): Promise<readonly RunnerPlacement[]>;touch(computerId: string, touch: LocalComputerTouch): Promise<void>;+ /** Replaces the Computer's stored model library with its latest snapshot. */+ recordLocalModels(+ computerId: string,+ snapshot: LocalModelsSnapshot,+ ): Promise<void>;remove(input: LocalComputerOwner & { readonly computerId: string },): Promise<LocalComputerRemovalResult>;@@ -86,6 +92,7 @@ export const createTeamHubLocalComputerRegistry = (| "connectLocalComputer"| "touchLocalComputer"| "removeLocalComputer"+ | "recordLocalModels">,): LocalComputerRegistry => ({async credentialGeneration(computerId, owner) {@@ -165,6 +172,12 @@ export const createTeamHubLocalComputerRegistry = (: { recommended_version: touch.recommendedVersion }),});},+ async recordLocalModels(computerId, snapshot) {+ await client.recordLocalModels({+ computer_id: computerId,+ snapshot: structuredClone(snapshot),+ });+ },async remove({ computerId, tenantId, ownerActorId }) {const response = await client.removeLocalComputer({computer_id: computerId,diff --git a/apps/node-services/src/agent/runner-gateway/runner-connections.ts b/apps/node-services/src/agent/runner-gateway/runner-connections.tsindex b043bc18..1118e19e 100644--- a/apps/node-services/src/agent/runner-gateway/runner-connections.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-connections.ts@@ -46,6 +46,7 @@ import {type RunnerGatewayPrincipal,} from "./runner-gateway-principal.js";import { isLocalSkillOutcome } from "./runner-local-capabilities.js";+import { isLocalModelsOutcome } from "./runner-local-models.js";import {RunnerGatewayError,RunnerGatewayProtocolError,@@ -84,6 +85,7 @@ export class RunnerConnections {| "lifecycle"| "modelInvocation"| "computerTools"+ | "localModels"| "operations"| "preparation">,@@ -406,10 +408,12 @@ export class RunnerConnections {phase: "reconciling",operationReconciled: false,runtimeDiagnosticsRevision: 0,+ localModelsRevision: 0,};this.#connections.set(hello.runner_id, connection);if (previous?.connected) {this.owners.capabilities().rejectConnectionWaiters(previous);+ this.owners.localModels().disconnected(previous);this.#clearHeartbeat(previous);previous.connected = false;previous.peer.close(1012, "Runner connection replaced");@@ -661,16 +665,12 @@ export class RunnerConnections {this.owners.capabilities().receiveLocalSkillOutcome(envelope);return;}- if (- envelope.type === "runner.local_models" ||- (envelope.type === "executed" && envelope.kind === "local_models")- ) {- // Agent Service does not relay local models to TeamHub yet; dropping the- // frame keeps a Computer that already reports them connected.- logAgentEvent("info", "runner.local_models.ignored", {- runnerId: connection.runnerId,- frameType: envelope.type,- });+ if (envelope.type === "runner.local_models") {+ this.owners.localModels().receiveSnapshot(connection, envelope);+ return;+ }+ if (isLocalModelsOutcome(envelope)) {+ this.owners.localModels().receiveOutcome(connection, envelope);return;}if (envelope.type === "prepared" && envelope.target === "provider") {@@ -890,6 +890,7 @@ export class RunnerConnections {disconnect(connection: ConnectedRunner): void {this.owners.capabilities().rejectConnectionWaiters(connection);+ this.owners.localModels().disconnected(connection);this.#clearHeartbeat(connection);connection.connected = false;this.owners.operations().wakeCapacityWaiters();diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway-context.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway-context.tsindex 212e64b9..d75ad33a 100644--- a/apps/node-services/src/agent/runner-gateway/runner-gateway-context.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway-context.ts@@ -43,6 +43,7 @@ import {import type { RunnerOperations } from "./runner-operations.js";import { operationMCPPrepareIdentity } from "./runner-operations.js";import type { RunnerComputerTools } from "./runner-computer-tools.js";+import type { RunnerLocalModels } from "./runner-local-models.js";import type { ModelQueue } from "./model-queue.js";import type { RunnerModelInvocation } from "./runner-model-invocation.js";import type { RunnerSessionCompaction } from "./runner-session-compaction.js";@@ -227,6 +228,8 @@ export interface ConnectedRunner {* acknowledges the previous one, so every unacknowledged one is valid.*/pendingRegistrationSnapshots?: Set<string>;+ /** The last runner.local_models revision; 0 until the connection sends one. */+ localModelsRevision: number;}export interface AgentRunnerStateWaiter {@@ -332,6 +335,7 @@ export interface RunnerGatewayControllers {readonly modelInvocation: () => RunnerModelInvocation;readonly queue: () => ModelQueue;readonly computerTools: () => RunnerComputerTools;+ readonly localModels: () => RunnerLocalModels;readonly contextViewContent: () => ContextViewContent | undefined;}const DEFAULT_HEARTBEAT_INTERVAL_MS = 5_000;diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway.tsindex 707d7c30..a2d47b43 100644--- a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts@@ -52,6 +52,11 @@ import {} from "./runner-gateway-context.js";import { type RunnerGatewayPrincipal } from "./runner-gateway-principal.js";import { RunnerLocalCapabilities } from "./runner-local-capabilities.js";+import {+ RunnerLocalModels,+ type LocalModelActionAck,+ type LocalModelActionCommand,+} from "./runner-local-models.js";import { RunnerOperationPreparation } from "./runner-operation-preparation.js";import type {RunnerCapacityPermit,@@ -142,6 +147,7 @@ export class RunnerGatewayreadonly #modelInvocation: RunnerModelInvocation;readonly #queue: ModelQueue;readonly #computerTools: RunnerComputerTools;+ readonly #localModels: RunnerLocalModels;constructor(options: RunnerGatewayOptions) {const context = createRunnerGatewayContext(options);const owners: RunnerGatewayControllers = {@@ -156,6 +162,7 @@ export class RunnerGatewaymodelInvocation: () => this.#modelInvocation,queue: () => this.#queue,computerTools: () => this.#computerTools,+ localModels: () => this.#localModels,contextViewContent: () => this.contextViewContent,};this.#connections = new RunnerConnections(context, owners);@@ -173,6 +180,7 @@ export class RunnerGateway),);this.#computerTools = new RunnerComputerTools(context, owners);+ this.#localModels = new RunnerLocalModels(context, owners);validateRunnerGatewayContext(context);if (options.contextContent) {this.contextViewContent = createContextViewContent({@@ -317,6 +325,12 @@ export class RunnerGatewayreturn this.#capabilities.scanLocalSkills(command);}+ async actOnLocalModels(+ command: LocalModelActionCommand,+ ): Promise<LocalModelActionAck> {+ return this.#localModels.act(command);+ }+async runLocalComputerMutation<T>(computerId: string,operation: () => Promise<T>,diff --git a/apps/node-services/src/agent/runner-gateway/runner-local-models.ts b/apps/node-services/src/agent/runner-gateway/runner-local-models.tsnew file mode 100644index 00000000..b6741937--- /dev/null+++ b/apps/node-services/src/agent/runner-gateway/runner-local-models.ts@@ -0,0 +1,300 @@+import type {+ CapabilityLocalModelsAccepted,+ CapabilityLocalModelsRefused,+ DaemonToAgentEnvelope,+ LocalModelActionRefusal,+ LocalModelsSnapshot,+ RunnerLocalModels as RunnerLocalModelsFrame,+} from "@linger/wire-contracts/runner-gateway/types";+import {+ RUNNER_GATEWAY_PROTOCOL_VERSION,+ parseAgentToDaemonEnvelope,+} from "@linger/wire-contracts/runner-gateway/validator";+import { TeamHubRuntimeStateError } from "../executor/teamhub-runtime-state-client.js";+import { logAgentEvent } from "../observability/agent-log.js";+import {+ LocalComputerCapabilityError,+ LocalComputerNotFoundError,+ LocalComputerOfflineError,+} from "./local-computer-management.js";+import { isServingConnection } from "./runner-connections.js";+import type {+ ConnectedRunner,+ RunnerGatewayContext,+ RunnerGatewayControllers,+} from "./runner-gateway-context.js";+import { RunnerGatewayProtocolError } from "./runner-operation.js";++export type LocalModelActionKind =+ | "download"+ | "cancel"+ | "load"+ | "unload"+ | "remove"+ | "refresh";++/** One action on an owned Computer's model library. */+export interface LocalModelActionCommand {+ readonly tenantId: string;+ readonly ownerActorId: string;+ readonly computerId: string;+ readonly action: LocalModelActionKind;+ /** Absent only for refresh. */+ readonly modelId?: string;+ /** Only for load. */+ readonly unloadFirst?: readonly string[];+ readonly expiresAt: string;+ readonly signal?: AbortSignal;+}++/** The Computer's immediate answer; progress arrives only as snapshots. */+export type LocalModelActionAck =+ | { readonly outcome: "accepted" }+ | { readonly outcome: "refused"; readonly refusal: LocalModelActionRefusal };++/** The Computer did not answer an action before it expired. */+export class LocalModelsActionTimeoutError extends Error {+ constructor() {+ super("Local Computer did not answer the local-models action");+ this.name = "LocalModelsActionTimeoutError";+ }+}++type LocalModelsOutcome =+ | CapabilityLocalModelsAccepted+ | CapabilityLocalModelsRefused;++interface ActionWaiter {+ readonly connection: ConnectedRunner;+ readonly action: LocalModelActionKind;+ readonly modelId: string | undefined;+ readonly resolve: (outcome: LocalModelsOutcome) => void;+ readonly reject: (error: unknown) => void;+}++interface SnapshotQueue {+ next: LocalModelsSnapshot | undefined;+ /** Ends a retry delay early: a newer snapshot is written at once. */+ wake?: () => void;+}++// A snapshot TeamHub failed to store is written again after these delays.+const FIRST_RECORD_RETRY_MS = 1_000;+const MAX_RECORD_RETRY_MS = 60_000;++// The Computer answers once localmodels has validated the action, which can+// take a few seconds. Past the command's expiry (and never past this bound)+// the action is unconfirmed, not refused: the Computer may still run it, and+// its snapshots show the outcome.+const MAX_ACTION_ACK_WAIT_MS = 30_000;++/**+ * Relays a Computer's model library to TeamHub and its actions to the+ * Computer. The Computer reports each library change as a runner.local_models+ * snapshot; this keeps only the newest one per Computer in flight, so TeamHub+ * receives one Computer's snapshots one at a time and never an older one last.+ */+export class RunnerLocalModels {+ readonly #waiters = new Map<string, ActionWaiter>();++ readonly #queues = new Map<string, SnapshotQueue>();++ constructor(+ private readonly context: RunnerGatewayContext,+ private readonly owners: Pick<RunnerGatewayControllers, "connections">,+ ) {}++ receiveSnapshot(+ connection: ConnectedRunner,+ frame: RunnerLocalModelsFrame,+ ): void {+ if (frame.revision <= connection.localModelsRevision) {+ logAgentEvent("warn", "runner.local_models.stale", {+ runnerId: connection.runnerId,+ revision: frame.revision,+ currentRevision: connection.localModelsRevision,+ });+ return;+ }+ connection.localModelsRevision = frame.revision;+ const queue = this.#queues.get(connection.runnerId);+ if (queue) {+ queue.next = frame.local_models;+ queue.wake?.();+ return;+ }+ const started: SnapshotQueue = { next: frame.local_models };+ this.#queues.set(connection.runnerId, started);+ void this.#drain(connection.runnerId, started);+ }++ async #drain(computerId: string, queue: SnapshotQueue): Promise<void> {+ let retryMs = FIRST_RECORD_RETRY_MS;+ for (+ let snapshot = queue.next;+ snapshot !== undefined;+ snapshot = queue.next+ ) {+ queue.next = undefined;+ try {+ await this.context.computerRegistry?.recordLocalModels(+ computerId,+ snapshot,+ );+ retryMs = FIRST_RECORD_RETRY_MS;+ } catch (error) {+ const retryable = !(+ error instanceof TeamHubRuntimeStateError && !error.retryable+ );+ logAgentEvent("warn", "runner.local_models.record_failed", {+ runnerId: computerId,+ retryable,+ error: error instanceof Error ? error.message : String(error),+ });+ // The Computer reports again only when its library changes, so the+ // unsaved snapshot is kept until TeamHub stores it; a newer one that+ // arrives meanwhile replaces it.+ if (!retryable || queue.next !== undefined) continue;+ queue.next = snapshot;+ await new Promise<void>((resolve) => {+ const timer = setTimeout(resolve, retryMs);+ timer.unref();+ queue.wake = () => {+ clearTimeout(timer);+ resolve();+ };+ });+ queue.wake = undefined;+ retryMs = Math.min(2 * retryMs, MAX_RECORD_RETRY_MS);+ }+ }+ this.#queues.delete(computerId);+ }++ /**+ * Sends one action and waits for the Computer's accept or refusal. Only a+ * connection that reported a library takes actions: an older Computer+ * would treat the unknown command as a protocol error.+ */+ async act(command: LocalModelActionCommand): Promise<LocalModelActionAck> {+ command.signal?.throwIfAborted();+ const connection = this.owners+ .connections()+ .getConnection(command.computerId);+ if (!isServingConnection(connection)) {+ throw new LocalComputerOfflineError();+ }+ if (+ connection.tenantOwners.get(command.tenantId) !== command.ownerActorId+ ) {+ throw new LocalComputerNotFoundError();+ }+ if (connection.localModelsRevision === 0) {+ throw new LocalComputerCapabilityError(+ "Local Computer has not reported a model library",+ );+ }+ const commandId = this.context.createId();+ const envelope = parseAgentToDaemonEnvelope({+ type: "execute",+ kind: "local_models",+ protocol_version: RUNNER_GATEWAY_PROTOCOL_VERSION,+ command_id: commandId,+ runner_id: command.computerId,+ tenant_id: command.tenantId,+ owner_actor_id: command.ownerActorId,+ connection_epoch: connection.connectionEpoch,+ expires_at: command.expiresAt,+ action: command.action,+ ...(command.modelId === undefined ? {} : { model_id: command.modelId }),+ ...(command.unloadFirst === undefined+ ? {}+ : { unload_first: [...command.unloadFirst] }),+ });+ const signal = command.signal;+ let onAbort: (() => void) | undefined;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const outcome = new Promise<LocalModelsOutcome>((resolve, reject) => {+ const waitMs = Math.min(+ MAX_ACTION_ACK_WAIT_MS,+ Math.max(0, Date.parse(command.expiresAt) - Date.now()),+ );+ timer = setTimeout(+ () => reject(new LocalModelsActionTimeoutError()),+ waitMs,+ );+ timer.unref();+ onAbort = () => reject(signal?.reason);+ signal?.addEventListener("abort", onAbort, { once: true });+ this.#waiters.set(commandId, {+ connection,+ action: command.action,+ modelId: command.modelId,+ resolve,+ reject,+ });+ });+ let result: LocalModelsOutcome;+ try {+ [, result] = await Promise.all([+ this.owners.connections().sendToCurrentRunner(envelope),+ outcome,+ ]);+ } finally {+ clearTimeout(timer);+ if (onAbort) signal?.removeEventListener("abort", onAbort);+ this.#waiters.delete(commandId);+ }+ return result.outcome === "accepted"+ ? { outcome: "accepted" }+ : { outcome: "refused", refusal: result.refusal };+ }++ receiveOutcome(connection: ConnectedRunner, envelope: LocalModelsOutcome) {+ if (+ envelope.connection_epoch !== connection.connectionEpoch ||+ connection.tenantOwners.get(envelope.tenant_id) !==+ envelope.owner_actor_id+ ) {+ throw new RunnerGatewayProtocolError(+ "Runner local-models outcome identity mismatch",+ );+ }+ const waiter = this.#waiters.get(envelope.command_id);+ if (!waiter) {+ // The action already expired; the Computer's next snapshot shows it.+ logAgentEvent("info", "runner.local_models.late_outcome", {+ runnerId: connection.runnerId,+ commandId: envelope.command_id,+ outcome: envelope.outcome,+ });+ return;+ }+ if (+ waiter.connection !== connection ||+ waiter.action !== envelope.action ||+ waiter.modelId !== envelope.model_id+ ) {+ throw new RunnerGatewayProtocolError(+ "Runner local-models command identity mismatch",+ );+ }+ this.#waiters.delete(envelope.command_id);+ waiter.resolve(envelope);+ }++ /** Fails every action still waiting on this connection. */+ disconnected(connection: ConnectedRunner): void {+ for (const [commandId, waiter] of this.#waiters) {+ if (waiter.connection !== connection) continue;+ this.#waiters.delete(commandId);+ waiter.reject(new LocalComputerOfflineError());+ }+ }+}++export function isLocalModelsOutcome(+ envelope: DaemonToAgentEnvelope,+): envelope is LocalModelsOutcome {+ return envelope.type === "executed" && envelope.kind === "local_models";+}diff --git a/apps/node-services/tests/agent/executor/http/local-computer-models-http.test.ts b/apps/node-services/tests/agent/executor/http/local-computer-models-http.test.tsnew file mode 100644index 00000000..f3901082--- /dev/null+++ b/apps/node-services/tests/agent/executor/http/local-computer-models-http.test.ts@@ -0,0 +1,190 @@+import { Hono } from "hono";+import { describe, expect, it, vi } from "vitest";+import {+ createLocalComputerRouteHandlers,+ LocalComputerHttpError,+ registerLocalComputerModelRoutes,+} from "../../../../src/agent/executor/http/local-computer-http.js";+import {+ LocalComputerCapabilityError,+ LocalComputerNotFoundError,+ LocalComputerOfflineError,+ type LocalComputerManagement,+} from "../../../../src/agent/runner-gateway/local-computer-management.js";+import {+ LocalModelsActionTimeoutError,+ type LocalModelActionAck,+ type LocalModelActionCommand,+} from "../../../../src/agent/runner-gateway/runner-local-models.js";++const path =+ "/v1/tenants/tenant-1/owners/actor-1/local-computers/computer-1/local-model-actions";+const expiresAt = "2026-11-13T10:00:10.000Z";++const createApp = (+ actOnLocalModels: (+ command: LocalModelActionCommand,+ ) => Promise<LocalModelActionAck>,+) => {+ const handlers = createLocalComputerRouteHandlers({+ localComputerManagement: {+ actOnLocalModels,+ } as unknown as LocalComputerManagement,+ pathId: (context, name) => context.req.param(name) ?? "",+ readJsonBody: (context) => context.req.json(),+ });+ const app = new Hono();+ registerLocalComputerModelRoutes(app, handlers);+ app.onError((error, context) =>+ error instanceof LocalComputerHttpError+ ? context.json({ code: error.errorCode }, error.status)+ : context.json({ code: "internal" }, 500),+ );+ return app;+};++const post = (app: Hono, body: unknown) =>+ app.request(path, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ });++describe("Agent Management local-models action route", () => {+ it("forwards the action and returns the Computer's answer under the request ID", async () => {+ const act = vi.fn(+ async (+ _command: LocalModelActionCommand,+ ): Promise<LocalModelActionAck> => ({ outcome: "accepted" }),+ );+ const response = await post(createApp(act), {+ request_id: "request-1",+ action: "load",+ model_id: "qwen3-4b:Q4_K_M",+ unload_first: ["gemma-3:Q4"],+ expires_at: expiresAt,+ });+ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({+ request_id: "request-1",+ outcome: "accepted",+ });+ expect(act).toHaveBeenCalledWith(+ expect.objectContaining({+ tenantId: "tenant-1",+ ownerActorId: "actor-1",+ computerId: "computer-1",+ action: "load",+ modelId: "qwen3-4b:Q4_K_M",+ unloadFirst: ["gemma-3:Q4"],+ expiresAt,+ }),+ );++ const refused = vi.fn(+ async (): Promise<LocalModelActionAck> => ({+ outcome: "refused",+ refusal: { code: "LOAD_NO_ROOM", pool: "gpu:0", need_bytes: 9 },+ }),+ );+ const refusal = await post(createApp(refused), {+ request_id: "request-2",+ action: "refresh",+ expires_at: expiresAt,+ });+ expect(refusal.status).toBe(200);+ expect(await refusal.json()).toEqual({+ request_id: "request-2",+ outcome: "refused",+ refusal: { code: "LOAD_NO_ROOM", pool: "gpu:0", need_bytes: 9 },+ });+ });++ it("rejects malformed actions before reaching the Computer", async () => {+ const act = vi.fn();+ const app = createApp(act);+ for (const body of [+ { request_id: "r", action: "download", expires_at: expiresAt },+ {+ request_id: "r",+ action: "refresh",+ model_id: "m:1",+ expires_at: expiresAt,+ },+ {+ request_id: "r",+ action: "unload",+ model_id: "m:1",+ unload_first: ["a:1"],+ expires_at: expiresAt,+ },+ {+ request_id: "r",+ action: "load",+ model_id: "m:1",+ unload_first: ["a:1", "a:1"],+ expires_at: expiresAt,+ },+ {+ request_id: "r",+ action: "load",+ model_id: "../m",+ expires_at: expiresAt,+ },+ {+ request_id: "r",+ action: "pause",+ model_id: "m:1",+ expires_at: expiresAt,+ },+ { request_id: "r", action: "unload", model_id: "m:1" },+ {+ request_id: "r",+ action: "unload",+ model_id: "m:1",+ expires_at: expiresAt,+ extra: true,+ },+ ]) {+ const response = await post(app, body);+ expect(response.status, JSON.stringify(body)).toBe(400);+ expect(await response.json()).toEqual({+ code: "INVALID_LOCAL_MODEL_ACTION",+ });+ }+ expect(act).not.toHaveBeenCalled();+ });++ it("maps Gateway failures to the codes TeamHub reads", async () => {+ for (const [error, status, code] of [+ [new LocalComputerNotFoundError(), 404, "LOCAL_COMPUTER_NOT_FOUND"],+ [new LocalComputerOfflineError(), 503, "LOCAL_COMPUTER_OFFLINE"],+ [+ new LocalComputerCapabilityError("no library"),+ 409,+ "LOCAL_MODELS_UNSUPPORTED",+ ],+ [new LocalModelsActionTimeoutError(), 503, "LOCAL_MODELS_ACTION_TIMEOUT"],+ ] as const) {+ const response = await post(+ createApp(async () => {+ throw error;+ }),+ {+ request_id: "r",+ action: "unload",+ model_id: "m:1",+ expires_at: expiresAt,+ },+ );+ expect(response.status).toBe(status);+ expect(await response.json()).toEqual({ code });+ }+ });++ it("allows only POST", async () => {+ const response = await createApp(vi.fn()).request(path);+ expect(response.status).toBe(405);+ expect(response.headers.get("allow")).toBe("POST");+ });+});diff --git a/apps/node-services/tests/agent/executor/teamhub-runtime-state-client.test.ts b/apps/node-services/tests/agent/executor/teamhub-runtime-state-client.test.tsindex ccc9507d..2bcb8578 100644--- a/apps/node-services/tests/agent/executor/teamhub-runtime-state-client.test.ts+++ b/apps/node-services/tests/agent/executor/teamhub-runtime-state-client.test.ts@@ -151,6 +151,31 @@ describe("TeamHubRuntimeStateClient retries", () => {},);+ it("records a Computer's model library and accepts TeamHub's empty answer", async () => {+ const fetchRequest = vi.fn<typeof fetch>(+ async () => new Response(null, { status: 204 }),+ );+ const body = {+ computer_id: "runner-local",+ snapshot: {+ available: false,+ reason: { code: "TOOL_NOT_INSTALLED" as const },+ observed_at: "2026-11-13T10:00:00.000Z",+ pools: [],+ models: [],+ },+ };+ await expect(+ runtimeStateClient(fetchRequest).recordLocalModels(body),+ ).resolves.toBeUndefined();+ const [input, init] = fetchRequest.mock.calls[0]!;+ expect(new URL(requestUrlText(input)).pathname).toBe(+ "/v0/agent-runtime/local-computers/local-models",+ );+ expect(init?.method).toBe("POST");+ expect(JSON.parse(init?.body as string)).toEqual(body);+ });+it("posts a bounded Context reconciliation page", async () => {const fetchRequest = vi.fn().mockResolvedValue(jsonResponse({diff --git a/apps/node-services/tests/agent/runner-gateway/runner-gateway-local-models.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-gateway-local-models.test.tsnew file mode 100644index 00000000..0a8bc856--- /dev/null+++ b/apps/node-services/tests/agent/runner-gateway/runner-gateway-local-models.test.ts@@ -0,0 +1,445 @@+import type {+ AgentToDaemonEnvelope,+ CapabilityLocalModelsExecute,+ LocalModelsSnapshot,+} from "@linger/wire-contracts/runner-gateway/types";+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ LocalComputerCapabilityError,+ LocalComputerNotFoundError,+ LocalComputerOfflineError,+} from "../../../src/agent/runner-gateway/local-computer-management.js";+import { type RunnerGatewayConnection } from "../../../src/agent/runner-gateway/runner-gateway.js";+import { TeamHubRuntimeStateError } from "../../../src/agent/executor/teamhub-runtime-state-client.js";+import { LocalModelsActionTimeoutError } from "../../../src/agent/runner-gateway/runner-local-models.js";+import {+ createTestLocalComputerRegistry,+ type TestLocalComputerRegistry,+} from "../test-support/local-computer-registry.js";+import { createTestRunnerGateway } from "../test-support/runner-gateway.js";+import { runtimeDiagnostics } from "./runtime-diagnostics-fixture.js";+import {+ CURRENT_RUNNER_CAPABILITIES,+ currentRunnerIdentity,+} from "../test-support/runner-capabilities.js";++const connections: RunnerGatewayConnection[] = [];+afterEach(() => {+ for (const connection of connections.splice(0)) connection.disconnect();+});++const target = {+ computerId: "computer-local",+ tenantId: "tenant-1",+ ownerActorId: "actor-1",+} as const;++const snapshot = (toolVersion: string): LocalModelsSnapshot => ({+ available: true,+ observed_at: new Date().toISOString(),+ tool_version: toolVersion,+ pools: [+ {+ id: "gpu:0",+ kind: "gpu",+ gpu_index: 0,+ total_bytes: 24_000,+ used_bytes: 0,+ holders: [],+ },+ ],+ models: [+ {+ id: "qwen3-4b:Q4_K_M",+ name: "Qwen3 4B",+ description: "",+ quant: "Q4_K_M",+ context_tokens: 32_768,+ vision: false,+ download_bytes: 4_000,+ memory_bytes: 5_000,+ fit: "gpu",+ recommended: true,+ availability: { downloadable: true },+ pool: "gpu:0",+ state: "absent",+ },+ {+ id: "giant:Q8",+ name: "Giant",+ description: "",+ quant: "Q8",+ context_tokens: 8_192,+ vision: false,+ download_bytes: 90_000,+ memory_bytes: 90_000,+ fit: "none",+ recommended: false,+ availability: {+ downloadable: false,+ reason: {+ code: "MEMORY_INSUFFICIENT",+ need_bytes: 90_000,+ have_bytes: 24_000,+ },+ },+ state: "absent",+ },+ ],+});++const connect = async (registry?: TestLocalComputerRegistry) => {+ const computerRegistry = registry ?? createTestLocalComputerRegistry();+ computerRegistry.enroll({ ...target });+ const gateway = createTestRunnerGateway({+ heartbeatIntervalMs: 60_000,+ computerRegistry,+ });+ const sent: AgentToDaemonEnvelope[] = [];+ const close = vi.fn();+ const connection = await gateway.acceptConnection(+ {+ runnerId: target.computerId,+ credentialGeneration: 0,+ tenantOwners: [+ { tenantId: target.tenantId, ownerActorId: target.ownerActorId },+ ],+ },+ {+ type: "runner.hello",+ platform: "linux",+ protocol_version: "2",+ daemon_version: "dev",+ ...currentRunnerIdentity(),+ capabilities: [...CURRENT_RUNNER_CAPABILITIES],+ runner_id: target.computerId,+ display_name: "Studio",+ connection_nonce: "nonce-1",+ sent_at: new Date().toISOString(),+ runtimes: ["codex"],+ runtime_diagnostics: runtimeDiagnostics(),+ workspace_grants: [],+ agent_runners: [],+ active_operations: [],+ },+ {+ send: vi.fn(async (envelope: AgentToDaemonEnvelope) => {+ sent.push(envelope);+ }),+ close,+ },+ );+ connections.push(connection);+ const report = (revision: number, toolVersion = `v${revision}`) =>+ connection.receive({+ type: "runner.local_models",+ protocol_version: "2",+ runner_id: target.computerId,+ sent_at: new Date().toISOString(),+ revision,+ local_models: snapshot(toolVersion),+ });+ const command = async (): Promise<CapabilityLocalModelsExecute> => {+ await vi.waitFor(() => expect(sent.some(isLocalModelsCommand)).toBe(true));+ const value = [...sent].reverse().find(isLocalModelsCommand);+ if (!value) throw new Error("Missing local-models command");+ sent.splice(sent.indexOf(value), 1);+ return value;+ };+ return { gateway, connection, computerRegistry, report, command, close };+};++const isLocalModelsCommand = (+ frame: AgentToDaemonEnvelope,+): frame is CapabilityLocalModelsExecute =>+ frame.type === "execute" && frame.kind === "local_models";++const identityOf = (request: CapabilityLocalModelsExecute) => ({+ protocol_version: request.protocol_version,+ command_id: request.command_id,+ runner_id: request.runner_id,+ tenant_id: request.tenant_id,+ owner_actor_id: request.owner_actor_id,+ connection_epoch: request.connection_epoch,+ expires_at: request.expires_at,+});++const inSeconds = (seconds: number) =>+ new Date(Date.now() + seconds * 1_000).toISOString();++const versions = (registry: TestLocalComputerRegistry) =>+ registry+ .localModels(target.computerId)+ .map((recorded) => recorded.tool_version);++describe("Runner Gateway local models", () => {+ it("records each snapshot in TeamHub and drops a stale revision", async () => {+ const { computerRegistry, report } = await connect();+ await report(1);+ await vi.waitFor(() => expect(versions(computerRegistry)).toEqual(["v1"]));+ await report(1, "replayed");+ await report(3);+ await vi.waitFor(() =>+ expect(versions(computerRegistry)).toEqual(["v1", "v3"]),+ );+ expect(computerRegistry.localModels(target.computerId)[1]).toEqual(+ expect.objectContaining({+ models: [+ expect.objectContaining({ pool: "gpu:0" }),+ expect.not.objectContaining({ pool: expect.anything() }),+ ],+ }),+ );+ });++ it("keeps one snapshot in flight per Computer and sends only the newest after it", async () => {+ const registry = createTestLocalComputerRegistry();+ const released: Array<() => void> = [];+ const record = registry.recordLocalModels;+ registry.recordLocalModels = async (computerId, value) => {+ await new Promise<void>((resolve) => released.push(resolve));+ await record(computerId, value);+ };+ const { report } = await connect(registry);+ await report(1);+ await report(2);+ await report(3);+ await vi.waitFor(() => expect(released).toHaveLength(1));+ released.shift()!();+ await vi.waitFor(() => expect(released).toHaveLength(1));+ released.shift()!();+ await vi.waitFor(() => expect(versions(registry)).toEqual(["v1", "v3"]));+ });++ it("keeps the connection when TeamHub refuses a snapshot", async () => {+ const registry = createTestLocalComputerRegistry();+ const record = registry.recordLocalModels;+ let failures = 1;+ registry.recordLocalModels = async (computerId, value) => {+ if (failures-- > 0) throw new Error("TeamHub is unavailable");+ await record(computerId, value);+ };+ const { gateway, report, close } = await connect(registry);+ await report(1);+ await report(2);+ await vi.waitFor(() => expect(versions(registry)).toEqual(["v2"]));+ expect(close).not.toHaveBeenCalled();+ expect(gateway.isLocalComputerExecutionReady(target.computerId)).toBe(true);+ });++ it("retries the newest snapshot until TeamHub stores it", async () => {+ const registry = createTestLocalComputerRegistry();+ const record = registry.recordLocalModels;+ let failures = 2;+ const attempt = vi.fn(+ async (computerId: string, value: LocalModelsSnapshot) => {+ if (failures-- > 0) throw new Error("TeamHub is unavailable");+ await record(computerId, value);+ },+ );+ registry.recordLocalModels = attempt;+ const { report, connection } = await connect(registry);+ vi.useFakeTimers();+ try {+ // The Computer's last report fails, and no newer one follows.+ await report(1);+ await vi.advanceTimersByTimeAsync(60_000);+ expect(versions(registry)).toEqual(["v1"]);+ expect(attempt).toHaveBeenCalledTimes(3);+ // Stored once: nothing is written again.+ await vi.advanceTimersByTimeAsync(60_000);+ expect(attempt).toHaveBeenCalledTimes(3);+ } finally {+ connection.disconnect();+ vi.useRealTimers();+ }+ });++ it("retries with the snapshot that replaced a failed one", async () => {+ const registry = createTestLocalComputerRegistry();+ const record = registry.recordLocalModels;+ let failures = 1;+ registry.recordLocalModels = async (computerId, value) => {+ if (failures-- > 0) throw new Error("TeamHub is unavailable");+ await record(computerId, value);+ };+ const { report, connection } = await connect(registry);+ vi.useFakeTimers();+ try {+ await report(1);+ await report(2);+ await vi.advanceTimersByTimeAsync(60_000);+ expect(versions(registry)).toEqual(["v2"]);+ } finally {+ connection.disconnect();+ vi.useRealTimers();+ }+ });++ it("stops retrying a snapshot TeamHub will never store", async () => {+ const registry = createTestLocalComputerRegistry();+ const attempt = vi.fn(async () => {+ throw new TeamHubRuntimeStateError(404, "Local Computer was not found");+ });+ registry.recordLocalModels = attempt;+ const { report, connection } = await connect(registry);+ vi.useFakeTimers();+ try {+ await report(1);+ await vi.advanceTimersByTimeAsync(600_000);+ expect(attempt).toHaveBeenCalledTimes(1);+ } finally {+ connection.disconnect();+ vi.useRealTimers();+ }+ });++ it("sends no action to a connection that never reported a library", async () => {+ const { gateway, connection } = await connect();+ await expect(+ gateway.actOnLocalModels({+ ...target,+ action: "download",+ modelId: "qwen3-4b:Q4_K_M",+ expiresAt: inSeconds(10),+ }),+ ).rejects.toBeInstanceOf(LocalComputerCapabilityError);+ await expect(+ gateway.actOnLocalModels({+ ...target,+ ownerActorId: "actor-other",+ action: "refresh",+ expiresAt: inSeconds(10),+ }),+ ).rejects.toBeInstanceOf(LocalComputerNotFoundError);+ connection.disconnect();+ await expect(+ gateway.actOnLocalModels({+ ...target,+ action: "refresh",+ expiresAt: inSeconds(10),+ }),+ ).rejects.toBeInstanceOf(LocalComputerOfflineError);+ });++ it("answers each action with the Computer's accept or refusal for that command", async () => {+ const { gateway, connection, report, command } = await connect();+ await report(1);+ const loading = gateway.actOnLocalModels({+ ...target,+ action: "load",+ modelId: "qwen3-4b:Q4_K_M",+ unloadFirst: ["gemma-3:Q4"],+ expiresAt: inSeconds(10),+ });+ const load = await command();+ expect(load).toMatchObject({+ action: "load",+ model_id: "qwen3-4b:Q4_K_M",+ unload_first: ["gemma-3:Q4"],+ tenant_id: target.tenantId,+ owner_actor_id: target.ownerActorId,+ });+ const downloading = gateway.actOnLocalModels({+ ...target,+ action: "download",+ modelId: "giant:Q8",+ expiresAt: inSeconds(10),+ });+ const download = await command();+ // Answers arrive out of order; each settles its own command.+ await connection.receive({+ type: "executed",+ kind: "local_models",+ outcome: "refused",+ ...identityOf(download),+ action: "download",+ model_id: "giant:Q8",+ refusal: {+ code: "MEMORY_INSUFFICIENT",+ need_bytes: 90_000,+ free_bytes: 24_000,+ },+ });+ await connection.receive({+ type: "executed",+ kind: "local_models",+ outcome: "accepted",+ ...identityOf(load),+ action: "load",+ model_id: "qwen3-4b:Q4_K_M",+ });+ await expect(loading).resolves.toEqual({ outcome: "accepted" });+ await expect(downloading).resolves.toEqual({+ outcome: "refused",+ refusal: {+ code: "MEMORY_INSUFFICIENT",+ need_bytes: 90_000,+ free_bytes: 24_000,+ },+ });+ });++ it("fails an unanswered action at its deadline and ignores the late answer", async () => {+ const { gateway, connection, report, command, close } = await connect();+ await report(1);+ const unloading = gateway.actOnLocalModels({+ ...target,+ action: "unload",+ modelId: "qwen3-4b:Q4_K_M",+ expiresAt: new Date(Date.now() + 50).toISOString(),+ });+ const request = await command();+ await expect(unloading).rejects.toBeInstanceOf(+ LocalModelsActionTimeoutError,+ );+ await connection.receive({+ type: "executed",+ kind: "local_models",+ outcome: "accepted",+ ...identityOf(request),+ action: "unload",+ model_id: "qwen3-4b:Q4_K_M",+ });+ expect(close).not.toHaveBeenCalled();+ });++ it("fails a waiting action when the Computer disconnects", async () => {+ const { gateway, connection, report, command } = await connect();+ await report(1);+ const removing = gateway.actOnLocalModels({+ ...target,+ action: "remove",+ modelId: "qwen3-4b:Q4_K_M",+ expiresAt: inSeconds(10),+ });+ await command();+ connection.disconnect();+ await expect(removing).rejects.toBeInstanceOf(LocalComputerOfflineError);+ });++ it("treats an answer naming another action as a protocol violation", async () => {+ const { gateway, connection, report, command, close } = await connect();+ await report(1);+ const cancelling = gateway.actOnLocalModels({+ ...target,+ action: "cancel",+ modelId: "qwen3-4b:Q4_K_M",+ expiresAt: inSeconds(10),+ });+ const request = await command();+ await expect(+ connection.receive({+ type: "executed",+ kind: "local_models",+ outcome: "accepted",+ ...identityOf(request),+ action: "remove",+ model_id: "qwen3-4b:Q4_K_M",+ }),+ ).rejects.toThrow(/identity mismatch/u);+ expect(close).toHaveBeenCalledWith(1002, "Runner protocol violation");+ await expect(cancelling).rejects.toBeInstanceOf(LocalComputerOfflineError);+ });+});diff --git a/apps/node-services/tests/agent/test-support/local-computer-registry.ts b/apps/node-services/tests/agent/test-support/local-computer-registry.tsindex bb757f41..1a7b62e9 100644--- a/apps/node-services/tests/agent/test-support/local-computer-registry.ts+++ b/apps/node-services/tests/agent/test-support/local-computer-registry.ts@@ -1,4 +1,7 @@-import type { RuntimeDiagnostics } from "@linger/wire-contracts/runner-gateway/types";+import type {+ LocalModelsSnapshot,+ RuntimeDiagnostics,+} from "@linger/wire-contracts/runner-gateway/types";import type { LocalRuntimeType } from "../../../src/agent/runner-gateway/local-computer-management.js";import {@@ -42,6 +45,8 @@ export interface TestLocalComputerRegistry extends LocalComputerRegistry {unplace(agentId: string): void;recorded(computerId: string): TestRecordedLocalComputer | undefined;list(owner: LocalComputerOwner): readonly TestRecordedLocalComputer[];+ /** Every model library snapshot recorded for the Computer, oldest first. */+ localModels(computerId: string): readonly LocalModelsSnapshot[];}const registries = new Map<string, TestLocalComputerRegistry>();@@ -63,6 +68,7 @@ export function createTestLocalComputerRegistry(string,{ computerId: string; placement: RunnerPlacement }>();+ const localModels = new Map<string, LocalModelsSnapshot[]>();const owns = (computer: TestRecordedLocalComputer,owner: LocalComputerOwner,@@ -143,6 +149,14 @@ export function createTestLocalComputerRegistry(if (touch.recommendedVersion)computer.recommendedVersion = touch.recommendedVersion;},+ async recordLocalModels(computerId, snapshot) {+ const recorded = localModels.get(computerId) ?? [];+ recorded.push(structuredClone(snapshot));+ localModels.set(computerId, recorded);+ },+ localModels(computerId) {+ return localModels.get(computerId) ?? [];+ },async remove({ computerId, ...owner }) {const computer = computers.get(computerId);if (!computer || !owns(computer, owner)) return "not-found";