Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): per-bot model selection + agent error surfacing
Gus01e731817558
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex e6077f2f4..4281187f7 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -194,7 +194,16 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaevent:| { kind: "cli_invocation"; payload: { subcommand: string } }| { kind: "tool_call"; payload: { name: string; target?: string } }- | { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } },+ | { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } }+ | {+ kind: "error";+ payload: {+ scope: "spawn" | "runtime" | "exit" | "handshake_timeout" | "model_switch" | "reset";+ code: string;+ message: string;+ model: string | null;+ };+ },context?: { sessionId?: string | null; launchId?: string | null }) => {void channelRef?.reportBotAuditEvent?.({diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.tsindex 7e3a8b02b..f54509a13 100644--- a/src/daemon/src/manager/agentRouter.test.ts+++ b/src/daemon/src/manager/agentRouter.test.ts@@ -29,6 +29,7 @@ function fakeManager(initialStatuses: Record<string, "idle" | "starting" | "runnconst registers: Array<{ agentId: string; sessionId?: string; launchId?: string }> = [];const forgets: string[] = [];const resets: Array<{ agentId: string; rewakePrompt: string; launchId: string }> = [];+ const switches: Array<{ agentId: string; rewakePrompt: string; launchId: string }> = [];const order: string[] = [];const statuses: Record<string, "idle" | "starting" | "running" | "stopping"> = { ...initialStatuses };const mgr = {@@ -48,6 +49,10 @@ function fakeManager(initialStatuses: Record<string, "idle" | "starting" | "runnresets.push({ agentId, rewakePrompt: opts.rewakePrompt, launchId: opts.launchId });order.push(`reset:${agentId}`);},+ async switchModel(agentId: string, opts: { launchId: string; rewakePrompt: string }) {+ switches.push({ agentId, rewakePrompt: opts.rewakePrompt, launchId: opts.launchId });+ order.push(`switch:${agentId}`);+ },stop() {},liveSessionReports: () => [],snapshot() {@@ -56,7 +61,7 @@ function fakeManager(initialStatuses: Record<string, "idle" | "starting" | "runnreturn { agents };},} as unknown as AgentProcessManager;- return { mgr, delivers, registers, statuses, forgets, resets, order };+ return { mgr, delivers, registers, statuses, forgets, resets, switches, order };}/** Fake channel capturing acks + the command handler the router registers. */@@ -178,12 +183,12 @@ describe("AgentRouter — agent:reset", () => {expect(router.buildReady().runningAgents).toContain("a1");});- it("a generic thrown error from resetSession is logged, doesn't crash, and does NOT add to running set", async () => {+ it("a generic thrown error from resetSession is logged, sends an error ack, doesn't crash, and does NOT add to running set", async () => {const mgr = {resetSession: async () => { throw new Error("boom"); },liveSessionReports: () => [],} as unknown as AgentProcessManager;- const { ch, fire } = fakeChannel();+ const { ch, wakeAcks, fire } = fakeChannel();const logger = stubLogger();const router = new AgentRouter({ manager: mgr, channel: ch, runtimeReport: [{ id: "mock" }], logger });await router.start();@@ -191,6 +196,8 @@ describe("AgentRouter — agent:reset", () => {await fire({ type: "agent:reset", agentId: "a1", config: CFG, launchId: "l1" });expect(router.buildReady().runningAgents).not.toContain("a1");expect(logger.calls.warn.some(([m]) => m === "agent:reset failed")).toBe(true);+ // The web gets a negative signal, not just a daemon log line.+ expect(wakeAcks).toContainEqual({ agentId: "a1", launchId: "l1", status: "error" });});it("UnknownRuntimeError from resetSession → forwards session.error{runtime_not_available}, running set untouched", async () => {@@ -220,6 +227,68 @@ describe("AgentRouter — agent:reset", () => {});});+describe("AgentRouter — agent:model_switch", () => {+ const CFG = {+ version: 1 as const,+ runtime: "mock",+ model: { kind: "named" as const, name: "opus" },+ mode: { kind: "default" as const },+ };++ it("calls onBeforeAgent BEFORE switchModel, with the pushed config, launchId, and the model-switch rewake prompt", async () => {+ const { mgr, switches, order } = fakeManager();+ const { ch, fire } = fakeChannel();+ const beforeCalls: string[] = [];+ const router = new AgentRouter({+ manager: mgr,+ channel: ch,+ runtimeReport: [{ id: "mock" }],+ onBeforeAgent: async (id) => { beforeCalls.push(id); order.push(`before:${id}`); },+ });+ await router.start();++ await fire({ type: "agent:model_switch", agentId: "a1", config: CFG, launchId: "l1" });++ expect(beforeCalls).toEqual(["a1"]);+ expect(switches).toHaveLength(1);+ expect(switches[0]).toMatchObject({ agentId: "a1", launchId: "l1" });+ expect(switches[0].rewakePrompt).toBe("You were just switched to a different model. Continue any unfinished work.");+ // Enroll gate: onBeforeAgent completes before switchModel fires.+ expect(order[0]).toBe("before:a1");+ expect(order[1]).toBe("switch:a1");+ expect(router.buildReady().runningAgents).toContain("a1");+ });++ it("UnknownRuntimeError → session.error{runtime_not_available}; generic error → warn, running set untouched", async () => {+ const throwing = new UnknownRuntimeError("gemini", ["claude", "codex"]);+ const mgrUnknown = {+ switchModel: async () => { throw throwing; },+ liveSessionReports: () => [],+ } as unknown as AgentProcessManager;+ const { ch, sessionErrors, fire } = fakeChannel();+ const router = new AgentRouter({ manager: mgrUnknown, channel: ch, runtimeReport: [{ id: "claude" }, { id: "codex" }] });+ await router.start();+ await fire({ type: "agent:model_switch", agentId: "a1", config: { ...CFG, runtime: "gemini" }, launchId: "l1" });+ expect(sessionErrors).toHaveLength(1);+ expect(sessionErrors[0]).toMatchObject({ type: "session.error", code: "runtime_not_available", agentId: "a1" });+ expect(router.buildReady().runningAgents).not.toContain("a1");++ const mgrGeneric = {+ switchModel: async () => { throw new Error("boom"); },+ liveSessionReports: () => [],+ } as unknown as AgentProcessManager;+ const { ch: ch2, wakeAcks: wakeAcks2, fire: fire2 } = fakeChannel();+ const logger = stubLogger();+ const router2 = new AgentRouter({ manager: mgrGeneric, channel: ch2, runtimeReport: [{ id: "mock" }], logger });+ await router2.start();+ await fire2({ type: "agent:model_switch", agentId: "a2", config: CFG, launchId: "l1" });+ expect(logger.calls.warn.some(([m]) => m === "agent:model_switch failed")).toBe(true);+ expect(router2.buildReady().runningAgents).not.toContain("a2");+ // The web gets a negative signal, not just a daemon log line.+ expect(wakeAcks2).toContainEqual({ agentId: "a2", launchId: "l1", status: "error" });+ });+});+describe("AgentRouter — unknown runtime → session.error", () => {it("catches UnknownRuntimeError from driverFor and forwards session.error{runtime_not_available}", async () => {// Manager whose register() re-throws whatever driverFor throws — mimicsdiff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.tsindex da8f8598e..9425cca15 100644--- a/src/daemon/src/manager/agentRouter.ts+++ b/src/daemon/src/manager/agentRouter.ts@@ -133,6 +133,14 @@ const REWAKE_PROMPT ="Read @todo.md, @memory.md, and your .context_timeline for anything unfinished, " +"then pull your inbox to catch up on unread messages before doing anything else.";+/**+ * Rewake prompt for `agent:model_switch`. Unlike `REWAKE_PROMPT`, the session+ * is PRESERVED — prior context survives — so this only tells the agent it was+ * relaunched on a different model and to continue whatever it was doing.+ */+const MODEL_SWITCH_REWAKE_PROMPT =+ "You were just switched to a different model. Continue any unfinished work.";+export class AgentRouter {private readonly running = new Set<string>();/**@@ -417,8 +425,72 @@ export class AgentRouter {});return;}+ // Non-runtime throw (enroll failure, spawn threw, …). Mirror the+ // wake arm: send an error ack so the web isn't left with only a+ // daemon log line and no negative signal.+ const code = classifyErrorCode(err);+ await this.opts.channel.reportWakeAck?.({+ agentId: cmd.agentId,+ launchId: cmd.launchId,+ status: "error",+ error: { code, message: err instanceof Error ? err.message : String(err) },+ });this.log.warn("agent:reset failed", {agentId: cmd.agentId,+ "error.code": code,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ break;+ case "agent:model_switch":+ this.log.info("agent:model_switch received", { agentId: cmd.agentId, launchId: cmd.launchId });+ try {+ // `onBeforeAgent` is the ENROLL step, not error handling — it is the+ // only writer of `enrolledKeys`. Without it, `doSpawn` →+ // `baseContextFor` throws `agent <id> not enrolled yet` for any bot+ // that hasn't woken since the daemon started, and the audit row ++ // "switched" toast would lie while the daemon never respawns. Must+ // run BEFORE switchModel, exactly as the agent:reset arm does.+ await this.opts.onBeforeAgent?.(cmd.agentId);+ await this.opts.manager.switchModel(cmd.agentId, {+ runtimeConfig: cmd.config,+ launchId: cmd.launchId,+ rewakePrompt: MODEL_SWITCH_REWAKE_PROMPT,+ });+ this.running.add(cmd.agentId);+ this.scheduleReadyFrameResend();+ this.log.info("agent:model_switch ok", { agentId: cmd.agentId });+ } catch (err) {+ if (err instanceof UnknownRuntimeError) {+ const frame: SessionErrorFrame = {+ type: "session.error",+ code: "runtime_not_available",+ agentId: cmd.agentId,+ payload: {+ requested: err.requested ?? null,+ available: err.available,+ },+ };+ await this.opts.channel.reportSessionError?.(frame);+ this.log.info("agent:model_switch error", {+ agentId: cmd.agentId,+ "error.code": "runtime_not_available",+ });+ return;+ }+ // Non-runtime throw (enroll failure, spawn threw, …). Mirror the+ // wake arm: send an error ack so the web isn't left with only a+ // daemon log line and no negative signal.+ const code = classifyErrorCode(err);+ await this.opts.channel.reportWakeAck?.({+ agentId: cmd.agentId,+ launchId: cmd.launchId,+ status: "error",+ error: { code, message: err instanceof Error ? err.message : String(err) },+ });+ this.log.warn("agent:model_switch failed", {+ agentId: cmd.agentId,+ "error.code": code,err: err instanceof Error ? err.message : String(err),});}diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.tsindex 2766c718e..163b09bd4 100644--- a/src/daemon/src/manager/managerRuntime.test.ts+++ b/src/daemon/src/manager/managerRuntime.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, vi } from "vitest";+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import {AgentProcessManager,truncateThinking,@@ -82,7 +82,7 @@ function fakeSession(): FakeSession {return s;}-function makeManager(opts: { logger?: Logger; tickIntervalMs?: number; idleTimeoutMs?: number; staleThresholdMs?: number; now?: () => number; onBotAuditEvent?: (agentId: string, event: unknown, context: { sessionId: string | null; launchId: string | null }) => void } = {}) {+function makeManager(opts: { logger?: Logger; tickIntervalMs?: number; idleTimeoutMs?: number; staleThresholdMs?: number; handshakeTimeoutMs?: number; now?: () => number; onBotAuditEvent?: (agentId: string, event: unknown, context: { sessionId: string | null; launchId: string | null }) => void } = {}) {const session = fakeSession();const factory: SessionFactory = () => session;const onRuntimeSpawnFailed = vi.fn();@@ -1028,6 +1028,146 @@ describe("AgentProcessManager — bot audit event emission", () => {});});+describe("AgentProcessManager — error audit emission", () => {+ it("emits an `error` row on a pre-handshake exit (spawn scope)", () => {+ const onBotAuditEvent = vi.fn();+ const { mgr, session } = makeManager({ onBotAuditEvent });+ mgr.deliver("a1", { seq: 1, text: "hello" });++ session.fire("exit");++ const errCalls = onBotAuditEvent.mock.calls.filter(+ ([, ev]) => (ev as { kind?: string })?.kind === "error",+ );+ expect(errCalls).toHaveLength(1);+ expect((errCalls[0]![1] as { payload: { scope: string; code: string } }).payload).toEqual(+ expect.objectContaining({ scope: "spawn", code: "pre_handshake_exit" }),+ );+ });++ it("emits an `error` row for a runtime `{kind:'error'}` event (runtime scope) and does NOT count it as progress", () => {+ const onBotAuditEvent = vi.fn();+ const { mgr, session } = makeManager({ onBotAuditEvent });+ mgr.deliver("a1", { seq: 1, text: "hello" });++ // Establish first so the error is session-level (runtime), not spawn.+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });+ session.fire("runtime_event", { kind: "error", message: "rate limited: 429 Too Many Requests" });++ const errCalls = onBotAuditEvent.mock.calls.filter(+ ([, ev]) => (ev as { kind?: string })?.kind === "error",+ );+ expect(errCalls).toHaveLength(1);+ const payload = (errCalls[0]![1] as { payload: { scope: string; code: string; message: string } }).payload;+ expect(payload.scope).toBe("runtime");+ expect(payload.code).toBe("runtime_error");+ expect(payload.message).toContain("429");+ });++ it("scrubs secrets out of an error message before it becomes an audit row", () => {+ const onBotAuditEvent = vi.fn();+ const { mgr, session } = makeManager({ onBotAuditEvent });+ mgr.deliver("a1", { seq: 1, text: "hello" });++ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });+ session.fire("runtime_event", { kind: "error", message: "auth failed with sk-ant-abc123DEF456 token" });++ const errCall = onBotAuditEvent.mock.calls.find(+ ([, ev]) => (ev as { kind?: string })?.kind === "error",+ );+ const message = (errCall![1] as { payload: { message: string } }).payload.message;+ expect(message).not.toContain("sk-ant-abc123DEF456");+ expect(message).toContain("[redacted-token]");+ });+});++describe("AgentProcessManager — handshake watchdog", () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it("terminates a session that never handshakes, emits an `error` row, and returns the FSM to idle", async () => {+ const onBotAuditEvent = vi.fn();+ const stopSpy = vi.fn();+ const session = fakeSession();+ session.stop = stopSpy as never;+ const onRuntimeSpawnFailed = vi.fn();+ const mgr = new AgentProcessManager({+ driverFor: () => fakeDriver("codex"),+ baseContextFor: () => ({+ workingDirectory: "/tmp",+ agentId: "a1",+ standingPrompt: "",+ config: {} as LaunchContext["config"],+ credentialProxy: {} as LaunchContext["credentialProxy"],+ }),+ sessionFactory: () => session,+ onRuntimeSpawnFailed,+ onBotAuditEvent: onBotAuditEvent as never,+ handshakeTimeoutMs: 1000,+ });+ mgr.register("a1");+ mgr.deliver("a1", { seq: 1, text: "hello" });++ // start() resolves → `spawned` dispatched → watchdog armed. Drain microtasks.+ session.startResolver?.();+ await Promise.resolve();+ await Promise.resolve();++ expect(mgr.snapshot().agents["a1"]?.status).toBe("running");++ // No handshake ever arrives; the deadline elapses.+ vi.advanceTimersByTime(1000);++ expect(onRuntimeSpawnFailed).toHaveBeenCalledWith("codex", "handshake_timeout");+ expect(stopSpy).toHaveBeenCalledTimes(1);+ const errCalls = onBotAuditEvent.mock.calls.filter(+ ([, ev]) => (ev as { kind?: string })?.kind === "error",+ );+ expect(errCalls).toHaveLength(1);+ expect((errCalls[0]![1] as { payload: { scope: string } }).payload.scope).toBe("handshake_timeout");+ // FSM returned to idle so a subsequent wake can retry.+ expect(mgr.snapshot().agents["a1"]?.status).toBe("idle");+ });++ it("does NOT fire when the handshake arrives before the deadline", async () => {+ const onBotAuditEvent = vi.fn();+ const stopSpy = vi.fn();+ const session = fakeSession();+ session.stop = stopSpy as never;+ const onRuntimeSpawnFailed = vi.fn();+ const mgr = new AgentProcessManager({+ driverFor: () => fakeDriver("codex"),+ baseContextFor: () => ({+ workingDirectory: "/tmp",+ agentId: "a1",+ standingPrompt: "",+ config: {} as LaunchContext["config"],+ credentialProxy: {} as LaunchContext["credentialProxy"],+ }),+ sessionFactory: () => session,+ onRuntimeSpawnFailed,+ onBotAuditEvent: onBotAuditEvent as never,+ handshakeTimeoutMs: 1000,+ });+ mgr.register("a1");+ mgr.deliver("a1", { seq: 1, text: "hello" });+ session.startResolver?.();+ await Promise.resolve();+ await Promise.resolve();++ // Handshake lands well within the window.+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });+ vi.advanceTimersByTime(1000);++ expect(onRuntimeSpawnFailed).not.toHaveBeenCalled();+ expect(stopSpy).not.toHaveBeenCalled();+ const errCalls = onBotAuditEvent.mock.calls.filter(+ ([, ev]) => (ev as { kind?: string })?.kind === "error",+ );+ expect(errCalls).toHaveLength(0);+ });+});+describe("canonicalToolName", () => {it("canonicalizes bash/shell to bash (case-insensitive)", () => {expect(canonicalToolName("Bash")).toBe("bash");diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex c64f3ad4c..d0c43a0ba 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -21,9 +21,10 @@ import {type AgentState,} from "./managerPolicy.js";import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";-import type { RuntimeConfig } from "../runtimeConfig.js";+import { resolveLaunchFieldsOrDefault, type RuntimeConfig } from "../runtimeConfig.js";import { createChildProcessRuntimeSession, type ChildProcessRuntimeSession } from "../runtime/runtimeSession.js";import { SESSION_STOP_GRACE_MS } from "../runtime/killTree.js";+import { scrubRuntimeErrorDiagnosticText } from "../runtime/errorDiagnostics.js";import { SdkManagedSession } from "../runtime/sdkManagedSession.js";import { DEFAULT_CLI_CONFIG } from "../drivers/cliTransport.js";import { createLogger, type Logger } from "../logger.js";@@ -86,6 +87,16 @@ export interface ManagerRuntimeOpts {staleThresholdMs?: number;/** Idle hibernation timeout (ms): stop a persistent process idle this long. */idleTimeoutMs?: number;+ /**+ * Handshake watchdog (ms): a spawned session that never emits its first+ * `runtime_event` (the handshake) within this window is treated as a+ * pre-establishment failure — the process is stopped, an `error` audit row+ * is emitted, and the FSM is returned to idle. Catches the case a bad model+ * makes the CLI HANG (no exit, no stderr, no stdout) — otherwise invisible+ * and unrecoverable (the `onTick` stall watchdog excludes an empty-inbox+ * gated agent). Defaults to 60s: a healthy cold start handshakes in <10s.+ */+ handshakeTimeoutMs?: number;tickIntervalMs?: number;/** Injectable clock (tests). Defaults to Date.now. */now?: () => number;@@ -119,7 +130,16 @@ export interface ManagerRuntimeOpts {agentId: string,event:| { kind: "tool_call"; payload: { name: string; target?: string } }- | { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } },+ | { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } }+ | {+ kind: "error";+ payload: {+ scope: "spawn" | "runtime" | "exit" | "handshake_timeout" | "model_switch" | "reset";+ code: string;+ message: string;+ model: string | null;+ };+ },context: { sessionId: string | null; launchId: string | null }) => void;/**@@ -213,6 +233,9 @@ const THINKING_MAX_BYTES = 4096;/** Max length of a runtime-stderr line the daemon logs verbatim (with an ellipsis when cut). */const STDERR_LOG_MAX_LEN = 2000;+/** Max length of an `error` audit row's message (schema caps at 2048; leave headroom). */+const AUDIT_ERROR_MESSAGE_MAX_LEN = 2000;+/*** Max UTF-16 code units for a tool_call's `target` field. The wire schema* caps `target` at 240 (see `AuditLogToolCallPayloadSchema`) and Zod's@@ -486,7 +509,21 @@ export class AgentProcessManager {*/private readonly activeSpawnState = new Map<string,- { hasEstablished: boolean; hasReportedSpawnFailure: boolean; suppressExitLog: boolean }+ {+ hasEstablished: boolean;+ hasReportedSpawnFailure: boolean;+ suppressExitLog: boolean;+ /** Handshake watchdog timer; cleared on first `runtime_event` or on exit. */+ handshakeTimer: ReturnType<typeof setTimeout> | null;+ /**+ * Set once this spawn's teardown has run (delete from maps + dispatch+ * `exit`). Guards against a SECOND teardown: the handshake watchdog tears+ * down eagerly, then the killed process emits its own late `exit` — that+ * late event must be a no-op, not a duplicate FSM `exit` that could clobber+ * a session a fresh wake spawned in between.+ */+ torndown: boolean;+ }>();private readonly opts: Required<Omit<@@ -531,6 +568,7 @@ export class AgentProcessManager {tickIntervalMs: 5_000,staleThresholdMs: 120_000,idleTimeoutMs: 300_000,+ handshakeTimeoutMs: 60_000,stampWakePromptTime: false,...opts,};@@ -664,6 +702,60 @@ export class AgentProcessManager {await this.stop(agentId);}+ /**+ * Owner-triggered model switch — `resetSession` MINUS the `forgetSession`+ * call, so the session and conversation history SURVIVE while the process is+ * relaunched on the new model. `register` installs the new `runtimeConfig`+ * into `runtimeConfigs`, which `doSpawn` reads at launch, so the respawn+ * carries the new model.+ *+ * Session preservation comes from two verified places — NOT from+ * `resumeSessions` (that map is only populated when `register` receives a+ * `launch.sessionId`, and `buildUnreadWakeCommand` never sets one, so it is+ * empty for community bots):+ * - Live path: skipping `forgetSession` means `reset_session` is never+ * dispatched, so `agent.sessionId` is still set at exit time and `onExit`+ * emits `{ type: "spawn", resumeSessionId: agent.sessionId }` — the+ * respawn resumes the same session.+ * - Durable path: no `reset_session` timeline barrier is written, so+ * `findResumableSession` still walks back to the last real session id+ * after a daemon restart.+ *+ * `markResetting`/`begin_reset` are reused as the SPAWN GATE, not as a+ * semantic "reset": they set `agent.resetting = true` so a wake landing+ * mid-switch queues to inbox instead of double-spawning. The field name reads+ * as reset-specific but the mechanism is identical; duplicating it would just+ * fork the same gate. `onExit` clears the flag unconditionally (including on+ * the spawn-failure path), so no new unlock path is needed.+ */+ async switchModel(+ agentId: string,+ opts: { runtimeConfig: RuntimeConfig; launchId: string; rewakePrompt: string },+ ): Promise<void> {+ this.register(agentId, { runtimeConfig: opts.runtimeConfig, launchId: opts.launchId });+ this.markResetting(agentId);+ const status = this.state.agents[agentId]?.status;+ if (status === "idle") {+ // Idle branch: same synchronous-throw recovery as `resetSession` — a+ // synchronous `doSpawn` throw would otherwise wedge the FSM at `starting`+ // with `resetting=true` forever. Dispatch `exit` so `onExit` clears the+ // gate and returns the agent to `idle`.+ try {+ this.deliver(agentId, { text: opts.rewakePrompt });+ } catch (err) {+ this.log.error("agent model switch idle-branch spawn threw synchronously", {+ agentId,+ err: err instanceof Error ? err.message : String(err),+ });+ this.dispatch({ type: "exit", agentId });+ throw err;+ }+ return;+ }+ this.enqueueRewake(agentId, { text: opts.rewakePrompt });+ await this.stop(agentId);+ }+start(): void {if (this.tickTimer) return;this.tickTimer = setInterval(() => this.dispatch({ type: "tick", nowMs: this.now() }), this.opts.tickIntervalMs);@@ -828,12 +920,19 @@ export class AgentProcessManager {private doSpawn(agentId: string, prompt: string, resumeSessionId: string | null): void {const driver = this.opts.driverFor(agentId, this.runtimeConfigs.get(agentId));- this.log.info("spawning agent", { agentId, runtime: driver.id });const base = this.opts.baseContextFor(agentId);// The server-pushed RuntimeConfig (from agent:wake) takes precedence over// any baseContextFor default; the resume sessionId likewise prefers the// manager's runtime-tracked id, then the server-pushed one, then the base.const runtimeConfig = this.runtimeConfigs.get(agentId) ?? base.config?.runtimeConfig;+ // Logged AFTER `runtimeConfig` is declared — reading it above would be a+ // `const` TDZ ReferenceError on every spawn. The resolved model is the QA+ // signal that a wake/reset/switch launched on the configured model.+ this.log.info("spawning agent", {+ agentId,+ runtime: driver.id,+ model: resolveLaunchFieldsOrDefault(runtimeConfig).model ?? "default",+ });const provider = runtimeConfig?.runtime ?? null;// Resume precedence: an explicit effect-supplied id → the manager's in-memory// tracked id → the server-pushed id → the durable timeline (latest finished@@ -905,13 +1004,25 @@ export class AgentProcessManager {// `terminate_stalled` from `applyEffect`) so the process's eventual// `exit` event doesn't ALSO log a redundant/contradictory// "session ended" line for the same termination.- const state = { hasEstablished: false, hasReportedSpawnFailure: false, suppressExitLog: false };+ const state = { hasEstablished: false, hasReportedSpawnFailure: false, suppressExitLog: false, handshakeTimer: null as ReturnType<typeof setTimeout> | null, torndown: false };this.activeSpawnState.set(agentId, state);- const reportSpawnFailure = (reason: string) => {+ const clearHandshakeTimer = () => {+ if (state.handshakeTimer) {+ clearTimeout(state.handshakeTimer);+ state.handshakeTimer = null;+ }+ };+ const reportSpawnFailure = (+ reason: string,+ opts?: { message?: string; scope?: "spawn" | "handshake_timeout" },+ ) => {if (state.hasEstablished || state.hasReportedSpawnFailure) return;state.hasReportedSpawnFailure = true;this.log.warn("spawn failed", { agentId, runtime: driver.id, reason });this.opts.onRuntimeSpawnFailed?.(driver.id, reason);+ // Surface to the owner: a spawn that never handshakes is otherwise+ // web-silent (the runtime-health chip is per-runtime, not per-bot).+ this.emitErrorAudit(agentId, opts?.scope ?? "spawn", reason, opts?.message ?? `Launch failed (${reason})`);};// Timeline entries are opened on the DATA plane (the agent's inbox pull),@@ -919,6 +1030,8 @@ export class AgentProcessManager {session.on("runtime_event", (e: unknown) => {if (!state.hasEstablished) {state.hasEstablished = true;+ // The handshake arrived — disarm the watchdog.+ clearHandshakeTimer();}// Fire on every runtime_event — the router's idempotence check on// `markRuntimeHealthy` (status already healthy + no lastError) collapses@@ -955,7 +1068,20 @@ export class AgentProcessManager {const code = err?.code ?? "spawn_error";reportSpawnFailure(String(code));});- session.on("exit", () => {+ session.on("exit", (...args: unknown[]) => {+ clearHandshakeTimer();+ // Teardown-once guard: the handshake watchdog may have already torn this+ // spawn down (reported the failure, killed the process, dispatched+ // `exit`) and a fresh wake may have spawned a NEW session since. The+ // killed process's own late `exit` event must not run teardown again —+ // that would dispatch a spurious FSM `exit` that could clobber the new+ // session. NB: `stop()` (reset/model_switch/idle) deletes from+ // `this.sessions` BEFORE this exit fires, so a `this.sessions` identity+ // check would wrongly bail on that legitimate exit — guard on our own+ // per-spawn flag instead.+ if (state.torndown) return;+ state.torndown = true;+ const info = args[0] as { code?: number | null; signal?: string | null; reason?: string } | undefined;// A session that exits without ever emitting `runtime_event` is// treated as a pre-handshake failure too — covers runtimes whose// wrapper binary exits non-zero without a Node-level `error` event.@@ -966,7 +1092,20 @@ export class AgentProcessManager {// already covered by the spawn-failed warning above. And only if this// termination wasn't already logged under a more specific reason (see// `suppressExitLog` above).- if (state.hasEstablished && !state.suppressExitLog) this.logSessionEnded(agentId, "exit");+ if (state.hasEstablished && !state.suppressExitLog) {+ this.logSessionEnded(agentId, "exit");+ // An established session that dies with a non-zero code / on a signal+ // and WASN'T a deliberate stop (`reason !== "requested"`) is an+ // unexpected mid-run crash — surface it. A clean `code === 0` exit or+ // a requested stop is normal turn/lifecycle end, no error row.+ const abnormal =+ info?.reason !== "requested" &&+ ((typeof info?.code === "number" && info.code !== 0) || !!info?.signal);+ if (abnormal) {+ const detail = info?.signal ? `signal ${info.signal}` : `code ${info?.code}`;+ this.emitErrorAudit(agentId, "exit", "abnormal_exit", `Session ended unexpectedly (${detail})`);+ }+ }// Flush any reasoning block that never saw a following event before exit.this.flushThinkingAudit(agentId);this.sessions.delete(agentId);@@ -993,6 +1132,33 @@ export class AgentProcessManager {// this now-dead spawn) until the daemon restarts.if (this.sessions.get(agentId) !== session) return;this.dispatch({ type: "spawned", agentId, nowMs: this.now() });+ // Arm the handshake watchdog. The FSM just went `running`+`turnActive`+ // optimistically (managerPolicy's `spawned`), but the process hasn't+ // proven itself — a bad model can make the CLI HANG with no exit, no+ // stderr, no stdout, so none of the subscribers above ever fire and+ // the `onTick` stall watchdog excludes an empty-inbox gated agent. If+ // no `runtime_event` arrives within the deadline, treat it as a+ // pre-handshake failure: stop the process and return the FSM to idle.+ if (state.hasEstablished || state.hasReportedSpawnFailure) return;+ state.handshakeTimer = setTimeout(() => {+ state.handshakeTimer = null;+ if (state.hasEstablished || state.hasReportedSpawnFailure) return;+ if (this.sessions.get(agentId) !== session) return;+ reportSpawnFailure("handshake_timeout", {+ scope: "handshake_timeout",+ message: `No response ${Math.round(this.opts.handshakeTimeoutMs / 1000)}s after launch — the runtime may be misconfigured (e.g. an invalid model).`,+ });+ void Promise.resolve(session.stop({ reason: "handshake_timeout", forceAfterMs: SESSION_STOP_GRACE_MS })).catch(() => {});+ // Drop tracking + return the FSM to idle so the next wake can retry;+ // don't wait on the `exit` event, which a wedged process may never+ // emit. Mark `torndown` so the killed process's eventual late `exit`+ // is a no-op instead of a second, session-clobbering teardown.+ state.torndown = true;+ if (this.sessions.get(agentId) === session) this.sessions.delete(agentId);+ this.liveSessions.delete(agentId);+ if (this.activeSpawnState.get(agentId) === state) this.activeSpawnState.delete(agentId);+ this.dispatch({ type: "exit", agentId });+ }, this.opts.handshakeTimeoutMs);}).catch((err: unknown) => {// Synchronous throws inside driver.spawn() (e.g. child_process.spawn@@ -1007,6 +1173,44 @@ export class AgentProcessManager {});}+ /**+ * The model in effect for an agent's current launch (`null` = runtime+ * default), for the `model` field of an `error` audit row — so the common+ * "switched to a bad model" failure names the culprit inline. Reads the same+ * resolved launch fields `doSpawn` logs, so it reflects what was actually+ * handed to the driver.+ */+ private currentModelFor(agentId: string): string | null {+ return resolveLaunchFieldsOrDefault(this.runtimeConfigs.get(agentId)).model ?? null;+ }++ /**+ * Emit an `error` audit row (launch/runtime failure the owner should see).+ * Reuses `errorDiagnostics` to classify + scrub the message. Best-effort and+ * never throws — an audit-emit failure must not cascade into the spawn/exit+ * path that called it. No-op when no audit sink is wired.+ */+ private emitErrorAudit(+ agentId: string,+ scope: "spawn" | "runtime" | "exit" | "handshake_timeout" | "model_switch" | "reset",+ code: string,+ rawMessage: string,+ ): void {+ if (!this.opts.onBotAuditEvent) return;+ const message = scrubRuntimeErrorDiagnosticText(rawMessage).slice(0, AUDIT_ERROR_MESSAGE_MAX_LEN);+ try {+ this.opts.onBotAuditEvent(agentId, {+ kind: "error",+ payload: { scope, code, message, model: this.currentModelFor(agentId) },+ }, {+ sessionId: this.liveSessions.get(agentId) ?? null,+ launchId: this.launchIds.get(agentId) ?? null,+ });+ } catch (err) {+ this.log.debug("audit emit failed (error)", { agentId, err: String(err) });+ }+ }+/*** Emit the buffered reasoning block as a single `thinking` audit row, then* clear the buffer. No-op when nothing accumulated (empty deltas were never@@ -1035,8 +1239,17 @@ export class AgentProcessManager {}private onRuntimeEvent(agentId: string, e: unknown, runtimeId: string): void {- const ev = e as { kind?: string; sessionId?: string; text?: string; name?: string; input?: unknown };+ const ev = e as { kind?: string; sessionId?: string; text?: string; name?: string; input?: unknown; message?: string };if (!ev?.kind) return;+ // A runtime-parsed `error` event (rate limit, auth failure, bad-model API+ // error, provider outage) is otherwise web-silent — the parser sees it,+ // the FSM shrugs, and the owner learns nothing. Emit an `error` audit row+ // so it lands in the bot's activity log. `hasEstablished` is already true+ // here (this fires from the `runtime_event` subscriber), so the scope is+ // `runtime`, not `spawn`.+ if (ev.kind === "error") {+ this.emitErrorAudit(agentId, "runtime", "runtime_error", ev.message ?? "Runtime error");+ }// Bot audit hook — thinking + non-Bash tool_call, no correlation.// Context carries the sessionId/launchId learned so far this launch so// ws-do can persist them alongside each row (the plan's Data model calls@@ -1095,8 +1308,10 @@ export class AgentProcessManager {// Progress for stall detection — but content-free heartbeats// (Claude `stream_event` / `status`, Codex raw response items) don't// count. They keep firing during a wedged compaction and would mask- // a real stall from `onTick`'s watchdog.- if (ev.kind !== "internal_progress") {+ // a real stall from `onTick`'s watchdog. An `error` event likewise isn't+ // progress: a runtime that errors then goes quiet must still trip the+ // stall watchdog rather than reset its progress clock on the way down.+ if (ev.kind !== "internal_progress" && ev.kind !== "error") {this.dispatch({ type: "progress", agentId, nowMs: this.now() });}// Forward every parsed event's kind for gated-steering phase trackingdiff --git a/src/daemon/src/manager/managerSwitchModel.test.ts b/src/daemon/src/manager/managerSwitchModel.test.tsnew file mode 100644index 000000000..75ca9f498--- /dev/null+++ b/src/daemon/src/manager/managerSwitchModel.test.ts@@ -0,0 +1,232 @@+import { describe, it, expect, vi } from "vitest";+import { AgentProcessManager, type ManagedSession, type SessionFactory, type TimelineRecorder } from "./managerRuntime.js";+import type { Driver, LaunchContext } from "../types.js";+import type { RuntimeConfig } from "../runtimeConfig.js";+import type { Logger } from "../logger.js";++function stubLogger(): Logger & { calls: Record<"debug" | "info" | "warn" | "error", Array<[string, unknown[]]>> } {+ const calls: Record<"debug" | "info" | "warn" | "error", Array<[string, unknown[]]>> = { debug: [], info: [], warn: [], error: [] };+ const logger = {+ calls,+ debug: (m: string, ...d: unknown[]) => calls.debug.push([m, d]),+ info: (m: string, ...d: unknown[]) => calls.info.push([m, d]),+ warn: (m: string, ...d: unknown[]) => calls.warn.push([m, d]),+ error: (m: string, ...d: unknown[]) => calls.error.push([m, d]),+ child: () => logger,+ };+ return logger;+}++function fakeDriver(id: string): Driver {+ return {+ id,+ lifecycle: { kind: "per_turn", start: "immediate", exit: "natural", inFlightWake: "spawn_new" } as never,+ session: { recovery: "resume_or_fresh" } as never,+ model: { detectedModelsVerifiedAs: "launchable", toLaunchSpec: () => ({ args: [] }) } as never,+ supportsStdinNotification: false,+ busyDeliveryMode: "none",+ probe: () => ({ status: "healthy" as const, version: "test" }),+ spawn: async () => ({ process: {} as never }),+ parseLine: () => [],+ encodeStdinMessage: () => null,+ buildSystemPrompt: () => "",+ } as unknown as Driver;+}++interface FakeSession extends ManagedSession {+ fire(evt: string, ...args: unknown[]): void;+}+function fakeSession(): FakeSession {+ const listeners = new Map<string, Array<(...a: unknown[]) => void>>();+ const s: FakeSession = {+ on(event, cb) {+ const arr = listeners.get(event) ?? [];+ arr.push(cb);+ listeners.set(event, arr);+ },+ start() { return Promise.resolve(); },+ send() {},+ stop() {},+ get currentSessionId() { return null; },+ fire(evt, ...args) { for (const cb of listeners.get(evt) ?? []) cb(...args); },+ };+ return s;+}++const NAMED_CFG: RuntimeConfig = {+ version: 1,+ runtime: "codex",+ model: { kind: "named", name: "opus" },+ mode: { kind: "default" },+};++function makeManager(opts: { logger?: Logger } = {}) {+ const spawns: Array<{ ctx: LaunchContext; prompt: string }> = [];+ let session = fakeSession();+ const sessions: FakeSession[] = [];+ const factory: SessionFactory = ({ ctx }: { ctx: LaunchContext }) => {+ spawns.push({ ctx, prompt: ctx.prompt });+ session = fakeSession();+ sessions.push(session);+ return session;+ };+ const mgr = new AgentProcessManager({+ driverFor: () => fakeDriver("codex"),+ baseContextFor: () => ({+ workingDirectory: "/tmp",+ agentId: "a1",+ standingPrompt: "",+ config: {} as LaunchContext["config"],+ credentialProxy: {} as LaunchContext["credentialProxy"],+ }),+ sessionFactory: factory,+ onRuntimeSpawnFailed: vi.fn(),+ onRuntimeSessionEstablished: vi.fn(),+ ...opts,+ });+ return { mgr, spawns, sessions, getSession: () => session };+}++const REWAKE = "You were just switched to a different model. Continue any unfinished work.";++describe("AgentProcessManager.switchModel", () => {+ it("on an idle agent: spawns immediately with the rewake prompt and the new config", () => {+ const { mgr, spawns } = makeManager();+ mgr.register("a1");+ void mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "l1", rewakePrompt: REWAKE });+ expect(spawns).toHaveLength(1);+ expect(spawns[0]!.prompt).toBe(REWAKE);+ expect(spawns[0]!.ctx.config.runtimeConfig).toEqual(NAMED_CFG);+ });++ it("registers a never-registered agent first, then spawns (no throw)", () => {+ const { mgr, spawns } = makeManager();+ // No prior register.+ expect(() =>+ mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "l1", rewakePrompt: REWAKE }),+ ).not.toThrow();+ expect(spawns).toHaveLength(1);+ });++ it("on a live agent: enqueues rewake, stops, and respawns exactly once on exit — carrying the prior sessionId as resumeSessionId (no reset_session)", async () => {+ const { mgr, spawns, getSession } = makeManager();+ mgr.register("a1");+ // First spawn + establish a session id.+ mgr.deliver("a1", { seq: 1, text: "hi" });+ expect(spawns).toHaveLength(1);+ getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-123" });++ // Switch while live. stop() → onExit drain → single respawn.+ await mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "l2", rewakePrompt: REWAKE });+ getSession().fire("exit");++ // Exactly two spawns total (initial + one respawn).+ expect(spawns).toHaveLength(2);+ // The respawn resumes the prior session id (preserved — switchModel never+ // dispatches reset_session) and carries the new model.+ expect(spawns[1]!.ctx.config.sessionId).toBe("sess-123");+ expect(spawns[1]!.ctx.config.runtimeConfig).toEqual(NAMED_CFG);+ // FSM sessionId is still set (not nulled by a reset_session).+ expect(mgr.snapshot().agents["a1"]!.sessionId).toBe("sess-123");+ });++ it("a wake landing between switchModel and the respawn queues to inbox (resetting gate), not a double-spawn", async () => {+ const { mgr, spawns, getSession } = makeManager();+ mgr.register("a1");+ mgr.deliver("a1", { seq: 1, text: "hi" });+ getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-1" });+ expect(spawns).toHaveLength(1);++ await mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "l2", rewakePrompt: REWAKE });+ // A real unread wake lands mid-switch — must NOT spawn a second process.+ mgr.deliver("a1", { seq: 2, text: "new unread" });+ expect(spawns).toHaveLength(1);+ // The exit drain produces exactly one respawn for the queued rewake + unread.+ getSession().fire("exit");+ expect(spawns).toHaveLength(2);+ });++ it("idle-branch synchronous spawn throw dispatches exit and clears the resetting gate", () => {+ const logger = stubLogger();+ let firstSpawn = true;+ const factory: SessionFactory = () => {+ if (firstSpawn) {+ firstSpawn = false;+ throw new Error("spawn boom");+ }+ return fakeSession();+ };+ const mgr = new AgentProcessManager({+ driverFor: () => fakeDriver("codex"),+ baseContextFor: () => ({+ workingDirectory: "/tmp",+ agentId: "a1",+ standingPrompt: "",+ config: {} as LaunchContext["config"],+ credentialProxy: {} as LaunchContext["credentialProxy"],+ }),+ sessionFactory: factory,+ onRuntimeSpawnFailed: vi.fn(),+ onRuntimeSessionEstablished: vi.fn(),+ logger,+ });+ mgr.register("a1");+ expect(() =>+ mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "l1", rewakePrompt: REWAKE }),+ ).rejects.toThrow(/spawn boom/);+ // The gate must have cleared (exit dispatched) — a subsequent wake spawns.+ expect(mgr.snapshot().agents["a1"]!.status).toBe("idle");+ });++ it("doSpawn's 'spawning agent' log includes the resolved model (named → 'opus')", () => {+ const logger = stubLogger();+ const { mgr } = makeManager({ logger });+ mgr.register("a1", { runtimeConfig: NAMED_CFG });+ mgr.deliver("a1", { seq: 1, text: "hi" });+ const spawnLog = logger.calls.info.find(([m]) => m === "spawning agent");+ expect(spawnLog).toBeTruthy();+ expect((spawnLog![1][0] as { model?: string }).model).toBe("opus");+ });++ it("doSpawn logs model 'default' when the config has no model", () => {+ const logger = stubLogger();+ const { mgr } = makeManager({ logger });+ mgr.register("a1"); // no runtimeConfig+ mgr.deliver("a1", { seq: 1, text: "hi" });+ const spawnLog = logger.calls.info.find(([m]) => m === "spawning agent");+ expect((spawnLog![1][0] as { model?: string }).model).toBe("default");+ });++ it("writes NO timeline reset_session barrier — forgetSession is never called, so resume still resolves", async () => {+ const timelineCalls: string[] = [];+ const timeline: TimelineRecorder = {+ setSession: (a, s) => timelineCalls.push(`session:${a}:${s}`),+ appendResponseToLatest: () => {},+ resumeSessionId: () => "resumable-sess",+ forgetSession: (a) => timelineCalls.push(`forget:${a}`),+ };+ let session = fakeSession();+ const factory: SessionFactory = () => (session = fakeSession());+ const mgr = new AgentProcessManager({+ driverFor: () => fakeDriver("codex"),+ baseContextFor: () => ({+ workingDirectory: "/tmp",+ agentId: "a1",+ standingPrompt: "",+ config: {} as LaunchContext["config"],+ credentialProxy: {} as LaunchContext["credentialProxy"],+ }),+ sessionFactory: factory,+ onRuntimeSpawnFailed: vi.fn(),+ onRuntimeSessionEstablished: vi.fn(),+ timeline,+ });+ mgr.register("a1");+ mgr.deliver("a1", { seq: 1, text: "hi" });+ session.fire("runtime_event", { kind: "session_init", sessionId: "sess-live" });+ await mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "l2", rewakePrompt: REWAKE });+ session.fire("exit");+ // forgetSession — the writer of the reset_session barrier — must never run.+ expect(timelineCalls.some((c) => c.startsWith("forget:"))).toBe(false);+ });+});diff --git a/src/daemon/src/runtimeConfig.test.ts b/src/daemon/src/runtimeConfig.test.tsnew file mode 100644index 000000000..1adb7b168--- /dev/null+++ b/src/daemon/src/runtimeConfig.test.ts@@ -0,0 +1,46 @@+import { describe, it, expect } from "vitest";+import { resolveLaunchFields } from "./runtimeConfig";+import { makeRuntimeConfig } from "./runtimeConfig";+import { buildAntigravityArgs } from "./drivers/antigravity";+import type { LaunchContext } from "./types";++describe("resolveLaunchFields — model id resolution across runtimes", () => {+ for (const runtime of ["claude", "codex", "gemini", "kimi"]) {+ it(`${runtime}: {kind:"named",name:"opus"} → f.model === "opus"`, () => {+ const f = resolveLaunchFields(makeRuntimeConfig({ runtime, model: { kind: "named", name: "opus" } }));+ expect(f.model).toBe("opus");+ });+ }++ it("claude: a custom model additionally sets ANTHROPIC_CUSTOM_MODEL_OPTION", () => {+ const f = resolveLaunchFields(makeRuntimeConfig({ runtime: "claude", model: { kind: "custom", name: "my-ft" } }));+ expect(f.model).toBe("my-ft");+ expect(f.providerEnv.ANTHROPIC_CUSTOM_MODEL_OPTION).toBe("my-ft");+ });++ it("codex: a custom model does NOT set the claude-specific env", () => {+ const f = resolveLaunchFields(makeRuntimeConfig({ runtime: "codex", model: { kind: "custom", name: "my-ft" } }));+ expect(f.model).toBe("my-ft");+ expect(f.providerEnv.ANTHROPIC_CUSTOM_MODEL_OPTION).toBeUndefined();+ });++ it("default model → f.model is undefined", () => {+ const f = resolveLaunchFields(makeRuntimeConfig({ runtime: "gemini" }));+ expect(f.model).toBeUndefined();+ });+});++describe("antigravity — discards the model at launch", () => {+ it("buildAntigravityArgs emits no model arg even when a model is set", () => {+ const ctx = {+ workingDirectory: "/tmp",+ agentId: "a1",+ standingPrompt: "",+ prompt: "hi",+ config: { runtimeConfig: makeRuntimeConfig({ runtime: "antigravity", model: { kind: "named", name: "opus" } }) },+ } as unknown as LaunchContext;+ const args = buildAntigravityArgs(ctx);+ expect(args).not.toContain("--model");+ expect(args.join(" ")).not.toContain("opus");+ });+});diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 2416885c9..bb2ddbf20 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -544,6 +544,17 @@ export type HostCommand =* synthetic rewake — see `AgentProcessManager.resetSession`.*/| { type: "agent:reset"; agentId: AgentId; config: RuntimeConfig; launchId: string }+ /**+ * Owner-triggered model switch. The twin of `agent:reset` — same+ * stop-and-immediate-rewake orchestration and boundary conditions — but it+ * PRESERVES the session (no `reset_session` row, no timeline barrier), so the+ * agent picks up whatever it was doing on the new model. `config` already+ * carries the new model (see `RuntimeConfig.model`). This is an EXPEDITE, not+ * the record: D1 remains authoritative and every subsequent `agent:wake`+ * reads the model fresh, so a lost frame merely means the bot is late to the+ * new model, never wrong about it. See `AgentProcessManager.switchModel`.+ */+ | { type: "agent:model_switch"; agentId: AgentId; config: RuntimeConfig; launchId: string }// ─── Bot lifecycle events (server → daemon) ────────────────────────────// Colon-namespaced to match the agent:* naming convention. Delivered to// the specific machine's daemon connection via the WS DO. On the daemon,@@ -637,6 +648,15 @@ export type BotAuditEventPayload =senderHandle: string;reason: "unread" | "mention";};+ }+ | {+ kind: "error";+ payload: {+ scope: "spawn" | "runtime" | "exit" | "handshake_timeout" | "model_switch" | "reset";+ code: string;+ message: string;+ model: string | null;+ };};export interface HostBotAuditEventFrame {diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex d7e4f84ae..18c9b89d8 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -460,7 +460,7 @@ export type CommunityBotAuditEvent = {type: "community:bot.audit_event"botId: stringid: string- kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset"+ kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "model_changed" | "error"payload: unknownsessionId?: string | nulllaunchId?: string | nulldiff --git a/src/shared/src/community/bot-model.test.ts b/src/shared/src/community/bot-model.test.tsnew file mode 100644index 000000000..eca6bc98f--- /dev/null+++ b/src/shared/src/community/bot-model.test.ts@@ -0,0 +1,75 @@+import { describe, it, expect } from "vitest";+import {+ resolveModelConfig,+ formatModelLabel,+ modelSelectState,+ modelNameFromSelect,+ MODEL_SELECT_DEFAULT,+ MODEL_SELECT_CUSTOM,+} from "./bot-model";++describe("resolveModelConfig", () => {+ it("treats null, empty, and whitespace-only as default", () => {+ for (const v of [null, "", " "]) {+ expect(resolveModelConfig("claude", v)).toEqual({ kind: "default" });+ }+ });++ it("resolves a catalog id to named and a non-catalog id to custom", () => {+ expect(resolveModelConfig("claude", "claude-opus-4-6")).toEqual({+ kind: "named",+ name: "claude-opus-4-6",+ });+ expect(resolveModelConfig("claude", "my-ft")).toEqual({ kind: "custom", name: "my-ft" });+ // Empty catalog ⇒ always custom.+ expect(resolveModelConfig("gemini", "anything")).toEqual({ kind: "custom", name: "anything" });+ // Null runtime ⇒ fallback empty catalog ⇒ custom.+ expect(resolveModelConfig(null, "x")).toEqual({ kind: "custom", name: "x" });+ });++ it("a model added to the catalog later resolves custom → named with no stored change (derive-at-read)", () => {+ // Same stored string; membership decides the kind. Simulate a not-yet-catalogued+ // id (custom) vs a catalogued id (named) without mutating storage.+ expect(resolveModelConfig("codex", "gpt-6-future")).toEqual({ kind: "custom", name: "gpt-6-future" });+ expect(resolveModelConfig("codex", "gpt-5.4")).toEqual({ kind: "named", name: "gpt-5.4" });+ });+});++describe("formatModelLabel", () => {+ it("strips exactly one runtime- prefix", () => {+ expect(formatModelLabel("claude", "claude-opus-4-6")).toBe("opus-4-6");+ });+ it("leaves a non-prefixed id unchanged", () => {+ expect(formatModelLabel("codex", "gpt-5.4")).toBe("gpt-5.4");+ });+ it("returns null for a default (null) model", () => {+ expect(formatModelLabel("claude", null)).toBeNull();+ expect(formatModelLabel(null, null)).toBeNull();+ });+ it("never empties a name equal to the bare runtime", () => {+ expect(formatModelLabel("claude", "claude")).toBe("claude");+ });+});++describe("modelSelectState / modelNameFromSelect round-trip", () => {+ it("round-trips default", () => {+ const s = modelSelectState("claude", null);+ expect(s).toEqual({ selectValue: MODEL_SELECT_DEFAULT, customName: "" });+ expect(modelNameFromSelect(s.selectValue, s.customName)).toBeNull();+ });+ it("round-trips a catalog id", () => {+ const s = modelSelectState("claude", "claude-opus-4-6");+ expect(s).toEqual({ selectValue: "claude-opus-4-6", customName: "" });+ expect(modelNameFromSelect(s.selectValue, s.customName)).toBe("claude-opus-4-6");+ });+ it("round-trips a custom name", () => {+ const s = modelSelectState("claude", "my-ft");+ expect(s).toEqual({ selectValue: MODEL_SELECT_CUSTOM, customName: "my-ft" });+ expect(modelNameFromSelect(s.selectValue, s.customName)).toBe("my-ft");+ });+ it("maps a cleared select (null) and an empty custom to null", () => {+ expect(modelNameFromSelect(null, "ignored")).toBeNull();+ expect(modelNameFromSelect(MODEL_SELECT_CUSTOM, "")).toBeNull();+ expect(modelNameFromSelect(MODEL_SELECT_CUSTOM, " ")).toBeNull();+ });+});diff --git a/src/shared/src/community/bot-model.ts b/src/shared/src/community/bot-model.tsnew file mode 100644index 000000000..05457c2d6--- /dev/null+++ b/src/shared/src/community/bot-model.ts@@ -0,0 +1,101 @@+/**+ * The single owner of every model-name ↔ `ModelConfig` ↔ Select translation.+ *+ * Storage (`community_bot_binding.model_name`), the wire request body, and the+ * UI all speak `string | null`. `ModelConfig` (the structured shape the daemon+ * consumes) is constructed in exactly ONE place — `resolveModelConfig` — so the+ * two wake sites, two write routes, and the picker cannot drift on how a stored+ * name maps to `{ kind }`.+ *+ * The `kind` (`default` / `named` / `custom`) is DERIVED from catalog+ * membership at read time, never stored: a value in the runtime's catalog is+ * `named`, anything else is `custom`, `null`/empty is `default`. Deriving at+ * read time always reflects the CURRENT catalog — a model entering our catalog+ * means it's first-party and should shed the custom-model env var — which a+ * persisted kind could not do.+ */++import type { ModelConfig } from "../runtime-config";+import { getRuntimeModelCatalog } from "../constants/runtime-models";++/** Select sentinel for "Default (the runtime's own default)". */+export const MODEL_SELECT_DEFAULT = "__default__";+/** Select sentinel for "Custom…" (reveals a free-text input). */+export const MODEL_SELECT_CUSTOM = "__custom__";++/**+ * The ONLY place a `ModelConfig` is constructed from stored model-name state+ * (outside `makeRuntimeConfig`'s own default). `null`, `""`, and+ * whitespace-only all mean the runtime's default. A catalog-member id resolves+ * to `named`; anything else to `custom`.+ */+export function resolveModelConfig(+ runtime: string | null,+ modelName: string | null+): ModelConfig {+ const name = (modelName ?? "").trim();+ if (name.length === 0) return { kind: "default" };+ const inCatalog = getRuntimeModelCatalog(runtime).models.includes(name);+ return inCatalog ? { kind: "named", name } : { kind: "custom", name };+}++/**+ * Card label. `null` when the model is default (the card renders no segment).+ *+ * Display rule: the stored value is always the full launchable id; strip+ * exactly ONE leading `` `${runtime}-` `` prefix when present, and nothing+ * else. A name equal to the bare runtime is returned unchanged (never emptied).+ * ("claude", "claude-opus-4-6") → "opus-4-6"+ * ("codex", "gpt-5.4") → "gpt-5.4"+ * ("claude", "claude") → "claude"+ * (*, null) → null+ */+export function formatModelLabel(+ runtime: string | null,+ modelName: string | null+): string | null {+ const name = (modelName ?? "").trim();+ if (name.length === 0) return null;+ if (runtime) {+ const prefix = `${runtime}-`;+ if (name.startsWith(prefix) && name.length > prefix.length) {+ return name.slice(prefix.length);+ }+ }+ return name;+}++/**+ * Seed the picker: which Select value is active, plus the text to prefill the+ * custom input with. A stored default → the Default sentinel and empty text; a+ * catalog id → that id as the Select value; anything else → the Custom sentinel+ * with the stored name in the text field.+ */+export function modelSelectState(+ runtime: string | null,+ modelName: string | null+): { selectValue: string; customName: string } {+ const name = (modelName ?? "").trim();+ if (name.length === 0) return { selectValue: MODEL_SELECT_DEFAULT, customName: "" };+ const inCatalog = getRuntimeModelCatalog(runtime).models.includes(name);+ if (inCatalog) return { selectValue: name, customName: "" };+ return { selectValue: MODEL_SELECT_CUSTOM, customName: name };+}++/**+ * Read the picker back out into a stored model-name. The Default sentinel and a+ * cleared Select (Base UI can emit `null`) both map to `null` ⇒ default. The+ * Custom sentinel maps to the trimmed custom text (empty ⇒ `null`). Any other+ * value is a catalog id, returned verbatim.+ */+export function modelNameFromSelect(+ selectValue: string | null,+ customName: string+): string | null {+ if (selectValue === null || selectValue === MODEL_SELECT_DEFAULT) return null;+ if (selectValue === MODEL_SELECT_CUSTOM) {+ const trimmed = customName.trim();+ return trimmed.length === 0 ? null : trimmed;+ }+ return selectValue;+}diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.tsindex 886eea81a..458aa1ccc 100644--- a/src/shared/src/community/wake-dispatch.ts+++ b/src/shared/src/community/wake-dispatch.ts@@ -1,6 +1,7 @@import { nanoid } from "nanoid";import type { HostCommand, UnreadNotice } from "../community-cli-contract";import { makeRuntimeConfig } from "../runtime-config";+import { resolveModelConfig } from "./bot-model";import { formatHandle } from "../lib/discriminator";import * as message from "../db/queries/community/message";import * as bot from "../db/queries/community/bot";@@ -168,6 +169,7 @@ export async function buildUnreadWakeCommand(};const config = makeRuntimeConfig({runtime: botCtx.runtime,+ model: resolveModelConfig(botCtx.runtime, botCtx.modelName),agentName: botCtx.name,agentHandle: `@${formatHandle(botCtx.name, botCtx.discriminator)}`,});diff --git a/src/shared/src/constants/runtime-models.test.ts b/src/shared/src/constants/runtime-models.test.tsnew file mode 100644index 000000000..4e21a9694--- /dev/null+++ b/src/shared/src/constants/runtime-models.test.ts@@ -0,0 +1,45 @@+import { describe, it, expect } from "vitest";+import {+ RUNTIME_MODEL_CATALOG,+ getRuntimeModelCatalog,+ runtimeSupportsModel,+} from "./runtime-models";++const SEEDED_RUNTIMES = [+ "claude",+ "codex",+ "gemini",+ "kimi",+ "copilot",+ "cursor",+ "opencode",+ "pi",+ "antigravity",+];++describe("getRuntimeModelCatalog", () => {+ it("returns the seeded entry for each of the 9 runtime ids", () => {+ for (const id of SEEDED_RUNTIMES) {+ expect(getRuntimeModelCatalog(id)).toBe(RUNTIME_MODEL_CATALOG[id]);+ }+ expect(getRuntimeModelCatalog("claude").models).toContain("claude-opus-4-6");+ expect(getRuntimeModelCatalog("codex").models).toContain("gpt-5.4");+ expect(getRuntimeModelCatalog("gemini").models).toEqual([]);+ });++ it("falls back to {supportsModel:true, models:[]} for an unknown id and null", () => {+ expect(getRuntimeModelCatalog("does-not-exist")).toEqual({ supportsModel: true, models: [] });+ expect(getRuntimeModelCatalog(null)).toEqual({ supportsModel: true, models: [] });+ });+});++describe("runtimeSupportsModel", () => {+ it("is false only for antigravity", () => {+ expect(runtimeSupportsModel("antigravity")).toBe(false);+ for (const id of SEEDED_RUNTIMES.filter((r) => r !== "antigravity")) {+ expect(runtimeSupportsModel(id)).toBe(true);+ }+ expect(runtimeSupportsModel(null)).toBe(true);+ expect(runtimeSupportsModel("unknown-runtime")).toBe(true);+ });+});diff --git a/src/shared/src/constants/runtime-models.ts b/src/shared/src/constants/runtime-models.tsnew file mode 100644index 000000000..4abefa37e--- /dev/null+++ b/src/shared/src/constants/runtime-models.ts@@ -0,0 +1,66 @@+/**+ * Runtime model catalog — a static, runtime-keyed suggestion list for the+ * per-bot model picker. This is the community-bot analogue of the legacy,+ * provider-keyed `RUNTIME_MODEL_OPTIONS` env var (wired only to `/w` agent+ * forms); it is keyed by RUNTIME id instead, seeded from what each daemon+ * driver actually does at launch today.+ *+ * The catalog SUGGESTS; it does not GATE. `named` vs `custom` is derived from+ * membership at read time (see `resolveModelConfig` in+ * `community/bot-model.ts`) — a value in `models` resolves to `named`,+ * anything else to `custom`. This preserves the distinction the daemon's+ * `resolveLaunchFields` needs (a `custom` model on `claude` additionally sets+ * `ANTHROPIC_CUSTOM_MODEL_OPTION`) without hard-rejecting a model the vendor+ * shipped after our last deploy — and, unlike a persisted kind, it stays+ * correct when the catalog grows.+ */++export interface RuntimeModelCatalogEntry {+ /** false ⇒ the driver ignores the model at launch; hide the field. */+ readonly supportsModel: boolean;+ /** Known-good ids for the picker. Empty ⇒ Default + free text only. */+ readonly models: readonly string[];+}++/**+ * Seeded from what each driver does today. `claude`/`codex` mirror the ids+ * already in `RUNTIME_MODEL_OPTIONS`; the runtimes that accept a model but+ * have no curated list get `{ supportsModel: true, models: [] }` (Default ++ * free text); `antigravity` alone is `supportsModel: false` — its driver+ * discards the model at launch, so offering the field would be a lie.+ */+export const RUNTIME_MODEL_CATALOG: Record<string, RuntimeModelCatalogEntry> = {+ claude: {+ supportsModel: true,+ models: ["claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"],+ },+ codex: {+ supportsModel: true,+ models: ["gpt-5.4", "gpt-5.3-codex"],+ },+ gemini: { supportsModel: true, models: [] },+ kimi: { supportsModel: true, models: [] },+ copilot: { supportsModel: true, models: [] },+ cursor: { supportsModel: true, models: [] },+ opencode: { supportsModel: true, models: [] },+ pi: { supportsModel: true, models: [] },+ antigravity: { supportsModel: false, models: [] },+};++/** Fallback for unknown/`null` runtime ids — a usable free-text field. */+const FALLBACK_ENTRY: RuntimeModelCatalogEntry = { supportsModel: true, models: [] };++/**+ * Catalog entry for a runtime id. Unknown or `null` runtimes fall back to+ * `{ supportsModel: true, models: [] }` so a runtime added to the daemon+ * before the catalog still gets a usable free-text field.+ */+export function getRuntimeModelCatalog(runtime: string | null): RuntimeModelCatalogEntry {+ if (runtime === null) return FALLBACK_ENTRY;+ return RUNTIME_MODEL_CATALOG[runtime] ?? FALLBACK_ENTRY;+}++/** Whether a runtime's driver honors a launch model. `null` ⇒ allow (unknown). */+export function runtimeSupportsModel(runtime: string | null): boolean {+ return getRuntimeModelCatalog(runtime).supportsModel;+}diff --git a/src/shared/src/db/community-machine-schema.ts b/src/shared/src/db/community-machine-schema.tsindex de6926feb..aa3403df3 100644--- a/src/shared/src/db/community-machine-schema.ts+++ b/src/shared/src/db/community-machine-schema.ts@@ -123,6 +123,11 @@ export const communityBotBinding = sqliteTable(.notNull().references(() => communityMachine.id, { onDelete: "restrict" }),runtime: text("runtime").notNull(),+ // Full launchable model id (e.g. "claude-opus-4-6"), or NULL for the+ // runtime's default. Kind is derived from the catalog at read time, never+ // stored. Hand-maintained in lockstep with migration 0063 (no drizzle-kit+ // generate in this repo).+ modelName: text("model_name"),createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.tsindex 930837089..34594eb5f 100644--- a/src/shared/src/db/queries/community/bot-audit-log.ts+++ b/src/shared/src/db/queries/community/bot-audit-log.ts@@ -30,7 +30,7 @@ export type BotActivityEventInput = {botId: string;sessionId?: string | null;launchId?: string | null;- kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset";+ kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "model_changed" | "error";payload: string;};@@ -219,3 +219,58 @@ export async function insertBotAuditSessionReset(payload: JSON.stringify({}),});}++/**+ * Model-changed audit write — the owner switched a bot's LLM model in+ * `/c/me/bots`. Actor is the owner (owner-scoped by construction on the API+ * route). Payload carries the full stored ids (`null` = the runtime's+ * default). Written ONLY after the daemon confirmed delivery of the+ * `agent:model_switch` frame (see plan decision #7) — an undelivered switch+ * (offline bot, transport error) leaves D1 authoritative but writes no row.+ */+export async function insertBotAuditModelChanged(+ db: Database,+ data: { botId: string; actorId: string; from: string | null; to: string | null }+): Promise<{ id: string; createdAt: string } | null> {+ return insertBotActivityEventAndPrune(db, {+ botId: data.botId,+ sessionId: null,+ launchId: null,+ kind: "model_changed",+ payload: JSON.stringify({ from: data.from, to: data.to }),+ });+}++/**+ * Error audit write — a launch/runtime failure the owner should see (see+ * `AuditLogErrorPayloadSchema`). Unlike the other writers this is fed by the+ * DAEMON (via the `bot_audit_event` frame → ws-do), not the web API: a bot+ * that spawns with a bad model, hangs past the handshake deadline, or exits+ * abnormally gets a visible row instead of going silent. `sessionId`/+ * `launchId` are carried from the failing launch when known.+ */+export async function insertBotAuditError(+ db: Database,+ data: {+ botId: string;+ sessionId?: string | null;+ launchId?: string | null;+ scope: "spawn" | "runtime" | "exit" | "handshake_timeout" | "model_switch" | "reset";+ code: string;+ message: string;+ model: string | null;+ }+): Promise<{ id: string; createdAt: string } | null> {+ return insertBotActivityEventAndPrune(db, {+ botId: data.botId,+ sessionId: data.sessionId ?? null,+ launchId: data.launchId ?? null,+ kind: "error",+ payload: JSON.stringify({+ scope: data.scope,+ code: data.code,+ message: data.message,+ model: data.model,+ }),+ });+}diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex a9ecc5757..d017dd828 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -55,6 +55,7 @@ export type BotBinding = {userId: string;machineId: string;runtime: string;+ modelName: string | null;createdAt: string;};@@ -74,7 +75,7 @@ export class OwnerHasBotsError extends Error {export async function listBotsForOwner(db: Database,ownerId: string-): Promise<Array<BotRow & { machineId: string; runtime: string }>> {+): Promise<Array<BotRow & { machineId: string; runtime: string; modelName: string | null }>> {const rows = await db.select({id: user.id,@@ -87,6 +88,7 @@ export async function listBotsForOwner(description: communityUserProfile.aboutMe,machineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,+ modelName: communityBotBinding.modelName,}).from(user).innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))@@ -112,6 +114,7 @@ export async function listBotsForOwner(updatedAt: r.updatedAt,machineId: r.machineId,runtime: r.runtime,+ modelName: r.modelName ?? null,}));}@@ -123,7 +126,7 @@ export async function getBotOwnedBy(db: Database,botId: string,ownerId: string-): Promise<(BotRow & { machineId: string | null; runtime: string | null }) | null> {+): Promise<(BotRow & { machineId: string | null; runtime: string | null; modelName: string | null }) | null> {const rows = await db.select({id: user.id,@@ -136,6 +139,7 @@ export async function getBotOwnedBy(description: communityUserProfile.aboutMe,machineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,+ modelName: communityBotBinding.modelName,}).from(user).leftJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))@@ -165,6 +169,7 @@ export async function getBotOwnedBy(updatedAt: r.updatedAt,machineId: r.machineId ?? null,runtime: r.runtime ?? null,+ modelName: r.modelName ?? null,};}@@ -190,16 +195,19 @@ export async function countLiveBotsForOwner(export async function getBotBinding(db: Database,botId: string-): Promise<{ machineId: string; runtime: string } | null> {+): Promise<{ machineId: string; runtime: string; modelName: string | null } | null> {const rows = await db.select({machineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,+ modelName: communityBotBinding.modelName,}).from(communityBotBinding).where(eq(communityBotBinding.userId, botId)).limit(1);- return rows[0] ?? null;+ const r = rows[0];+ if (!r) return null;+ return { machineId: r.machineId, runtime: r.runtime, modelName: r.modelName ?? null };}/**@@ -299,6 +307,7 @@ export type BotWakeContext =discriminator: string;machineId: string;runtime: string;+ modelName: string | null;ownerUserId: string | null;};@@ -313,6 +322,7 @@ export async function getBotWakeContext(db: Database, botUserId: string): PromisownerUserId: user.ownerUserId,machineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,+ modelName: communityBotBinding.modelName,}).from(user).leftJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))@@ -329,6 +339,7 @@ export async function getBotWakeContext(db: Database, botUserId: string): Promisdiscriminator: r.discriminator,machineId: r.machineId,runtime: r.runtime,+ modelName: r.modelName ?? null,ownerUserId: r.ownerUserId,};}@@ -436,6 +447,7 @@ export type CreateBotInput = {machineId: string;runtime: string;image?: string | null;+ modelName?: string | null;};/**@@ -479,6 +491,7 @@ export async function createBot(userId: botId,machineId: data.machineId,runtime: data.runtime,+ modelName: data.modelName ?? null,createdAt: nowIso,});// Match updateBot's upsert semantics — reincarnation paths (nanoid collision@@ -585,6 +598,44 @@ export async function updateBot(};}+/**+ * Update a bot's stored model name. Owner-scoped in the WHERE clause via the+ * sanctioned `ownerScopedIds` subquery (see §Ownership scoping invariant) — a+ * cross-owner `botId` is a no-op, not a leak.+ *+ * Returns whether a binding row was actually written. `getBotOwnedBy` 404s a+ * missing/cross-owner bot before this runs, but a bot with NO binding row+ * (unbound / never paired) still passes that check while this UPDATE matches+ * zero rows — the caller must NOT report a model as saved in that case (it+ * wasn't). Detection uses `RETURNING` (reliable in D1, as `softDeleteBot`+ * relies on) rather than the driver-specific `meta.changes` that "can flip a+ * real success into a 404".+ */+export async function updateBotModel(+ db: Database,+ botId: string,+ ownerId: string,+ modelName: string | null+): Promise<boolean> {+ const ownerScopedIds = db+ .select({ id: user.id })+ .from(user)+ .where(+ and(+ eq(user.id, botId),+ eq(user.ownerUserId, ownerId),+ eq(user.isBot, true),+ isNull(user.deletedAt)+ )+ );+ const rows = await db+ .update(communityBotBinding)+ .set({ modelName })+ .where(inArray(communityBotBinding.userId, ownerScopedIds))+ .returning({ userId: communityBotBinding.userId });+ return rows.length > 0;+}+/*** Soft-delete a bot atomically:* 1. UPDATE `user` set deletedAt (scoped by ownerUserId + isBot).diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 59c65925a..6cb2c42d6 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -283,6 +283,9 @@ export {AuditLogToolCallPayloadSchema,AuditLogThinkingPayloadSchema,AuditLogWakeTriggerPayloadSchema,+ AuditLogModelChangedPayloadSchema,+ AuditLogSessionResetPayloadSchema,+ AuditLogErrorPayloadSchema,HostBotAuditEventFrameSchema,} from "./schemas";@@ -431,6 +434,22 @@ export type {} from "./runtime-config";export { RUNTIME_CONFIG_VERSION, makeRuntimeConfig } from "./runtime-config";+export type { RuntimeModelCatalogEntry } from "./constants/runtime-models";+export {+ RUNTIME_MODEL_CATALOG,+ getRuntimeModelCatalog,+ runtimeSupportsModel,+} from "./constants/runtime-models";++export {+ MODEL_SELECT_DEFAULT,+ MODEL_SELECT_CUSTOM,+ resolveModelConfig,+ formatModelLabel,+ modelSelectState,+ modelNameFromSelect,+} from "./community/bot-model";+export { sendWakeToMachine, buildUnreadWakeCommand, dispatchOneUnreadWake } from "./community/wake-dispatch";export type { DispatchOneWakeResult } from "./community/wake-dispatch";export type { WakePayload, BuildUnreadWakeResult } from "./community/wake-dispatch";diff --git a/src/shared/src/schemas.test.ts b/src/shared/src/schemas.test.tsindex 00ec6658c..81f4c7bf7 100644--- a/src/shared/src/schemas.test.ts+++ b/src/shared/src/schemas.test.ts@@ -6,6 +6,8 @@ import {AgentTypingStopMessageSchema,CreateWorkspaceRequestSchema,UpdateWorkspaceRequestSchema,+ BotAuditEventSchema,+ BotAuditEventKindSchema,} from "./schemas"function validCreatePayload(image?: string) {@@ -191,3 +193,83 @@ describe("UpdateWorkspaceRequestSchema slug sanitization", () => {expect(res.slug!.length).toBeLessThanOrEqual(60)})})++describe("CommunityBotCreateRequestSchema — model", () => {+ it("accepts a model string, accepts null, rejects empty and >100 chars", () => {+ expect(CommunityBotCreateRequestSchema.safeParse({ ...validCreatePayload(), model: "claude-opus-4-6" }).success).toBe(true)+ expect(CommunityBotCreateRequestSchema.safeParse({ ...validCreatePayload(), model: null }).success).toBe(true)+ // omitted is fine (untouched)+ expect(CommunityBotCreateRequestSchema.safeParse(validCreatePayload()).success).toBe(true)+ expect(CommunityBotCreateRequestSchema.safeParse({ ...validCreatePayload(), model: "" }).success).toBe(false)+ expect(CommunityBotCreateRequestSchema.safeParse({ ...validCreatePayload(), model: "x".repeat(101) }).success).toBe(false)+ })+})++describe("CommunityBotPatchRequestSchema — model", () => {+ it("accepts {model: 'x'} and {model: null} as the sole field", () => {+ expect(CommunityBotPatchRequestSchema.safeParse({ model: "claude-opus-4-6" }).success).toBe(true)+ // explicit null must count as present for the at-least-one refine+ expect(CommunityBotPatchRequestSchema.safeParse({ model: null }).success).toBe(true)+ })+ it("rejects an empty object (no fields)", () => {+ expect(CommunityBotPatchRequestSchema.safeParse({}).success).toBe(false)+ })+})++describe("BotAuditEventSchema — model_changed", () => {+ it("parses a model_changed event with null-able from/to", () => {+ expect(+ BotAuditEventSchema.safeParse({ kind: "model_changed", payload: { from: "a", to: "b" } }).success,+ ).toBe(true)+ expect(+ BotAuditEventSchema.safeParse({ kind: "model_changed", payload: { from: null, to: "b" } }).success,+ ).toBe(true)+ expect(+ BotAuditEventSchema.safeParse({ kind: "model_changed", payload: { from: "a", to: null } }).success,+ ).toBe(true)+ })+ it("rejects a payload missing `to`", () => {+ expect(+ BotAuditEventSchema.safeParse({ kind: "model_changed", payload: { from: "a" } }).success,+ ).toBe(false)+ })+ it("BotAuditEventKindSchema includes model_changed", () => {+ expect(BotAuditEventKindSchema.safeParse("model_changed").success).toBe(true)+ })+})++describe("BotAuditEventSchema — error", () => {+ it("parses an error event across all scopes with a null-able model", () => {+ for (const scope of ["spawn", "runtime", "exit", "handshake_timeout", "model_switch", "reset"]) {+ expect(+ BotAuditEventSchema.safeParse({+ kind: "error",+ payload: { scope, code: "handshake_timeout", message: "no response", model: "claude-bogus" },+ }).success,+ ).toBe(true)+ }+ expect(+ BotAuditEventSchema.safeParse({+ kind: "error",+ payload: { scope: "spawn", code: "ENOENT", message: "not found", model: null },+ }).success,+ ).toBe(true)+ })+ it("rejects an unknown scope and an empty code", () => {+ expect(+ BotAuditEventSchema.safeParse({+ kind: "error",+ payload: { scope: "nope", code: "x", message: "m", model: null },+ }).success,+ ).toBe(false)+ expect(+ BotAuditEventSchema.safeParse({+ kind: "error",+ payload: { scope: "spawn", code: "", message: "m", model: null },+ }).success,+ ).toBe(false)+ })+ it("BotAuditEventKindSchema includes error", () => {+ expect(BotAuditEventKindSchema.safeParse("error").success).toBe(true)+ })+})diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 3f6a1a723..81d89173a 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1054,6 +1054,9 @@ export const CommunityBotCreateRequestSchema = z.object({machineId: z.string().min(1),runtime: z.string().min(1),image: BotImageUrlSchema.optional(),+ // Full launchable model id, or null for the runtime's default. `undefined`+ // ⇒ untouched (default), explicit `null` ⇒ default.+ model: z.string().trim().min(1).max(100).nullable().optional(),});export type CommunityBotCreateRequest = z.infer<typeof CommunityBotCreateRequestSchema>;@@ -1068,10 +1071,22 @@ export const CommunityBotPatchRequestSchema = z.optional(),description: z.string().max(COMMUNITY_BOT_DESCRIPTION_MAX).optional(),image: BotImageUrlSchema.nullable().optional(),+ // Full launchable model id, or null for the runtime's default. Explicit+ // `null` clears a set model; `undefined` leaves it untouched.+ model: z.string().trim().min(1).max(100).nullable().optional(),})- .refine((v) => v.name !== undefined || v.description !== undefined || v.image !== undefined, {- message: "at least one field must be provided",- });+ .refine(+ (v) =>+ v.name !== undefined ||+ v.description !== undefined ||+ v.image !== undefined ||+ // `model` alone is a valid patch. An explicit `null` must count as+ // present — hence the `in` form, not a truthiness check.+ "model" in v,+ {+ message: "at least one field must be provided",+ }+ );export type CommunityBotPatchRequest = z.infer<typeof CommunityBotPatchRequestSchema>;export const CommunityBotAddToServerRequestSchema = z.object({@@ -1285,12 +1300,46 @@ export type AuditLogWakeTriggerPayload = z.infer<typeof AuditLogWakeTriggerPayloexport const AuditLogSessionResetPayloadSchema = z.object({});export type AuditLogSessionResetPayload = z.infer<typeof AuditLogSessionResetPayloadSchema>;+/**+ * `model_changed` payload — the owner switched a bot's LLM model. `from`/`to`+ * are the full stored ids; `null` means the runtime's default. Written only+ * after the daemon confirmed delivery (see plan decision #7).+ */+export const AuditLogModelChangedPayloadSchema = z.object({+ from: z.string().nullable(),+ to: z.string().nullable(),+});+export type AuditLogModelChangedPayload = z.infer<typeof AuditLogModelChangedPayloadSchema>;++/**+ * `error` payload — a launch/runtime failure the owner should see. Emitted by+ * the daemon (never written server-side, unlike `model_changed`), so a bot+ * that goes silent has a visible reason instead of a black hole.+ *+ * - `scope` — which stage failed. `handshake_timeout` is the bad-model case:+ * the process spawned but never emitted its handshake within the deadline.+ * - `code` — machine reason (`pre_handshake_exit`, `handshake_timeout`,+ * `runtime_error`, `ENOENT`, `spawn_threw`, …). Stable enough to group on.+ * - `message`— human one-liner, already scrubbed of secrets by the daemon.+ * - `model` — the model in effect at failure (`null` = runtime default), so+ * the common "switched to a bad model" case names the culprit inline.+ */+export const AuditLogErrorPayloadSchema = z.object({+ scope: z.enum(["spawn", "runtime", "exit", "handshake_timeout", "model_switch", "reset"]),+ code: z.string().min(1).max(120),+ message: z.string().max(2048),+ model: z.string().nullable(),+});+export type AuditLogErrorPayload = z.infer<typeof AuditLogErrorPayloadSchema>;+export const BotAuditEventSchema = z.discriminatedUnion("kind", [z.object({ kind: z.literal("cli_invocation"), payload: AuditLogCliInvocationPayloadSchema }),z.object({ kind: z.literal("tool_call"), payload: AuditLogToolCallPayloadSchema }),z.object({ kind: z.literal("thinking"), payload: AuditLogThinkingPayloadSchema }),z.object({ kind: z.literal("wake_trigger"), payload: AuditLogWakeTriggerPayloadSchema }),z.object({ kind: z.literal("session_reset"), payload: AuditLogSessionResetPayloadSchema }),+ z.object({ kind: z.literal("model_changed"), payload: AuditLogModelChangedPayloadSchema }),+ z.object({ kind: z.literal("error"), payload: AuditLogErrorPayloadSchema }),]);export type BotAuditEvent = z.infer<typeof BotAuditEventSchema>;@@ -1300,6 +1349,8 @@ export const BotAuditEventKindSchema = z.enum(["thinking","wake_trigger","session_reset",+ "model_changed",+ "error",]);export type BotAuditEventKind = z.infer<typeof BotAuditEventKindSchema>;diff --git a/src/shared/test/community/wake-dispatch-build.test.ts b/src/shared/test/community/wake-dispatch-build.test.tsindex b32f0674a..8bc139b06 100644--- a/src/shared/test/community/wake-dispatch-build.test.ts+++ b/src/shared/test/community/wake-dispatch-build.test.ts@@ -60,6 +60,7 @@ const BOT_READY: {discriminator: string;machineId: string;runtime: string;+ modelName: string | null;ownerUserId: string | null;} = {state: "ready",@@ -68,6 +69,7 @@ const BOT_READY: {discriminator: "0042",machineId: "machine_1",runtime: "claude",+ modelName: null,ownerUserId: "owner_1",};@@ -155,6 +157,26 @@ describe("buildUnreadWakeCommand", () => {expect(result.command.unreadNotice.dmConversationId).toBeUndefined();});+ it("ready: config.model reflects the binding's model_name (named / custom / default)", async () => {+ // Catalog id ⇒ named.+ seedHappyPath({ bot: { modelName: "claude-opus-4-6" } });+ let result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });+ if (result.state !== "ready" || result.command.type !== "agent:wake") throw new Error("expected ready wake");+ expect(result.command.config.model).toEqual({ kind: "named", name: "claude-opus-4-6" });++ // Non-catalog id ⇒ custom.+ seedHappyPath({ bot: { modelName: "my-ft-model" } });+ result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });+ if (result.state !== "ready" || result.command.type !== "agent:wake") throw new Error("expected ready wake");+ expect(result.command.config.model).toEqual({ kind: "custom", name: "my-ft-model" });++ // NULL ⇒ default.+ seedHappyPath({ bot: { modelName: null } });+ result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });+ if (result.state !== "ready" || result.command.type !== "agent:wake") throw new Error("expected ready wake");+ expect(result.command.config.model).toEqual({ kind: "default" });+ });+it("skip: message_missing when the message no longer exists", async () => {mockGetWakeMessageScopeById.mockResolvedValue(null);diff --git a/src/shared/test/queries/community-bot-audit-log.test.ts b/src/shared/test/queries/community-bot-audit-log.test.tsindex 2e071a791..14254564a 100644--- a/src/shared/test/queries/community-bot-audit-log.test.ts+++ b/src/shared/test/queries/community-bot-audit-log.test.ts@@ -14,6 +14,7 @@ describe("community/bot-audit-log exports", () => {expect(typeof q.pruneBotActivityEventsStatement).toBe("function")expect(typeof q.insertBotActivityEventAndPrune).toBe("function")expect(typeof q.insertBotAuditWakeTrigger).toBe("function")+ expect(typeof q.insertBotAuditError).toBe("function")})it("exposes a reader", () => {@@ -105,6 +106,20 @@ describe("BotAuditEventSchema — payload discriminated union", () => {})expect(r.success).toBe(false)})+ it("accepts an error payload with scope/code/message/model", () => {+ const r = BotAuditEventSchema.safeParse({+ kind: "error",+ payload: { scope: "handshake_timeout", code: "handshake_timeout", message: "no response after 60s", model: "claude-bogus" },+ })+ expect(r.success).toBe(true)+ })+ it("rejects an error payload with a bad scope", () => {+ const r = BotAuditEventSchema.safeParse({+ kind: "error",+ payload: { scope: "meltdown", code: "x", message: "m", model: null },+ })+ expect(r.success).toBe(false)+ })it("rejects a kind/payload mismatch", () => {const r = BotAuditEventSchema.safeParse({kind: "tool_call",diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.tsindex e56e78637..d8241d167 100644--- a/src/shared/test/queries/community-bot.test.ts+++ b/src/shared/test/queries/community-bot.test.ts@@ -166,10 +166,16 @@ describe("getBotBinding", () => {return chain}- it("returns { machineId, runtime } when the binding exists", async () => {- const chain = makeSelectChain([{ machineId: "machine_1", runtime: "codex" }])+ it("returns { machineId, runtime, modelName } when the binding exists (modelName defaults to null)", async () => {+ const chain = makeSelectChain([{ machineId: "machine_1", runtime: "codex", modelName: null }])const result = await q.getBotBinding(chain, "bot_1")- expect(result).toEqual({ machineId: "machine_1", runtime: "codex" })+ expect(result).toEqual({ machineId: "machine_1", runtime: "codex", modelName: null })+ })++ it("surfaces a stored modelName", async () => {+ const chain = makeSelectChain([{ machineId: "machine_1", runtime: "claude", modelName: "claude-opus-4-6" }])+ const result = await q.getBotBinding(chain, "bot_1")+ expect(result).toEqual({ machineId: "machine_1", runtime: "claude", modelName: "claude-opus-4-6" })})it("returns null when no binding row matches", async () => {diff --git a/src/web/migrations/0064_community_bot_binding_model.sql b/src/web/migrations/0064_community_bot_binding_model.sqlnew file mode 100644index 000000000..26f776a10--- /dev/null+++ b/src/web/migrations/0064_community_bot_binding_model.sql@@ -0,0 +1,17 @@+-- Per-bot LLM model selection — one narrow nullable column on the bot binding.+-- See plans/community-bot-model-sync.md (TODO 5).+--+-- `model_name` is the full launchable model id (e.g. "claude-opus-4-6"), or+-- NULL for the runtime's own default. The ModelConfig `kind`+-- (default / named / custom) is DERIVED from the runtime's catalog at read+-- time (see src/shared/src/community/bot-model.ts) and is NEVER stored:+-- deriving at read time always reflects the current catalog, whereas a+-- persisted kind would freeze a catalog-membership verdict.+--+-- NULL ⇒ { kind: "default" }, which is byte-identical to the config every bot+-- receives today, so this migration is behaviorally INERT for existing rows.+-- No index — the column is never filtered on.+--+-- SQLite has no `ADD COLUMN IF NOT EXISTS`; this statement is NOT idempotent.++ALTER TABLE community_bot_binding ADD COLUMN model_name TEXT;diff --git a/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts b/src/web/src/app/api/community/bots/[id]/audit-log/route.test.tsindex 66f37a608..9daafabb4 100644--- a/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts+++ b/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts@@ -171,6 +171,26 @@ describe("GET /api/community/bots/[id]/audit-log", () => {)})+ it("returns a parsed {from,to} payload for a model_changed row (guards parseAuditLogPayload's default)", async () => {+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })+ mockListBotActivityEvents.mockResolvedValue([+ {+ id: "bae_m",+ botId: "b1",+ sessionId: null,+ launchId: null,+ kind: "model_changed",+ payload: JSON.stringify({ from: "claude-opus-4-6", to: "claude-sonnet-4-6" }),+ createdAt: "2026-07-26T00:00:00.000Z",+ },+ ])+ const res = await GET(req(), ctx("b1"))+ expect(res.status).toBe(200)+ const body = (await res.json()) as { events: Array<{ kind: string; payload: unknown }> }+ expect(body.events[0]!.kind).toBe("model_changed")+ expect(body.events[0]!.payload).toEqual({ from: "claude-opus-4-6", to: "claude-sonnet-4-6" })+ })+it("caps limit at 100 and floors it at 1 (defends against unbounded page requests)", async () => {mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })mockListBotActivityEvents.mockResolvedValue([])diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.test.tsindex d95ef1fe0..b83b506f3 100644--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts@@ -71,6 +71,7 @@ const READY_CTX = {discriminator: "0042",machineId: "mac_1",runtime: "claude",+ modelName: "claude-opus-4-6",ownerUserId: "owner_1",}@@ -161,4 +162,16 @@ describe("POST /api/community/bots/[id]/reset-session", () => {}),)})++ it("regression: reset sends the bot's configured model in config.model (not default)", async () => {+ seedOwnedAndBound()+ mockPushAgentResetToMachine.mockResolvedValue({ sent: 1 })+ mockInsertBotAuditSessionReset.mockResolvedValue({ id: "evt_1", createdAt: "2026-07-26T00:00:00.000Z" })+ mockBroadcastToUser.mockResolvedValue(undefined)++ const res = await POST(req(), ctx)+ expect(res.status).toBe(200)+ const [, , args] = mockPushAgentResetToMachine.mock.calls[0]!+ expect(args.config.model).toEqual({ kind: "named", name: "claude-opus-4-6" })+ })})diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.tsindex 397e106fc..0ef1b6d70 100644--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts@@ -1,5 +1,5 @@import { nanoid } from "nanoid"-import { queries, makeRuntimeConfig, formatHandle, WS_EVENTS } from "@alook/shared"+import { queries, makeRuntimeConfig, resolveModelConfig, formatHandle, WS_EVENTS } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"@@ -29,6 +29,7 @@ export const POST = withAuth(async (_req, ctx) => {const config = makeRuntimeConfig({runtime: wakeCtx.runtime,+ model: resolveModelConfig(wakeCtx.runtime, wakeCtx.modelName),agentName: wakeCtx.name,agentHandle: `@${formatHandle(wakeCtx.name, wakeCtx.discriminator)}`,})diff --git a/src/web/src/app/api/community/bots/[id]/route.test.ts b/src/web/src/app/api/community/bots/[id]/route.test.tsindex cc6827cfd..bdbd1568a 100644--- a/src/web/src/app/api/community/bots/[id]/route.test.ts+++ b/src/web/src/app/api/community/bots/[id]/route.test.ts@@ -3,8 +3,13 @@ import { NextRequest } from "next/server"const mockGetBotOwnedBy = vi.fn()const mockUpdateBot = vi.fn()+const mockUpdateBotModel = vi.fn()+const mockGetBotWakeContext = vi.fn()+const mockInsertBotAuditModelChanged = vi.fn()const mockGetUserPublic = vi.fn()const mockPushBotEventToMachine = vi.fn()+const mockPushAgentModelSwitchToMachine = vi.fn()+const mockBroadcastToUser = vi.fn()const mockLogAudit = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({@@ -21,6 +26,11 @@ vi.mock("@alook/shared", async () => {communityBot: {getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),updateBot: (...a: unknown[]) => mockUpdateBot(...a),+ updateBotModel: (...a: unknown[]) => mockUpdateBotModel(...a),+ getBotWakeContext: (...a: unknown[]) => mockGetBotWakeContext(...a),+ },+ communityBotAuditLog: {+ insertBotAuditModelChanged: (...a: unknown[]) => mockInsertBotAuditModelChanged(...a),},user: {getUserPublic: (...a: unknown[]) => mockGetUserPublic(...a),@@ -31,6 +41,10 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/community/bot-push", () => ({pushBotEventToMachine: (...a: unknown[]) => mockPushBotEventToMachine(...a),+ pushAgentModelSwitchToMachine: (...a: unknown[]) => mockPushAgentModelSwitchToMachine(...a),+}))+vi.mock("@/lib/broadcast", () => ({+ broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),}))vi.mock("@/lib/community/fanout", () => ({fanOutToServerMembers: vi.fn(),@@ -72,11 +86,20 @@ describe("PATCH /api/community/bots/[id]", () => {vi.clearAllMocks()mockGetBotOwnedBy.mockResolvedValue({id: "b1", name: "Old", description: "old desc", machineId: "mac1", ownerUserId: "u1",+ runtime: "claude", modelName: null,})mockUpdateBot.mockResolvedValue({id: "b1", name: "New", discriminator: "0001", description: "new desc", image: null,})mockGetUserPublic.mockResolvedValue({ id: "u1", name: "Owner", discriminator: "9999" })+ mockGetBotWakeContext.mockResolvedValue({+ state: "ready", botUserId: "b1", name: "Old", discriminator: "0001",+ machineId: "mac1", runtime: "claude", modelName: null, ownerUserId: "u1",+ })+ mockPushAgentModelSwitchToMachine.mockResolvedValue({ sent: 1, deliveryError: false })+ mockInsertBotAuditModelChanged.mockResolvedValue({ id: "evt_1", createdAt: "2026-07-26T00:00:00.000Z" })+ // A bound bot's model write matches its binding row by default.+ mockUpdateBotModel.mockResolvedValue(true)})it("updates and pushes bot:updated to the daemon when the name changed", async () => {@@ -108,4 +131,134 @@ describe("PATCH /api/community/bots/[id]", () => {expect(mockPushBotEventToMachine).not.toHaveBeenCalled()expect(mockUpdateBot).toHaveBeenCalled()})++ it("changed model on a wake-ready bot: writes column, pushes new model, applied:true, one audit row", async () => {+ const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)+ expect(res.status).toBe(200)+ const body = (await res.json()) as { applied: boolean; deliveryError: boolean; bot: { modelName: string } }+ expect(body.applied).toBe(true)+ expect(body.deliveryError).toBe(false)+ expect(body.bot.modelName).toBe("claude-sonnet-4-6")+ expect(mockUpdateBotModel).toHaveBeenCalledWith(expect.anything(), "b1", "u1", "claude-sonnet-4-6")+ expect(mockPushAgentModelSwitchToMachine).toHaveBeenCalledWith(+ expect.anything(),+ "mac1",+ expect.objectContaining({+ agentId: "b1",+ config: expect.objectContaining({ model: { kind: "named", name: "claude-sonnet-4-6" } }),+ }),+ )+ expect(mockInsertBotAuditModelChanged).toHaveBeenCalledTimes(1)+ expect(mockInsertBotAuditModelChanged).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ botId: "b1", from: null, to: "claude-sonnet-4-6" }),+ )+ })++ it("changed model, daemon disconnected (sent 0): 200, applied:false, deliveryError:false, no audit", async () => {+ mockPushAgentModelSwitchToMachine.mockResolvedValue({ sent: 0, deliveryError: false })+ const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)+ const body = (await res.json()) as { applied: boolean; deliveryError: boolean }+ expect(res.status).toBe(200)+ expect(body.applied).toBe(false)+ expect(body.deliveryError).toBe(false)+ expect(mockUpdateBotModel).toHaveBeenCalled()+ expect(mockInsertBotAuditModelChanged).not.toHaveBeenCalled()+ })++ it("changed model, push transport error: 200, applied:false, deliveryError:true, no audit", async () => {+ mockPushAgentModelSwitchToMachine.mockResolvedValue({ sent: 0, deliveryError: true })+ const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)+ const body = (await res.json()) as { applied: boolean; deliveryError: boolean }+ expect(res.status).toBe(200)+ expect(body.applied).toBe(false)+ expect(body.deliveryError).toBe(true)+ expect(mockInsertBotAuditModelChanged).not.toHaveBeenCalled()+ })++ it("changed model but wake ctx not ready: no push, applied:false, column still written, never 409", async () => {+ mockGetBotWakeContext.mockResolvedValue({ state: "bot_unbound" })+ const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)+ expect(res.status).toBe(200)+ const body = (await res.json()) as { applied: boolean }+ expect(body.applied).toBe(false)+ expect(mockUpdateBotModel).toHaveBeenCalled()+ expect(mockPushAgentModelSwitchToMachine).not.toHaveBeenCalled()+ expect(mockInsertBotAuditModelChanged).not.toHaveBeenCalled()+ })++ it("model PATCH on a bot with no binding row → 409, does NOT claim the model was saved", async () => {+ // getBotOwnedBy passes (the bot exists + is owned) but the binding row is+ // absent, so updateBotModel matches zero rows.+ mockUpdateBotModel.mockResolvedValue(false)+ const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)+ expect(res.status).toBe(409)+ const body = (await res.json()) as { error?: string; bot?: { modelName: string } }+ // Must not echo the model as saved — it wasn't.+ expect(body.bot).toBeUndefined()+ expect(mockPushAgentModelSwitchToMachine).not.toHaveBeenCalled()+ expect(mockInsertBotAuditModelChanged).not.toHaveBeenCalled()+ })++ it("same model / omitted model: no push, no audit, column untouched", async () => {+ // same: before.modelName is null, body sends null+ let res = await PATCH(patchReq({ model: null }), ctx)+ expect(res.status).toBe(200)+ expect(mockUpdateBotModel).not.toHaveBeenCalled()+ expect(mockPushAgentModelSwitchToMachine).not.toHaveBeenCalled()++ // omitted: name-only patch+ vi.clearAllMocks()+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1", runtime: "claude", modelName: null })+ mockUpdateBot.mockResolvedValue({ id: "b1", name: "New", discriminator: "0001", description: "d", image: null })+ mockGetUserPublic.mockResolvedValue({ id: "u1", name: "Owner", discriminator: "9999" })+ res = await PATCH(patchReq({ name: "New" }), ctx)+ expect(res.status).toBe(200)+ expect(mockUpdateBotModel).not.toHaveBeenCalled()+ })++ it("model:null on a bot that had one: clears column, pushes default, audits {from, to:null}", async () => {+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1", runtime: "claude", modelName: "claude-opus-4-6" })+ mockGetBotWakeContext.mockResolvedValue({ state: "ready", botUserId: "b1", name: "Old", discriminator: "0001", machineId: "mac1", runtime: "claude", modelName: "claude-opus-4-6", ownerUserId: "u1" })+ const res = await PATCH(patchReq({ model: null }), ctx)+ expect(res.status).toBe(200)+ expect(mockUpdateBotModel).toHaveBeenCalledWith(expect.anything(), "b1", "u1", null)+ expect(mockPushAgentModelSwitchToMachine).toHaveBeenCalledWith(+ expect.anything(),+ "mac1",+ expect.objectContaining({ config: expect.objectContaining({ model: { kind: "default" } }) }),+ )+ expect(mockInsertBotAuditModelChanged).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ from: "claude-opus-4-6", to: null }),+ )+ })++ it("name AND model changed: both bot:updated and agent:model_switch pushed; audit changedFields includes both", async () => {+ const res = await PATCH(patchReq({ name: "New", model: "claude-sonnet-4-6" }), ctx)+ expect(res.status).toBe(200)+ expect(mockPushBotEventToMachine).toHaveBeenCalledWith(expect.anything(), "mac1", expect.objectContaining({ type: "bot:updated" }))+ expect(mockPushAgentModelSwitchToMachine).toHaveBeenCalled()+ const auditCall = mockLogAudit.mock.calls.at(-1)?.[1] as { changes: string }+ const fields = JSON.parse(auditCall.changes).fields as string[]+ expect(fields).toContain("name")+ expect(fields).toContain("model")+ })++ it("model on an antigravity bot → 400; runtime null → allowed", async () => {+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1", runtime: "antigravity", modelName: null })+ let res = await PATCH(patchReq({ model: "whatever" }), ctx)+ expect(res.status).toBe(400)+ expect(mockUpdateBotModel).not.toHaveBeenCalled()++ vi.clearAllMocks()+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1", runtime: null, modelName: null })+ mockGetBotWakeContext.mockResolvedValue({ state: "ready", botUserId: "b1", name: "Old", discriminator: "0001", machineId: "mac1", runtime: "claude", modelName: null, ownerUserId: "u1" })+ mockUpdateBot.mockResolvedValue({ id: "b1", name: "Old", discriminator: "0001", description: "d", image: null })+ mockPushAgentModelSwitchToMachine.mockResolvedValue({ sent: 1, deliveryError: false })+ mockInsertBotAuditModelChanged.mockResolvedValue({ id: "e", createdAt: "t" })+ res = await PATCH(patchReq({ model: "some-model" }), ctx)+ expect(res.status).toBe(200)+ expect(mockUpdateBotModel).toHaveBeenCalled()+ })})diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.tsindex 6282f1740..adba9a25d 100644--- a/src/web/src/app/api/community/bots/[id]/route.ts+++ b/src/web/src/app/api/community/bots/[id]/route.ts@@ -1,11 +1,21 @@import { NextRequest } from "next/server"import { NextResponse } from "next/server"-import { queries, CommunityBotPatchRequestSchema, WS_EVENTS } from "@alook/shared"+import { nanoid } from "nanoid"+import {+ queries,+ CommunityBotPatchRequestSchema,+ WS_EVENTS,+ makeRuntimeConfig,+ resolveModelConfig,+ runtimeSupportsModel,+ formatHandle,+} from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"-import { pushBotEventToMachine } from "@/lib/community/bot-push"+import { pushBotEventToMachine, pushAgentModelSwitchToMachine } from "@/lib/community/bot-push"+import { broadcastToUser } from "@/lib/broadcast"import { fanOutToServerMembers } from "@/lib/community/fanout"export const GET = withAuth(async (_req, ctx) => {@@ -28,6 +38,17 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {const nameChanged = body.name !== undefined && body.name !== before.nameconst descriptionChanged =body.description !== undefined && body.description !== before.description+ // `model` alone is a valid patch. Storage/wire/UI all speak `string | null`,+ // so "did it change?" is a plain string comparison — no ModelConfig here.+ const nextModel = body.model === undefined ? undefined : (body.model ?? null)+ const modelChanged = nextModel !== undefined && nextModel !== (before.modelName ?? null)++ // antigravity ignores the model at launch; reject a non-null model on it (and+ // on any runtime that doesn't support one). `before.runtime === null`+ // (unknown runtime) is allowed — only antigravity is excluded.+ if (nextModel !== null && nextModel !== undefined && !runtimeSupportsModel(before.runtime)) {+ return writeError(`runtime ${before.runtime} does not support a model selection`, 400)+ }// Will we push bot:updated to the daemon? (Iff name/description changed —// image-only is display-only and doesn't affect the system prompt.) If so,// resolve the owner handle BEFORE mutating the row: the frame shape must stay@@ -60,10 +81,71 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {})}+ // Model switch. D1 is authoritative — write the column regardless of daemon+ // reachability, then EXPEDITE via a push. NEVER 409: name/description writes+ // (and this one) must land even when the bot is offline. The audit row is+ // written only on confirmed delivery (`sent > 0`), so an offline/undelivered+ // switch persists silently and the next wake applies it.+ let applied = false+ let deliveryError = false+ if (modelChanged) {+ // A bot with no binding row (unbound / never paired) passes the+ // `getBotOwnedBy` 404 check above but has nothing to write the model onto.+ // Reject rather than echo a model the response would claim was saved while+ // a later GET reads the old value (UI/D1 divergence).+ const wrote = await queries.communityBot.updateBotModel(db, id, ctx.userId, nextModel!)+ if (!wrote) {+ return writeError("bot has no runtime binding — pair it to a machine before setting a model", 409)+ }++ const wakeCtx = await queries.communityBot.getBotWakeContext(db, id)+ if (wakeCtx.state === "ready") {+ const config = makeRuntimeConfig({+ runtime: wakeCtx.runtime,+ model: resolveModelConfig(wakeCtx.runtime, nextModel!),+ agentName: wakeCtx.name,+ agentHandle: `@${formatHandle(wakeCtx.name, wakeCtx.discriminator)}`,+ })+ const result = await pushAgentModelSwitchToMachine(ctx.env, wakeCtx.machineId, {+ agentId: id,+ config,+ launchId: nanoid(),+ })+ deliveryError = result.deliveryError+ applied = result.sent > 0++ if (applied) {+ const inserted = await queries.communityBotAuditLog.insertBotAuditModelChanged(db, {+ botId: id,+ actorId: ctx.userId,+ from: before.modelName ?? null,+ to: nextModel!,+ })+ if (inserted) {+ try {+ await broadcastToUser(ctx.userId, {+ type: WS_EVENTS.BOT_AUDIT_EVENT,+ botId: id,+ id: inserted.id,+ kind: "model_changed",+ payload: { from: before.modelName ?? null, to: nextModel! },+ sessionId: null,+ launchId: null,+ createdAt: inserted.createdAt,+ })+ } catch {+ // Best-effort — D1 row is authoritative.+ }+ }+ }+ }+ }+const changedFields: string[] = []if (body.name !== undefined) changedFields.push("name")if (body.description !== undefined) changedFields.push("description")if (body.image !== undefined) changedFields.push("image")+ if (modelChanged) changedFields.push("model")logAudit(db, {serverId: null,actorId: ctx.userId,@@ -79,7 +161,10 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {name: updated.name,description: updated.description,image: updated.image,+ modelName: nextModel !== undefined ? nextModel : (before.modelName ?? null),},+ applied,+ deliveryError,})})diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.tsnew file mode 100644index 000000000..823200578--- /dev/null+++ b/src/web/src/app/api/community/bots/route.test.ts@@ -0,0 +1,117 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++const mockCountLiveBotsForOwner = vi.fn()+const mockGetMachineForOwner = vi.fn()+const mockCreateBot = vi.fn()+const mockGetUserPublic = vi.fn()+const mockPushBotEventToMachine = vi.fn()+const mockLogAudit = vi.fn()++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}))++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityBot: {+ countLiveBotsForOwner: (...a: unknown[]) => mockCountLiveBotsForOwner(...a),+ getMachineForOwner: (...a: unknown[]) => mockGetMachineForOwner(...a),+ createBot: (...a: unknown[]) => mockCreateBot(...a),+ },+ user: {+ getUserPublic: (...a: unknown[]) => mockGetUserPublic(...a),+ },+ },+ }+})++vi.mock("@/lib/community/bot-push", () => ({+ pushBotEventToMachine: (...a: unknown[]) => mockPushBotEventToMachine(...a),+}))+vi.mock("@/lib/community/audit", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")+ return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }+})++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })+ },+}))++vi.mock("@/lib/middleware/helpers", async () => {+ const { NextResponse } = require("next/server")+ const actual = await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")+ return {+ ...actual,+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++import { POST } from "./route"++function postReq(body: unknown) {+ return new NextRequest("http://localhost/api/community/bots", {+ method: "POST",+ body: JSON.stringify(body),+ })+}+const ctx = {} as any++function base(model?: unknown, runtime = "claude") {+ return {+ name: "MyBot",+ machineId: "mac1",+ runtime,+ ...(model !== undefined ? { model } : {}),+ }+}++describe("POST /api/community/bots — model", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockCountLiveBotsForOwner.mockResolvedValue(0)+ mockGetMachineForOwner.mockResolvedValue({+ id: "mac1",+ availableRuntimes: [{ id: "claude", status: "healthy" }, { id: "antigravity", status: "healthy" }],+ })+ mockCreateBot.mockResolvedValue({ botId: "b1", name: "MyBot", discriminator: "0001", description: "", image: null })+ mockGetUserPublic.mockResolvedValue({ id: "u1", name: "Owner", discriminator: "9999" })+ })++ it("persists model_name and returns it in the 201 body", async () => {+ const res = await POST(postReq(base("claude-opus-4-6")), ctx)+ expect(res.status).toBe(201)+ const body = (await res.json()) as { bot: { modelName: string | null } }+ expect(body.bot.modelName).toBe("claude-opus-4-6")+ expect(mockCreateBot).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ modelName: "claude-opus-4-6" }),+ )+ })++ it("omitting model leaves modelName null", async () => {+ const res = await POST(postReq(base()), ctx)+ expect(res.status).toBe(201)+ const body = (await res.json()) as { bot: { modelName: string | null } }+ expect(body.bot.modelName).toBeNull()+ expect(mockCreateBot).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ modelName: null }),+ )+ })++ it("rejects a model on runtime antigravity with 400", async () => {+ const res = await POST(postReq(base("some-model", "antigravity")), ctx)+ expect(res.status).toBe(400)+ expect(mockCreateBot).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.tsindex fc90216a1..02558c2fc 100644--- a/src/web/src/app/api/community/bots/route.ts+++ b/src/web/src/app/api/community/bots/route.ts@@ -3,6 +3,7 @@ import {queries,CommunityBotCreateRequestSchema,COMMUNITY_BOT_LIMIT_PER_OWNER,+ runtimeSupportsModel,} from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"@@ -54,6 +55,13 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {)}+ // antigravity discards the model at launch; storing an inert value would make+ // the card lie. Reject a non-null model on a runtime that doesn't honor it.+ const modelName = body.model ?? null+ if (modelName !== null && !runtimeSupportsModel(body.runtime)) {+ return writeError(`runtime ${body.runtime} does not support a model selection`, 400)+ }+const created = await queries.communityBot.createBot(db, {ownerId: ctx.userId,name: body.name,@@ -61,6 +69,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {machineId: body.machineId,runtime: body.runtime,image: body.image ?? null,+ modelName,})// The bot's owner is the authenticated caller — resolve their handle to@@ -109,6 +118,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {image: created.image,machineId: body.machineId,runtime: body.runtime,+ modelName,},},201,diff --git a/src/web/src/components/community/bots/bot-activity-row.test.ts b/src/web/src/components/community/bots/bot-activity-row.test.tsnew file mode 100644index 000000000..e4dfd2d7d--- /dev/null+++ b/src/web/src/components/community/bots/bot-activity-row.test.ts@@ -0,0 +1,97 @@+import { describe, it, expect } from "vitest"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"++import { BotActivityRow } from "./bot-activity-row"+import type { AuditEvent } from "@/hooks/community/use-bot-audit-log"++function render(event: AuditEvent): TestRenderer.ReactTestRenderer {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(BotActivityRow, { event }))+ })+ return renderer+}++// Flatten a node's rendered children into a single string.+const flatten = (children: unknown): string => {+ if (typeof children === "string") return children+ if (Array.isArray(children)) return children.map(flatten).join("")+ if (children && typeof children === "object" && "props" in (children as any)) {+ return flatten((children as any).props.children)+ }+ return ""+}++function rowText(renderer: TestRenderer.ReactTestRenderer, testid: string): string {+ const node = renderer.root.find((n) => n.props?.["data-testid"] === testid)+ return flatten(node.props.children).replace(/\s+/g, " ").trim()+}++function modelRowText(renderer: TestRenderer.ReactTestRenderer): string {+ return rowText(renderer, "bot-activity-event-model_changed")+}++describe("BotActivityRow — model_changed", () => {+ it("renders the raw stored ids from → to", () => {+ const renderer = render({+ id: "e1",+ kind: "model_changed",+ payload: { from: "claude-opus-4-6", to: "claude-sonnet-4-6" },+ sessionId: null,+ launchId: null,+ createdAt: "2026-07-26T00:00:00.000Z",+ })+ expect(modelRowText(renderer)).toContain("claude-opus-4-6")+ expect(modelRowText(renderer)).toContain("→")+ expect(modelRowText(renderer)).toContain("claude-sonnet-4-6")+ })++ it("substitutes the literal `default` for a null `from`", () => {+ const renderer = render({+ id: "e2",+ kind: "model_changed",+ payload: { from: null, to: "claude-sonnet-4-6" },+ sessionId: null,+ launchId: null,+ createdAt: "2026-07-26T00:00:00.000Z",+ })+ expect(modelRowText(renderer)).toContain("default")+ expect(modelRowText(renderer)).toContain("claude-sonnet-4-6")+ })+})++describe("BotActivityRow — error", () => {+ it("renders the failure message plus the code · model detail", () => {+ const renderer = render({+ id: "e3",+ kind: "error",+ payload: {+ scope: "handshake_timeout",+ code: "handshake_timeout",+ message: "No response 60s after launch — the runtime may be misconfigured.",+ model: "claude-bogus",+ },+ sessionId: null,+ launchId: null,+ createdAt: "2026-07-26T00:00:00.000Z",+ })+ const text = rowText(renderer, "bot-activity-event-error")+ expect(text).toContain("No response 60s after launch")+ expect(text).toContain("handshake_timeout")+ expect(text).toContain("claude-bogus")+ })++ it("falls back gracefully when payload fields are missing", () => {+ const renderer = render({+ id: "e4",+ kind: "error",+ payload: {},+ sessionId: null,+ launchId: null,+ createdAt: "2026-07-26T00:00:00.000Z",+ })+ const text = rowText(renderer, "bot-activity-event-error")+ expect(text).toContain("Something went wrong")+ })+})diff --git a/src/web/src/components/community/bots/bot-activity-row.tsx b/src/web/src/components/community/bots/bot-activity-row.tsxindex 08bbf796e..439d500b0 100644--- a/src/web/src/components/community/bots/bot-activity-row.tsx+++ b/src/web/src/components/community/bots/bot-activity-row.tsx@@ -57,6 +57,8 @@ function kindMeta(kind: AuditKind): { label: string; tone: string } {if (kind === "tool_call") return { label: "tool", tone: "text-muted-foreground" }if (kind === "wake_trigger") return { label: "wake", tone: "text-foreground/70" }if (kind === "session_reset") return { label: "reset", tone: "text-foreground/70" }+ if (kind === "model_changed") return { label: "model", tone: "text-foreground/70" }+ if (kind === "error") return { label: "err", tone: "text-destructive" }return { label: "think", tone: "text-muted-foreground/70" }}@@ -110,6 +112,42 @@ function RowBody({</div>)}+ if (event.kind === "model_changed") {+ const p = event.payload as { from?: string | null; to?: string | null } | null+ // Developer-facing audit surface — print the RAW stored ids (no card-style+ // shortening), with the literal `default` standing in for `null`.+ const from = p?.from ?? "default"+ const to = p?.to ?? "default"+ return (+ <div+ data-testid="bot-activity-event-model_changed"+ className="truncate font-mono text-[13px] text-foreground"+ >+ {from} <span className="text-muted-foreground/60">→</span> {to}+ </div>+ )+ }+ if (event.kind === "error") {+ const p = event.payload as {+ scope?: string+ code?: string+ message?: string+ model?: string | null+ } | null+ const message = p?.message || "Something went wrong"+ // The code/scope is the machine detail; the model names the common+ // bad-model culprit inline. Both muted so the message reads first.+ const detail = p?.model ? `${p?.code ?? "error"} · ${p.model}` : p?.code ?? p?.scope ?? "error"+ return (+ <div+ data-testid="bot-activity-event-error"+ className="flex min-w-0 flex-col gap-0.5"+ >+ <span className="wrap-break-word font-mono text-[13px] text-destructive">{message}</span>+ <span className="truncate font-mono text-[11px] text-muted-foreground/70">{detail}</span>+ </div>+ )+ }if (event.kind === "wake_trigger") {const p = event.payload as {channel?: stringdiff --git a/src/web/src/components/community/bots/bot-form-validation.ts b/src/web/src/components/community/bots/bot-form-validation.tsindex 9c36eb910..60f68984f 100644--- a/src/web/src/components/community/bots/bot-form-validation.ts+++ b/src/web/src/components/community/bots/bot-form-validation.ts@@ -33,3 +33,16 @@ export function validateBotCreateFields({export function hasBotCreateFieldErrors(errors: BotCreateFieldErrors): boolean {return Boolean(errors.name || errors.machineId || errors.runtime)}++/**+ * Validate a picked model value (the `string | null` the ModelField emits). A+ * `Custom…` selection that was left empty resolves to `null` (Default), which+ * is valid; the only failure is a name over the server's 100-char cap. Returns+ * an error message, or undefined when the model is acceptable.+ */+export function validateBotModel(model: string | null): string | undefined {+ if (model === null) return undefined+ if (model.trim().length === 0) return "Enter a model name"+ if (model.length > 100) return "Model name must be 100 characters or fewer"+ return undefined+}diff --git a/src/web/src/components/community/bots/bot-list-card.test.ts b/src/web/src/components/community/bots/bot-list-card.test.tsnew file mode 100644index 000000000..272bfc6d5--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-card.test.ts@@ -0,0 +1,106 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import type { BotSummary } from "@/hooks/community/use-bots"++// BotList pulls in many hooks + portal-heavy children. Mock them to passthroughs+// so we can render just the card meta row and assert the model segment. What we+// assert is the presence/absence of `data-testid="bot-card-model"` and its text.++const useBotsMock = vi.fn()++vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: vi.fn() }),+ useSearchParams: () => new URLSearchParams(),+}))+vi.mock("@/hooks/community/use-machines", () => ({+ useMachines: () => ({ machines: [{ id: "mac1", displayName: "Mac", hostname: "mac", status: "online" }] }),+}))+vi.mock("@/hooks/community/use-bots", () => ({+ useBots: () => useBotsMock(),+ useDeleteBot: () => ({ mutateAsync: vi.fn(), isPending: false }),+ useResetBotSession: () => ({ mutateAsync: vi.fn(), isPending: false }),+}))+vi.mock("@/hooks/community/mutations", () => ({+ useCreateOrGetDm: () => ({ mutateAsync: vi.fn() }),+}))+vi.mock("@/stores/community/ws", () => ({+ useOnlineUserIds: () => new Set<string>(),+}))++function passthrough(name: string) {+ return function P({ children }: { children?: React.ReactNode }) {+ return React.createElement("div", { "data-mock": name }, children)+ }+}+vi.mock("./create-bot-sheet", () => ({ CreateBotSheet: passthrough("create-sheet") }))+vi.mock("./edit-bot-sheet", () => ({ EditBotSheet: passthrough("edit-sheet") }))+vi.mock("./bot-activity-modal", () => ({ BotActivityModal: passthrough("activity-modal") }))+vi.mock("@/components/avatar", () => ({ AgentAvatar: () => React.createElement("span", {}) }))+vi.mock("@/components/provider-logo", () => ({ ProviderLogo: () => React.createElement("span", {}) }))+vi.mock("@/components/ui/dropdown-menu", () => ({+ DropdownMenu: passthrough("dm"),+ DropdownMenuContent: passthrough("dmc"),+ DropdownMenuItem: passthrough("dmi"),+ DropdownMenuTrigger: passthrough("dmt"),+}))+vi.mock("@/components/ui/alert-dialog", () => ({+ AlertDialog: passthrough("ad"),+ AlertDialogAction: passthrough("ada"),+ AlertDialogCancel: passthrough("adc"),+ AlertDialogContent: passthrough("adco"),+ AlertDialogDescription: passthrough("add"),+ AlertDialogFooter: passthrough("adf"),+ AlertDialogHeader: passthrough("adh"),+ AlertDialogTitle: passthrough("adt"),+}))++import { BotList } from "./bot-list"++function bot(over: Partial<BotSummary>): BotSummary {+ return {+ id: "b1",+ name: "Blake",+ description: "",+ image: null,+ machineId: "mac1",+ runtime: "claude",+ modelName: null,+ ...over,+ }+}++function render(): TestRenderer.ReactTestRenderer {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(BotList, {}))+ })+ return renderer+}++function modelSegments(renderer: TestRenderer.ReactTestRenderer): string[] {+ return renderer.root+ .findAll((n) => n.props?.["data-testid"] === "bot-card-model")+ .map((n) => {+ const c = n.props.children+ return typeof c === "string" ? c : Array.isArray(c) ? c.join("") : String(c)+ })+}++describe("BotList — card model segment", () => {+ beforeEach(() => {+ useBotsMock.mockReset()+ })++ it("renders `opus-4-6` after the runtime when a model is set", () => {+ useBotsMock.mockReturnValue({ bots: [bot({ modelName: "claude-opus-4-6" })], isLoading: false })+ const renderer = render()+ expect(modelSegments(renderer)).toEqual(["opus-4-6"])+ })++ it("shows a `local default` hint when modelName is null", () => {+ useBotsMock.mockReturnValue({ bots: [bot({ modelName: null })], isLoading: false })+ const renderer = render()+ expect(modelSegments(renderer)).toEqual(["local default"])+ })+})diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsxindex 531b6338e..84e4d3448 100644--- a/src/web/src/components/community/bots/bot-list.tsx+++ b/src/web/src/components/community/bots/bot-list.tsx@@ -5,7 +5,7 @@ import { useRouter, useSearchParams } from "next/navigation"import { ChevronLeft, Bot as BotIcon, Monitor, MoreVertical, Plus } from "lucide-react"import { toast } from "sonner"import { toastApiError } from "@/lib/api/client"-import { isPresenceOnline } from "@alook/shared"+import { isPresenceOnline, formatModelLabel } from "@alook/shared"import { machineName as resolveMachineName } from "@/lib/community/machine-name"import { Button } from "@/components/ui/button"import { Card } from "@/components/ui/card"@@ -267,6 +267,20 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {<span className="flex items-center gap-1.5 truncate text-xs text-muted-foreground"><ProviderLogo provider={bot.runtime} className="size-3.5 shrink-0" /><span className="truncate">{bot.runtime}</span>+ <span aria-hidden className="shrink-0">·</span>+ {formatModelLabel(bot.runtime, bot.modelName) ? (+ <span data-testid="bot-card-model" className="truncate font-mono">+ {formatModelLabel(bot.runtime, bot.modelName)}+ </span>+ ) : (+ <span+ data-testid="bot-card-model"+ className="truncate font-mono text-muted-foreground/70"+ title="No model set — uses the machine's local default"+ >+ local default+ </span>+ )}</span></div></div>diff --git a/src/web/src/components/community/bots/create-bot-sheet.test.ts b/src/web/src/components/community/bots/create-bot-sheet.test.tsindex 833dcdf80..eeb13a189 100644--- a/src/web/src/components/community/bots/create-bot-sheet.test.ts+++ b/src/web/src/components/community/bots/create-bot-sheet.test.ts@@ -134,6 +134,16 @@ vi.mock("./bot-form-fields", () => ({BotFormFields: () => React.createElement("div", { "data-mock": "form-fields" }),}))+// Capture ModelField's incoming `value` so we can assert the create sheet+// resets the model to null (Default) on a runtime change.+const modelFieldRenders: Array<{ runtime: string | null; value: string | null }> = []+vi.mock("./model-field", () => ({+ ModelField: ({ runtime, value }: { runtime: string | null; value: string | null }) => {+ modelFieldRenders.push({ runtime, value })+ return React.createElement("div", { "data-mock": "model-field", "data-value": value ?? "" })+ },+}))+vi.mock("@/components/provider-logo", () => ({ProviderLogo: () => React.createElement("span", { "data-mock": "provider-logo" }),}))@@ -255,6 +265,40 @@ describe("CreateBotSheet — auto-select defaults", () => {expect(checkedValue(renderer, "bot-runtime")).toBe(null)})+ it("resets the model to Default (null) when the user switches machine/runtime", () => {+ useMachinesMock.mockReturnValue({+ machines: [+ machine({+ id: "mac",+ status: "online",+ availableRuntimes: [+ { id: "claude", status: "healthy" },+ ] as unknown as CommunityMachineSummary["availableRuntimes"],+ }),+ machine({+ id: "server",+ status: "online",+ availableRuntimes: [+ { id: "codex", status: "healthy" },+ ] as unknown as CommunityMachineSummary["availableRuntimes"],+ }),+ ],+ })+ modelFieldRenders.length = 0+ const renderer = render()+ // Switching machine (which re-defaults the runtime) hands ModelField a+ // fresh runtime with value null.+ const serverRadio = renderer.root.findAll(+ (n) => n.type === "input" && n.props.name === "bot-machine" && n.props.value === "server",+ )[0]+ act(() => {+ serverRadio.props.onChange()+ })+ const last = modelFieldRenders.at(-1)!+ expect(last.runtime).toBe("codex")+ expect(last.value).toBeNull()+ })+it("re-defaults the runtime when the user switches to another machine", () => {useMachinesMock.mockReturnValue({machines: [diff --git a/src/web/src/components/community/bots/create-bot-sheet.tsx b/src/web/src/components/community/bots/create-bot-sheet.tsxindex 84ece7b18..4df13f340 100644--- a/src/web/src/components/community/bots/create-bot-sheet.tsx+++ b/src/web/src/components/community/bots/create-bot-sheet.tsx@@ -21,6 +21,7 @@ import { ProviderLogo } from "@/components/provider-logo"import { useMachines } from "@/hooks/community/use-machines"import { useCreateBot, useUploadBotAvatar } from "@/hooks/community/use-bots"import { BotFormFields } from "./bot-form-fields"+import { ModelField } from "./model-field"import {type BotCreateFieldErrors,hasBotCreateFieldErrors,@@ -82,6 +83,7 @@ export function CreateBotSheet({const [description, setDescription] = useState("")const [machineId, setMachineId] = useState<string>("")const [runtime, setRuntime] = useState<string>("")+ const [model, setModel] = useState<string | null>(null)const [fieldErrors, setFieldErrors] = useState<BotCreateFieldErrors>({})const [avatarDraft, setAvatarDraft] = useState<AvatarDraft>({kind: "procedural",@@ -106,6 +108,7 @@ export function CreateBotSheet({setDescription("")setMachineId("")setRuntime("")+ setModel(null)setFieldErrors({})}, [open])@@ -142,11 +145,17 @@ export function CreateBotSheet({setMachineId(id)const nextMachine = machines.find((m) => m.id === id)setRuntime(firstHealthyRuntimeId(normalizeRuntimes(nextMachine)))+ // A model id is runtime-specific; a machine switch can change the runtime,+ // so drop any selected model back to Default.+ setModel(null)setFieldErrors((prev) => ({ ...prev, machineId: undefined }))}function selectRuntime(id: string) {setRuntime(id)+ // Reset the model to Default — carrying (e.g.) gpt-5.4 across to claude+ // would be nonsense.+ setModel(null)setFieldErrors((prev) => ({ ...prev, runtime: undefined }))}@@ -162,6 +171,7 @@ export function CreateBotSheet({machineId,runtime,image: avatarDraft.kind === "procedural" ? avatarDraft.image : undefined,+ model,})// Bots don't have an id until creation resolves — the photo upload is// deferred until now so a cropped-then-cancelled dialog never uploads@@ -302,6 +312,9 @@ export function CreateBotSheet({{fieldErrors.runtime && (<p className="text-xs text-destructive">{fieldErrors.runtime}</p>)}+ {runtime && (+ <ModelField runtime={runtime} value={model} onChange={setModel} />+ )}</div>)}</SheetBody>diff --git a/src/web/src/components/community/bots/edit-bot-sheet.test.ts b/src/web/src/components/community/bots/edit-bot-sheet.test.tsnew file mode 100644index 000000000..e2b0a687b--- /dev/null+++ b/src/web/src/components/community/bots/edit-bot-sheet.test.ts@@ -0,0 +1,117 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import type { BotSummary } from "@/hooks/community/use-bots"++// Drive the edit sheet's submit() and assert the toast copy branches on the+// PATCH response (applied / deliveryError / plain-offline). The Sheet portals,+// so mock the shell + heavy children to passthroughs and stub the mutation.++const toastSuccess = vi.fn()+const toastError = vi.fn()+vi.mock("sonner", () => ({ toast: { success: (m: string) => toastSuccess(m), error: (m: string) => toastError(m) } }))+vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))++const updateMutateAsync = vi.fn()+vi.mock("@/hooks/community/use-bots", () => ({+ useUpdateBot: () => ({ mutateAsync: updateMutateAsync, isPending: false }),+ useUploadBotAvatar: () => ({ mutateAsync: vi.fn() }),+}))++vi.mock("@/components/ui/sheet", () => {+ const React = require("react")+ const pass = (name: string) =>+ function P({ children }: { children?: React.ReactNode }) {+ return React.createElement("div", { "data-mock": name }, children)+ }+ return {+ Sheet: pass("sheet"),+ SheetBody: pass("body"),+ SheetContent: pass("content"),+ SheetDescription: pass("desc"),+ SheetFooter: pass("footer"),+ SheetHeader: pass("header"),+ SheetTitle: pass("title"),+ }+})+vi.mock("@/components/ui/button", () => {+ const React = require("react")+ return { Button: ({ children, onClick }: any) => React.createElement("button", { onClick }, children) }+})+vi.mock("./bot-form-fields", () => ({ BotFormFields: () => require("react").createElement("div") }))+vi.mock("./model-field", () => {+ const React = require("react")+ // Expose the onChange so the test can set a new model, revealing modelChanged.+ return {+ ModelField: ({ onChange }: { onChange: (v: string | null) => void }) =>+ React.createElement("button", {+ "data-testid": "set-model",+ onClick: () => onChange("claude-sonnet-4-6"),+ }),+ }+})+vi.mock("@/components/avatar", () => ({+ isPhotoAvatarUrl: () => false,+}))+vi.mock("@/lib/avatar/seed-url", () => ({+ serializeBeamSeed: (s: string) => `beam:${s}`,+ parseBeamSeed: () => true,+}))++import { EditBotSheet } from "./edit-bot-sheet"++const BOT: BotSummary = {+ id: "b1",+ name: "Blake",+ description: "",+ image: "beam:b1",+ machineId: "mac1",+ runtime: "claude",+ modelName: null,+}++function renderAndSwitchModel(response: unknown): { save: () => void } {+ updateMutateAsync.mockResolvedValue(response)+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(EditBotSheet, { bot: BOT, open: true, onOpenChange: vi.fn() }),+ )+ })+ // Change the model via the mocked ModelField.+ const setModel = renderer.root.find((n) => n.props?.["data-testid"] === "set-model")+ act(() => setModel.props.onClick())+ // Find the Save button (last button rendered in the footer).+ const buttons = renderer.root.findAll((n) => n.type === "button" && !n.props["data-testid"])+ const save = buttons.at(-1)!+ return { save: () => act(() => { void save.props.onClick() }) }+}++describe("EditBotSheet — model switch toast copy", () => {+ beforeEach(() => {+ toastSuccess.mockReset()+ toastError.mockReset()+ updateMutateAsync.mockReset()+ })++ it("applied:true → 'Model switched to <new>'", async () => {+ const { save } = renderAndSwitchModel({ bot: { ...BOT, modelName: "claude-sonnet-4-6" }, applied: true, deliveryError: false })+ save()+ await Promise.resolve(); await Promise.resolve()+ expect(toastSuccess).toHaveBeenCalledWith("Model switched to claude-sonnet-4-6")+ })++ it("deliveryError:true → couldn't-reach copy", async () => {+ const { save } = renderAndSwitchModel({ bot: { ...BOT, modelName: "claude-sonnet-4-6" }, applied: false, deliveryError: true })+ save()+ await Promise.resolve(); await Promise.resolve()+ expect(toastSuccess).toHaveBeenCalledWith("Model saved — couldn't reach the bot just now; it'll apply on the next wake")+ })++ it("plain offline (applied:false, deliveryError:false) → applies-when-online copy", async () => {+ const { save } = renderAndSwitchModel({ bot: { ...BOT, modelName: "claude-sonnet-4-6" }, applied: false, deliveryError: false })+ save()+ await Promise.resolve(); await Promise.resolve()+ expect(toastSuccess).toHaveBeenCalledWith("Model saved — applies when the bot comes online")+ })+})diff --git a/src/web/src/components/community/bots/edit-bot-sheet.tsx b/src/web/src/components/community/bots/edit-bot-sheet.tsxindex d7772009b..326997404 100644--- a/src/web/src/components/community/bots/edit-bot-sheet.tsx+++ b/src/web/src/components/community/bots/edit-bot-sheet.tsx@@ -20,6 +20,8 @@ import {import { serializeBeamSeed, parseBeamSeed } from "@/lib/avatar/seed-url"import { useUpdateBot, useUploadBotAvatar, type BotSummary } from "@/hooks/community/use-bots"import { BotFormFields } from "./bot-form-fields"+import { ModelField } from "./model-field"+import { validateBotModel } from "./bot-form-validation"import { uniqueNamesGenerator, names } from "unique-names-generator"function draftFromBot(bot: BotSummary): AvatarDraft {@@ -45,6 +47,7 @@ export function EditBotSheet({}) {const [name, setName] = useState(bot?.name ?? "")const [description, setDescription] = useState(bot?.description ?? "")+ const [model, setModel] = useState<string | null>(bot?.modelName ?? null)const [nameError, setNameError] = useState<string | undefined>(undefined)const [avatarDraft, setAvatarDraft] = useState<AvatarDraft>(() =>bot ? draftFromBot(bot) : { kind: "procedural", image: serializeBeamSeed("initial") },@@ -63,6 +66,7 @@ export function EditBotSheet({syncedForRef.current = bot.idsetName(bot.name)setDescription(bot.description ?? "")+ setModel(bot.modelName ?? null)setAvatarDraft(draftFromBot(bot))setNameError(undefined)}, [open, bot])@@ -83,15 +87,24 @@ export function EditBotSheet({setNameError("Name is required")return}+ const modelError = validateBotModel(model)+ if (modelError) {+ toast.error(modelError)+ return+ }+ const modelChanged = model !== (bot.modelName ?? null)try {// Sequence matters — only attempt the avatar upload AFTER the// name/description update resolves, inside the same try block, so a// failed field update never triggers an upload.- await update.mutateAsync({+ const res = await update.mutateAsync({id: bot.id,name: name.trim(),description: description.trim() || undefined,image: avatarDraft.kind === "procedural" ? avatarDraft.image : undefined,+ // Only send `model` when it actually changed, so an unrelated edit+ // never triggers a stop-and-rewake.+ ...(modelChanged ? { model } : {}),})let avatarFailed = falseif (avatarDraft.kind === "photo" && avatarDraft.file) {@@ -102,7 +115,20 @@ export function EditBotSheet({toastApiError(e, "Bot updated, but the avatar photo failed to upload")}}- if (!avatarFailed) toast.success("Bot updated")+ if (!avatarFailed) {+ if (modelChanged) {+ const label = model ?? "the runtime default"+ if (res.applied) {+ toast.success(`Model switched to ${label}`)+ } else if (res.deliveryError) {+ toast.success("Model saved — couldn't reach the bot just now; it'll apply on the next wake")+ } else {+ toast.success("Model saved — applies when the bot comes online")+ }+ } else {+ toast.success("Bot updated")+ }+ }onOpenChange(false)} catch (e) {toastApiError(e, "Update failed")@@ -119,11 +145,11 @@ export function EditBotSheet({<SheetHeader><SheetTitle>Edit {bot?.name ?? "bot"}</SheetTitle><SheetDescription>- Name and description edits take effect on the bot's next wake trigger.+ Name and description edits take effect on the bot's next wake trigger. A model change applies right away if the bot is online.</SheetDescription></SheetHeader>- <SheetBody>+ <SheetBody className="flex flex-col gap-6"><BotFormFieldsavatarDraft={avatarDraft}onAvatarChange={setAvatarDraft}@@ -134,6 +160,9 @@ export function EditBotSheet({setDescription={setDescription}nameError={nameError}/>+ {bot && (+ <ModelField runtime={bot.runtime} value={model} onChange={setModel} />+ )}</SheetBody><SheetFooter>diff --git a/src/web/src/components/community/bots/model-field.test.ts b/src/web/src/components/community/bots/model-field.test.tsnew file mode 100644index 000000000..40c4f422a--- /dev/null+++ b/src/web/src/components/community/bots/model-field.test.ts@@ -0,0 +1,105 @@+import { describe, it, expect, vi } from "vitest"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"++// The Select is a base-ui component that portals its content into `document`,+// unavailable under this repo's node vitest env. Mock the Select shell to a+// passthrough that (a) records the current value and (b) exposes an onValueChange+// hook the test can drive, and render SelectItem children as plain nodes so we+// can assert which options exist.+const selectCalls: Array<{ value: string; onValueChange: (v: string | null) => void }> = []+vi.mock("@/components/ui/select", () => {+ const React = require("react")+ return {+ Select: ({ value, onValueChange, children }: any) => {+ selectCalls.push({ value, onValueChange })+ return React.createElement("div", { "data-mock": "select", "data-value": value }, children)+ },+ SelectTrigger: ({ children, ...props }: any) =>+ React.createElement("button", { "data-mock": "trigger", ...props }, children),+ SelectValue: ({ placeholder }: any) =>+ React.createElement("span", { "data-mock": "value" }, placeholder),+ SelectContent: ({ children }: any) => React.createElement("div", { "data-mock": "content" }, children),+ SelectItem: ({ value, children }: any) =>+ React.createElement("div", { "data-mock": "item", "data-value": value }, children),+ SelectSeparator: () => React.createElement("hr", { "data-mock": "separator" }),+ }+})++vi.mock("@/components/ui/label", () => {+ const React = require("react")+ return { Label: ({ children }: any) => React.createElement("label", {}, children) }+})+vi.mock("@/components/ui/input", () => {+ const React = require("react")+ return { Input: (props: any) => React.createElement("input", props) }+})++import { ModelField } from "./model-field"++function itemValues(renderer: TestRenderer.ReactTestRenderer): string[] {+ return renderer.root+ .findAll((n) => n.props?.["data-mock"] === "item")+ .map((n) => n.props["data-value"] as string)+}++function render(props: {+ runtime: string | null+ value: string | null+ onChange?: (v: string | null) => void+}): TestRenderer.ReactTestRenderer {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(ModelField, { onChange: vi.fn(), ...props }),+ )+ })+ return renderer+}++describe("ModelField", () => {+ it("renders Default + the catalog options + Custom… for claude", () => {+ const renderer = render({ runtime: "claude", value: null })+ const values = itemValues(renderer)+ expect(values).toContain("__default__")+ expect(values).toContain("claude-opus-4-6")+ expect(values).toContain("claude-sonnet-4-6")+ expect(values).toContain("__custom__")+ })++ it("renders only Default + Custom… for gemini (empty catalog)", () => {+ const values = itemValues(render({ runtime: "gemini", value: null }))+ expect(values).toEqual(["__default__", "__custom__"])+ })++ it("renders nothing for antigravity", () => {+ const renderer = render({ runtime: "antigravity", value: null })+ expect(renderer.root.findAll((n) => n.props?.["data-mock"] === "select")).toHaveLength(0)+ })++ it("selecting a catalog entry emits that id; selecting Default emits null", () => {+ const onChange = vi.fn()+ selectCalls.length = 0+ render({ runtime: "claude", value: null, onChange })+ const latest = selectCalls.at(-1)!+ act(() => latest.onValueChange("claude-opus-4-6"))+ expect(onChange).toHaveBeenLastCalledWith("claude-opus-4-6")+ act(() => selectCalls.at(-1)!.onValueChange("__default__"))+ expect(onChange).toHaveBeenLastCalledWith(null)+ })++ it("Custom… reveals the input; typing emits the raw string; clearing emits null", () => {+ const onChange = vi.fn()+ selectCalls.length = 0+ const renderer = render({ runtime: "claude", value: null, onChange })+ // No custom input until Custom… is chosen.+ expect(renderer.root.findAll((n) => n.props?.["data-testid"] === "bot-model-custom-input")).toHaveLength(0)+ act(() => selectCalls.at(-1)!.onValueChange("__custom__"))+ const input = renderer.root.find((n) => n.props?.["data-testid"] === "bot-model-custom-input")+ expect(input).toBeTruthy()+ act(() => input.props.onChange({ target: { value: "my-ft" } }))+ expect(onChange).toHaveBeenLastCalledWith("my-ft")+ act(() => input.props.onChange({ target: { value: "" } }))+ expect(onChange).toHaveBeenLastCalledWith(null)+ })+})diff --git a/src/web/src/components/community/bots/model-field.tsx b/src/web/src/components/community/bots/model-field.tsxnew file mode 100644index 000000000..a683ad35c--- /dev/null+++ b/src/web/src/components/community/bots/model-field.tsx@@ -0,0 +1,130 @@+"use client"++import { useEffect, useMemo, useState } from "react"+import {+ getRuntimeModelCatalog,+ runtimeSupportsModel,+ modelSelectState,+ modelNameFromSelect,+ MODEL_SELECT_DEFAULT,+ MODEL_SELECT_CUSTOM,+} from "@alook/shared"+import { Label } from "@/components/ui/label"+import { Input } from "@/components/ui/input"+import {+ Select,+ SelectTrigger,+ SelectValue,+ SelectContent,+ SelectItem,+ SelectSeparator,+} from "@/components/ui/select"++/**+ * Per-bot model picker. A `Select` over `[Default, ...catalog, Custom…]` plus a+ * conditionally-rendered custom text input. All model-name ↔ Select translation+ * goes through the shared `bot-model` helpers — never ad-hoc string logic.+ *+ * Renders nothing when the runtime doesn't honor a launch model (antigravity):+ * offering the choice would be a lie.+ *+ * The picker keeps its OWN Select/custom-text state rather than deriving purely+ * from `value`, because "Custom… selected with an empty name" and "Default" both+ * map to a `null` stored value — only local state can tell them apart, so the+ * text input stays revealed after choosing Custom…. The state re-seeds from+ * props whenever `value`/`runtime` change externally (runtime switch, a+ * different bot opening), detected by comparing the incoming value against what+ * local state currently resolves to — so it never clobbers on its own echo.+ */+export function ModelField({+ runtime,+ value,+ onChange,+ disabled,+}: {+ runtime: string | null+ value: string | null+ onChange: (v: string | null) => void+ disabled?: boolean+}) {+ const catalog = useMemo(() => getRuntimeModelCatalog(runtime), [runtime])+ const seed = useMemo(() => modelSelectState(runtime, value), [runtime, value])++ const [selectValue, setSelectValue] = useState(seed.selectValue)+ const [customName, setCustomName] = useState(seed.customName)++ // Re-seed on external value/runtime changes only. Our own onChange echoes back+ // as a `value` that already round-trips to local state, so this no-ops for it.+ useEffect(() => {+ const resolved = modelNameFromSelect(selectValue, customName)+ if (resolved !== (value ?? null)) {+ setSelectValue(seed.selectValue)+ setCustomName(seed.customName)+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [runtime, value])++ if (!runtimeSupportsModel(runtime)) return null++ const isCustom = selectValue === MODEL_SELECT_CUSTOM+ const defaultLabel = runtime ? `Default (${runtime}'s own default)` : "Default"++ // Base UI resolves the collapsed-trigger label from `items` (value → label).+ // Without it, SelectValue renders the raw value — fine for catalog ids+ // (value === label) but leaks the `__default__` / `__custom__` sentinels.+ // Same pattern as runtime-select.tsx.+ const items = [+ { value: MODEL_SELECT_DEFAULT, label: defaultLabel },+ ...catalog.models.map((m) => ({ value: m, label: m })),+ { value: MODEL_SELECT_CUSTOM, label: "Custom…" },+ ]++ return (+ <div className="flex flex-col gap-2">+ <Label className="text-xs text-muted-foreground">Model</Label>+ <Select+ items={items}+ value={selectValue}+ onValueChange={(next: string | null) => {+ // Base UI can emit `null` on clear — treat it as Default.+ const nextValue = next ?? MODEL_SELECT_DEFAULT+ setSelectValue(nextValue)+ // Custom… keeps the text field revealed even when empty (emits null+ // until something is typed); any other value maps through the helper.+ onChange(modelNameFromSelect(nextValue, customName))+ }}+ disabled={disabled}+ >+ <SelectTrigger+ data-testid="bot-model-select"+ className="w-full data-[size=default]:h-11 sm:data-[size=default]:h-8"+ >+ <SelectValue placeholder={defaultLabel} />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={MODEL_SELECT_DEFAULT}>{defaultLabel}</SelectItem>+ {catalog.models.map((m) => (+ <SelectItem key={m} value={m}>+ <span className="font-mono">{m}</span>+ </SelectItem>+ ))}+ <SelectSeparator />+ <SelectItem value={MODEL_SELECT_CUSTOM}>Custom…</SelectItem>+ </SelectContent>+ </Select>+ {isCustom && (+ <Input+ data-testid="bot-model-custom-input"+ value={customName}+ disabled={disabled}+ placeholder="e.g. claude-sonnet-4-6"+ onChange={(e) => {+ setCustomName(e.target.value)+ onChange(modelNameFromSelect(MODEL_SELECT_CUSTOM, e.target.value))+ }}+ className="h-11 font-mono sm:h-8"+ />+ )}+ </div>+ )+}diff --git a/src/web/src/components/ui/select.tsx b/src/web/src/components/ui/select.tsxindex 6f3d7d423..e599e8240 100644--- a/src/web/src/components/ui/select.tsx+++ b/src/web/src/components/ui/select.tsx@@ -83,7 +83,7 @@ function SelectContent({<SelectPrimitive.Popupdata-slot="select-content"data-align-trigger={alignItemWithTrigger}- className={cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}+ className={cn("thin-scrollbar relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}{...props}><SelectScrollUpButton />diff --git a/src/web/src/hooks/community/use-bot-audit-log.ts b/src/web/src/hooks/community/use-bot-audit-log.tsindex 65baf6b2c..f3e7c1e5a 100644--- a/src/web/src/hooks/community/use-bot-audit-log.ts+++ b/src/web/src/hooks/community/use-bot-audit-log.ts@@ -10,7 +10,7 @@ import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { useBotAuditEventsForBot } from "@/stores/community/ws"-export type AuditKind = "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset"+export type AuditKind = "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "model_changed" | "error"export type AuditEvent = {id: stringdiff --git a/src/web/src/hooks/community/use-bots.test.ts b/src/web/src/hooks/community/use-bots.test.tsindex ecf7b1a77..8f159d44f 100644--- a/src/web/src/hooks/community/use-bots.test.ts+++ b/src/web/src/hooks/community/use-bots.test.ts@@ -80,6 +80,23 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {expect(result.bot.description).toBe("new description")})+ it("useUpdateBot includes `model` in its request body when the input carries it", async () => {+ const { useUpdateBot } = await import("./use-bots")+ expect(typeof useUpdateBot).toBe("function")+ // Mirror the mutationFn's body construction: `model` is present when the+ // input object has the key (including explicit null), omitted otherwise.+ const buildBody = (input: { id: string; name?: string; model?: string | null }) =>+ JSON.stringify({+ name: input.name,+ description: undefined,+ image: undefined,+ ...("model" in input ? { model: input.model } : {}),+ })+ expect(JSON.parse(buildBody({ id: "b1", model: "claude-sonnet-4-6" })).model).toBe("claude-sonnet-4-6")+ expect("model" in JSON.parse(buildBody({ id: "b1", model: null }))).toBe(true)+ expect("model" in JSON.parse(buildBody({ id: "b1", name: "x" }))).toBe(false)+ })+it("useDeleteBot's mutationFn resolves with no body, so onSuccess must use the id mutation variable", async () => {apiFetchMock.mockResolvedValueOnce(undefined)const result = await apiFetchMock("/api/community/bots/bot_1", { method: "DELETE" })diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.tsindex f51ab1d91..3611e78f6 100644--- a/src/web/src/hooks/community/use-bots.ts+++ b/src/web/src/hooks/community/use-bots.ts@@ -11,6 +11,7 @@ export type BotSummary = {image: string | nullmachineId: stringruntime: string+ modelName: string | null}export type BotsResponse = { bots: BotSummary[] }@@ -30,6 +31,7 @@ export type CreateBotInput = {machineId: stringruntime: stringimage?: string+ model?: string | null}// Bot identity (name, image) is projected into friends() (self-bot rows) and@@ -63,17 +65,34 @@ export function useCreateBot() {})}+export type UpdateBotInput = {+ id: string+ name?: string+ description?: string+ image?: string | null+ // Explicit `null` clears a set model; `undefined` leaves it untouched.+ model?: string | null+}+export type UpdateBotResponse = {+ bot: BotSummary+ applied?: boolean+ deliveryError?: boolean+}+export function useUpdateBot() {const qc = useQueryClient()return useMutation({- mutationFn: (input: { id: string; name?: string; description?: string; image?: string | null }) =>- apiFetch<{ bot: BotSummary }>(`/api/community/bots/${input.id}`, {+ mutationFn: (input: UpdateBotInput) =>+ apiFetch<UpdateBotResponse>(`/api/community/bots/${input.id}`, {method: "PATCH",headers: { "Content-Type": "application/json" },body: JSON.stringify({name: input.name,description: input.description,image: input.image,+ // Omit `model` entirely when undefined so the PATCH doesn't send an+ // explicit key the server would read as "clear to default".+ ...("model" in input ? { model: input.model } : {}),}),}),onSuccess: (data) => invalidateBotSurfaces(qc, data.bot.id),diff --git a/src/web/src/lib/community/audit-log-payload.test.ts b/src/web/src/lib/community/audit-log-payload.test.tsindex e928f3c37..3f5d5182c 100644--- a/src/web/src/lib/community/audit-log-payload.test.ts+++ b/src/web/src/lib/community/audit-log-payload.test.ts@@ -49,6 +49,33 @@ describe("parseAuditLogPayload", () => {}expect(parseAuditLogPayload("wake_trigger", JSON.stringify(payload))).toEqual(payload)})+ it("parses a well-shaped model_changed payload (null-able from/to)", () => {+ expect(parseAuditLogPayload("model_changed", JSON.stringify({ from: null, to: "claude-opus-4-6" }))).toEqual({+ from: null,+ to: "claude-opus-4-6",+ })+ })+ it("parses an empty session_reset payload", () => {+ expect(parseAuditLogPayload("session_reset", JSON.stringify({}))).toEqual({})+ })+ it("parses a well-shaped error payload (so history rows keep their message, not the fallback)", () => {+ const payload = {+ scope: "handshake_timeout" as const,+ code: "handshake_timeout",+ message: "Launch failed — model claude-bogus never handshaked within 60s",+ model: "claude-bogus",+ }+ expect(parseAuditLogPayload("error", JSON.stringify(payload))).toEqual(payload)+ })+ it("parses an error payload with a null model", () => {+ const payload = { scope: "spawn" as const, code: "ENOENT", message: "not found", model: null }+ expect(parseAuditLogPayload("error", JSON.stringify(payload))).toEqual(payload)+ })+ it("returns null on an error payload with a bad scope", () => {+ expect(+ parseAuditLogPayload("error", JSON.stringify({ scope: "meltdown", code: "x", message: "m", model: null })),+ ).toBe(null)+ })it("returns null on invalid JSON — the whole page must not 500", () => {expect(parseAuditLogPayload("cli_invocation", "{not-json")).toBe(null)})diff --git a/src/web/src/lib/community/audit-log-payload.ts b/src/web/src/lib/community/audit-log-payload.tsindex 66a5631ed..c22af1624 100644--- a/src/web/src/lib/community/audit-log-payload.ts+++ b/src/web/src/lib/community/audit-log-payload.ts@@ -3,6 +3,9 @@ import {AuditLogToolCallPayloadSchema,AuditLogThinkingPayloadSchema,AuditLogWakeTriggerPayloadSchema,+ AuditLogModelChangedPayloadSchema,+ AuditLogSessionResetPayloadSchema,+ AuditLogErrorPayloadSchema,} from "@alook/shared"/**@@ -38,6 +41,18 @@ export function parseAuditLogPayload(const r = AuditLogWakeTriggerPayloadSchema.safeParse(json)return r.success ? r.data : null}+ case "model_changed": {+ const r = AuditLogModelChangedPayloadSchema.safeParse(json)+ return r.success ? r.data : null+ }+ case "session_reset": {+ const r = AuditLogSessionResetPayloadSchema.safeParse(json)+ return r.success ? r.data : null+ }+ case "error": {+ const r = AuditLogErrorPayloadSchema.safeParse(json)+ return r.success ? r.data : null+ }default:return null}diff --git a/src/web/src/lib/community/bot-push.test.ts b/src/web/src/lib/community/bot-push.test.tsindex ebb3568c0..416701e53 100644--- a/src/web/src/lib/community/bot-push.test.ts+++ b/src/web/src/lib/community/bot-push.test.ts@@ -5,7 +5,7 @@ vi.mock("@/lib/broadcast", () => ({wsDoFetch: (...a: unknown[]) => wsDoFetch(...a),}))-import { pushAgentResetToMachine } from "./bot-push"+import { pushAgentResetToMachine, pushAgentModelSwitchToMachine } from "./bot-push"const FAKE_ENV = { WS_DO_WORKER: {}, DEV_WS_DO_URL: undefined } as unknown as Env@@ -63,3 +63,51 @@ describe("pushAgentResetToMachine", () => {expect(result).toEqual({ sent: 0 })})})++describe("pushAgentModelSwitchToMachine", () => {+ beforeEach(() => {+ wsDoFetch.mockReset()+ })++ const CFG = {+ version: 1 as const,+ runtime: "claude",+ model: { kind: "named" as const, name: "claude-sonnet-4-6" },+ mode: { kind: "default" as const },+ }++ it("POSTs to /forward-agent-model-switch with the narrow body and returns { sent, deliveryError:false }", async () => {+ wsDoFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))+ const result = await pushAgentModelSwitchToMachine(FAKE_ENV, "machine-1", {+ agentId: "bot-1",+ config: CFG,+ launchId: "l-1",+ })+ expect(result).toEqual({ sent: 1, deliveryError: false })+ const [, path, init] = wsDoFetch.mock.calls[0]!+ expect(path).toBe("/community-machine/by-id/machine-1/forward-agent-model-switch")+ const body = JSON.parse(init.body as string)+ expect(body).toEqual({ agentId: "bot-1", config: CFG, launchId: "l-1" })+ expect(body.type).toBeUndefined()+ })++ it("distinguishes offline (sent:0, deliveryError:false) from a transport error (deliveryError:true)", async () => {+ // 200 with sent:0 → daemon just offline.+ wsDoFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 0 }), { status: 200 }))+ expect(+ await pushAgentModelSwitchToMachine(FAKE_ENV, "m", { agentId: "b", config: CFG, launchId: "l" }),+ ).toEqual({ sent: 0, deliveryError: false })++ // non-ok → transport error.+ wsDoFetch.mockResolvedValue(new Response("boom", { status: 503 }))+ expect(+ await pushAgentModelSwitchToMachine(FAKE_ENV, "m", { agentId: "b", config: CFG, launchId: "l" }),+ ).toEqual({ sent: 0, deliveryError: true })++ // thrown fetch → transport error.+ wsDoFetch.mockRejectedValue(new Error("network"))+ expect(+ await pushAgentModelSwitchToMachine(FAKE_ENV, "m", { agentId: "b", config: CFG, launchId: "l" }),+ ).toEqual({ sent: 0, deliveryError: true })+ })+})diff --git a/src/web/src/lib/community/bot-push.ts b/src/web/src/lib/community/bot-push.tsindex 995e1993d..e6144b81c 100644--- a/src/web/src/lib/community/bot-push.ts+++ b/src/web/src/lib/community/bot-push.ts@@ -103,3 +103,55 @@ export async function pushAgentResetToMachine(return { sent: 0 }}}++/**+ * Push an owner-triggered `agent:model_switch` to the machine's daemon over WS.+ *+ * Narrowly typed (only switch fields, no arbitrary HostCommand) so no caller+ * can smuggle a different command shape onto the wire. Unlike+ * `pushAgentResetToMachine`, this DISTINGUISHES a transport failure from "no+ * daemon connected": a non-ok response or a thrown fetch returns+ * `deliveryError: true`, while a 200 with `sent: 0` (daemon just offline)+ * returns `deliveryError: false`. The caller needs the difference to choose the+ * right toast copy — and to write no audit row in either case, since the audit+ * contract is confirmed-application (`sent > 0`).+ */+export async function pushAgentModelSwitchToMachine(+ env: Env,+ machineId: string,+ args: { agentId: string; config: RuntimeConfig; launchId: string },+): Promise<{ sent: number; deliveryError: boolean }> {+ const path = `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-agent-model-switch`+ const body = JSON.stringify({+ agentId: args.agentId,+ config: args.config,+ launchId: args.launchId,+ })+ try {+ const res = await wsDoFetch(+ env,+ path,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body,+ },+ { label: machineId, type: "agent:model_switch" },+ )+ if (!res.ok) {+ log.warn("agent:model_switch push non-ok", {+ machineId,+ status: res.status,+ })+ return { sent: 0, deliveryError: true }+ }+ const data = (await res.json()) as { sent?: number }+ return { sent: data.sent ?? 0, deliveryError: false }+ } catch (err) {+ log.warn("agent:model_switch push threw", {+ machineId,+ err: String(err),+ })+ return { sent: 0, deliveryError: true }+ }+}diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.tsindex 498d17aa2..8944c0073 100644--- a/src/web/src/stores/community/ws.ts+++ b/src/web/src/stores/community/ws.ts@@ -39,7 +39,7 @@ export const BOT_AUDIT_RING_MAX = 200export type BotAuditEventEntry = {id: stringbotId: string- kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset"+ kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "model_changed" | "error"payload: unknownsessionId?: string | nulllaunchId?: string | nulldiff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.tsindex ea78dac93..327e24e42 100644--- a/src/ws-do/src/index.test.ts+++ b/src/ws-do/src/index.test.ts@@ -153,6 +153,27 @@ describe("ws-do router", () => {const res = await handler.fetch(req, env as any)expect(res.status).toBe(503)})++ it("accepts kind: 'model_changed' (guards the AUDIT_KINDS allowlist)", async () => {+ doMock.stubFetch.mockResolvedValue(new Response("ok"))+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ botId: "bot_1",+ ownerUserId: "owner_1",+ id: "evt_m",+ kind: "model_changed",+ payload: { from: "claude-opus-4-6", to: "claude-sonnet-4-6" },+ createdAt: "2026-07-26T00:00:00.000Z",+ }),+ })+ const res = await handler.fetch(req, env as any)+ expect(res.status).toBe(204)+ const body = JSON.parse(await (doMock.stubFetch.mock.calls[0][0] as Request).text()) as Record<string, unknown>+ expect(body.kind).toBe("model_changed")+ expect(body.payload).toEqual({ from: "claude-opus-4-6", to: "claude-sonnet-4-6" })+ })})describe("POST /presence/users", () => {@@ -582,6 +603,70 @@ describe("ws-do router", () => {})})+ describe("POST /community-machine/by-id/:machineId/forward-agent-model-switch", () => {+ const validBody = {+ agentId: "bot-1",+ config: { version: 1, runtime: "claude", model: { kind: "named", name: "claude-sonnet-4-6" }, mode: { kind: "default" } },+ launchId: "l-1",+ }++ beforeEach(() => {+ mockGetActiveDoNamesForMachine.mockReset()+ mockGetActiveDoNamesForMachine.mockResolvedValue([])+ })++ it("forwards a { type:'agent:model_switch', ... } frame to each DO's /push and aggregates sent", async () => {+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {+ method: "POST",+ body: JSON.stringify(validBody),+ })+ const res = await handler.fetch(req, env as any)+ expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-abc")+ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request+ expect(stubReq.url).toBe("http://internal/push")+ const parsed = JSON.parse(await stubReq.text())+ expect(parsed).toEqual({ type: "agent:model_switch", agentId: "bot-1", config: validBody.config, launchId: "l-1" })+ // config.model passes through byte-identical (no inspection).+ expect(parsed.config.model).toEqual({ kind: "named", name: "claude-sonnet-4-6" })+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ sent: 1 })+ })++ it("rejects an extra top-level key with 400 (allowlist parity with reset)", async () => {+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {+ method: "POST",+ body: JSON.stringify({ ...validBody, sneaky: "x" }),+ })+ const res = await handler.fetch(req, env as any)+ expect(res.status).toBe(400)+ expect(doMock.stubFetch).not.toHaveBeenCalled()+ })++ it("rejects a missing/non-object config with 400", async () => {+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {+ method: "POST",+ body: JSON.stringify({ agentId: "bot-1", config: "nope", launchId: "l-1" }),+ })+ const res = await handler.fetch(req, env as any)+ expect(res.status).toBe(400)+ expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()+ expect(doMock.stubFetch).not.toHaveBeenCalled()+ })++ it("zero active doNames → { sent: 0 } without erroring", async () => {+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {+ method: "POST",+ body: JSON.stringify(validBody),+ })+ const res = await handler.fetch(req, env as any)+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ sent: 0 })+ expect(doMock.stubFetch).not.toHaveBeenCalled()+ })+ })+describe("force-close routing", () => {it("keys the DO by the do_name suffix", async () => {doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ closed: 1 })))diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.tsindex c781b6455..1f1b03b0b 100644--- a/src/ws-do/src/index.ts+++ b/src/ws-do/src/index.ts@@ -119,7 +119,7 @@ export default {// browser understands are broadcastable. An unknown `kind` reaches the// owner UI as an untyped row (bot-activity-row.tsx renders it verbatim),// so reject at the boundary instead.- const AUDIT_KINDS = new Set(["cli_invocation", "tool_call", "thinking", "wake_trigger", "session_reset"])+ const AUDIT_KINDS = new Set(["cli_invocation", "tool_call", "thinking", "wake_trigger", "session_reset", "model_changed"])if (!AUDIT_KINDS.has(b.kind)) {return new Response("invalid kind", { status: 400 })}@@ -404,6 +404,92 @@ export default {return Response.json({ sent: delivered })}+ // POST /community-machine/by-id/<machineId>/forward-agent-model-switch —+ // owner-triggered `agent:model_switch` push. A verbatim twin of+ // /forward-agent-reset (same narrow `{agentId, config, launchId}` allowlist,+ // same doName resolution, same `/push` fan-out and `{sent}` aggregation)+ // that only differs in the frame `type` — the daemon applies it by+ // preserving the session (see `AgentProcessManager.switchModel`). Callers+ // must use `pushAgentModelSwitchToMachine`.+ const forwardAgentModelSwitch = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-model-switch$/)+ if (forwardAgentModelSwitch && request.method === "POST") {+ const machineId = decodeURIComponent(forwardAgentModelSwitch[1])+ const reqLog = log.child({ traceId, machineId })+ reqLog.debug("forwarding agent:model_switch to machine")++ let payload: unknown+ try {+ payload = await request.json()+ } catch {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ if (!payload || typeof payload !== "object") {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ const raw = payload as Record<string, unknown>+ const allowedKeys = new Set(["agentId", "config", "launchId"])+ for (const key of Object.keys(raw)) {+ if (!allowedKeys.has(key)) {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ }+ const { agentId, config, launchId } = raw+ if (typeof agentId !== "string" || agentId.length === 0) {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ if (typeof launchId !== "string" || launchId.length === 0) {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ if (!config || typeof config !== "object") {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }++ let doNames: string[] = []+ try {+ const shared = await import("@alook/shared")+ const db = shared.createDb((env as unknown as { DB: D1Database }).DB)+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)+ } catch (err) {+ reqLog.error("failed to resolve machine doNames for agent model switch", { err })+ return Response.json({ error: "failed to resolve machine" }, { status: 503 })+ }+ if (doNames.length === 0) {+ return Response.json({ sent: 0 })+ }+ const frame = JSON.stringify({ type: "agent:model_switch", agentId, config, launchId })+ let delivered = 0+ let transientFailure = false+ for (const dn of doNames) {+ const doId = env.WS_DO.idFromName("community-machine:" + dn)+ const stub = env.WS_DO.get(doId)+ try {+ const res = await stub.fetch(+ new Request("http://internal/push", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: frame,+ }),+ )+ if (!res.ok) {+ transientFailure = true+ continue+ }+ const data = (await res.json()) as { sent?: unknown }+ if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {+ transientFailure = true+ continue+ }+ delivered += data.sent+ } catch {+ transientFailure = true+ }+ }+ if (delivered === 0 && transientFailure) {+ return Response.json({ error: "failed to forward agent model switch" }, { status: 503 })+ }+ return Response.json({ sent: delivered })+ }+// POST /community-machine/<doName>/force-close — disconnect a daemon by// its DO-name suffix (first 32 hex of the credential hash). Callers look// the suffix up from `community_machine_credential.do_name`.