Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

community(bot): support switching provider on bot edit

Gus233c6339889c
diff --git a/src/daemon/src/manager/managerSwitchModel.test.ts b/src/daemon/src/manager/managerSwitchModel.test.ts
index 27d251440..39dafecc5 100644
--- a/src/daemon/src/manager/managerSwitchModel.test.ts
+++ b/src/daemon/src/manager/managerSwitchModel.test.ts
@@ -58,7 +58,12 @@ const NAMED_CFG: RuntimeConfig = {
mode: { kind: "default" },
};
-function makeManager(opts: { logger?: Logger } = {}) {
+function makeManager(
+ opts: {
+ logger?: Logger;
+ onAgentSession?: (info: { agentId: string; sessionId: string; launchId: string }) => void;
+ } = {},
+) {
const spawns: Array<{ ctx: LaunchContext; prompt: string }> = [];
let session = fakeSession();
const sessions: FakeSession[] = [];
@@ -228,6 +233,49 @@ describe("AgentProcessManager.switchModel", () => {
expect(timelineCalls.some((c) => c.startsWith("forget:"))).toBe(false);
});
+ // #910 verify-by-test (Cecilia FINAL LOCK §7 / bot-provider-switch plan):
+ // model_changed re-home to agent_session only works if a forgetSession:false
+ // respawn still emits session_init AND threads the switch's launchId into
+ // onAgentSession. Driver-side: resume already yields session_init
+ // (codex.test "delivers the prompt on resume too"; cursor system/init;
+ // SdkRuntimeSession.emitEvents first-event). This pins the manager half.
+ it("after switchModel respawn, session_init emits onAgentSession with the switch launchId (not the prior wake's)", async () => {
+ const sessionsSeen: Array<{ agentId: string; sessionId: string; launchId: string }> = [];
+ const { mgr, getSession } = makeManager({
+ onAgentSession: (info) => sessionsSeen.push(info),
+ });
+ mgr.register("a1", { launchId: "wake-l1" });
+ mgr.deliver("a1", { seq: 1, text: "hi" });
+ getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-123" });
+ expect(sessionsSeen).toEqual([
+ { agentId: "a1", sessionId: "sess-123", launchId: "wake-l1" },
+ ]);
+
+ await mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "switch-l2", rewakePrompt: REWAKE });
+ getSession().fire("exit");
+ // Respawn is live; driver resume path emits session_init again (same or new id).
+ getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-123" });
+
+ expect(sessionsSeen).toHaveLength(2);
+ expect(sessionsSeen[1]).toEqual({
+ agentId: "a1",
+ sessionId: "sess-123",
+ launchId: "switch-l2",
+ });
+ });
+
+ it("idle switchModel cold-start: session_init emits onAgentSession with the switch launchId", async () => {
+ const sessionsSeen: Array<{ agentId: string; sessionId: string; launchId: string }> = [];
+ const { mgr, getSession } = makeManager({
+ onAgentSession: (info) => sessionsSeen.push(info),
+ });
+ await mgr.switchModel("a1", { runtimeConfig: NAMED_CFG, launchId: "switch-l1", rewakePrompt: REWAKE });
+ getSession().fire("runtime_event", { kind: "session_init", sessionId: "sess-new" });
+ expect(sessionsSeen).toEqual([
+ { agentId: "a1", sessionId: "sess-new", launchId: "switch-l1" },
+ ]);
+ });
+
// Convergence contract (B1): resetSession and switchModel now both route
// through the shared `restartAgent`; the ONLY behavioral difference is whether
// it calls forgetSession (reset does + writes its barrier; switch does not).
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index b32559d15..81091f2ab 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -529,7 +529,7 @@ export type CommunityBotAuditEvent = {
type: "community:bot.audit_event"
botId: string
id: string
- kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "error"
+ kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "provider_changed" | "error"
payload: unknown
sessionId?: string | null
launchId?: string | null
diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.ts
index b5592e3fa..3e78680be 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" | "nap" | "model_changed" | "error";
+ kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "provider_changed" | "error";
payload: string;
};
@@ -265,25 +265,36 @@ export async function insertBotAuditNap(
/**
* 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.
+ * `/c/me/bots`. Payload carries the full stored ids (`null` = the runtime's
+ * default). Written when the switched launch's `agent_session` lands; an
+ * undelivered or failed launch writes no row.
*/
export async function insertBotAuditModelChanged(
db: Database,
- data: { botId: string; actorId: string; from: string | null; to: string | null }
+ data: { botId: string; launchId: string; from: string | null; to: string | null }
): Promise<{ id: string; createdAt: string } | null> {
return insertBotActivityEventAndPrune(db, {
botId: data.botId,
sessionId: null,
- launchId: null,
+ launchId: data.launchId,
kind: "model_changed",
payload: JSON.stringify({ from: data.from, to: data.to }),
});
}
+export async function insertBotAuditProviderChanged(
+ db: Database,
+ data: { botId: string; launchId: string; from: string; to: string }
+): Promise<{ id: string; createdAt: string } | null> {
+ return insertBotActivityEventAndPrune(db, {
+ botId: data.botId,
+ sessionId: null,
+ launchId: data.launchId,
+ kind: "provider_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
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index ec45a2644..0700f8533 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -671,14 +671,40 @@ export async function updateBotModel(
return rows.length > 0;
}
+export async function updateBotRuntime(
+ db: Database,
+ botId: string,
+ ownerId: string,
+ runtime: 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({ runtime, modelName })
+ .where(inArray(communityBotBinding.userId, ownerScopedIds))
+ .returning({ userId: communityBotBinding.userId });
+ return rows.length > 0;
+}
+
/**
* Record a context refresh on a bot: stamp `lastRefreshContextAt`. Called at —
- * and ONLY at — the two audit chokepoints that record a refresh: `nap`
- * (self-initiated) and `session_reset` (owner). Keeping this the single write
+ * and ONLY at — the audit chokepoints that record a context refresh: `nap`,
+ * `session_reset`, and `provider_changed`. Keeping this the single write
* point is what makes the field a monotonic historical fact that never drifts
* from the audit log or the live FSM. Scoped to `isBot=true` and not
* soft-deleted; the caller has already authorized the action (runner-key for
- * nap, owner for reset), so no ownerUserId predicate here. `now` is injected so
+ * nap, owner for reset/switch), so no ownerUserId predicate here. `now` is injected so
* callers pass the same instant they wrote the audit row.
*/
export async function touchBotRefreshContext(
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index d5b459f43..949873c26 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -295,6 +295,7 @@ export {
AuditLogThinkingPayloadSchema,
AuditLogWakeTriggerPayloadSchema,
AuditLogModelChangedPayloadSchema,
+ AuditLogProviderChangedPayloadSchema,
AuditLogSessionResetPayloadSchema,
AuditLogNapPayloadSchema,
AuditLogErrorPayloadSchema,
@@ -380,6 +381,7 @@ export type {
BotAuditEvent,
BotAuditEventKind,
AuditLogWakeTriggerPayload,
+ AuditLogProviderChangedPayload,
} from "./schemas";
// Community agent CLI bridge contract — lifted from `src/daemon/src/server/contract.ts`.
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 61243f9ed..f28edd847 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1108,12 +1108,14 @@ export const CommunityBotPatchRequestSchema = z
// 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(),
+ runtime: z.string().trim().min(1).max(COMMUNITY_RUNTIME_ID_MAX).optional(),
})
.refine(
(v) =>
v.name !== undefined ||
v.description !== undefined ||
v.image !== undefined ||
+ v.runtime !== 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,
@@ -1426,6 +1428,12 @@ export const AuditLogModelChangedPayloadSchema = z.object({
});
export type AuditLogModelChangedPayload = z.infer<typeof AuditLogModelChangedPayloadSchema>;
+export const AuditLogProviderChangedPayloadSchema = z.object({
+ from: z.string().min(1),
+ to: z.string().min(1),
+});
+export type AuditLogProviderChangedPayload = z.infer<typeof AuditLogProviderChangedPayloadSchema>;
+
/**
* `error` payload — a launch/runtime failure the owner should see. Emitted by
* the daemon (never written server-side, unlike `model_changed`), so a bot
@@ -1455,6 +1463,7 @@ export const BotAuditEventSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("session_reset"), payload: AuditLogSessionResetPayloadSchema }),
z.object({ kind: z.literal("nap"), payload: AuditLogNapPayloadSchema }),
z.object({ kind: z.literal("model_changed"), payload: AuditLogModelChangedPayloadSchema }),
+ z.object({ kind: z.literal("provider_changed"), payload: AuditLogProviderChangedPayloadSchema }),
z.object({ kind: z.literal("error"), payload: AuditLogErrorPayloadSchema }),
]);
export type BotAuditEvent = z.infer<typeof BotAuditEventSchema>;
@@ -1467,6 +1476,7 @@ export const BotAuditEventKindSchema = z.enum([
"session_reset",
"nap",
"model_changed",
+ "provider_changed",
"error",
]);
export type BotAuditEventKind = z.infer<typeof BotAuditEventKindSchema>;
@@ -1484,4 +1494,3 @@ export const HostBotAuditEventFrameSchema = z.object({
event: BotAuditEventSchema,
});
export type HostBotAuditEventFrame = z.infer<typeof HostBotAuditEventFrameSchema>;
-
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.ts
index bdbd1568a..1ea2bc4ec 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
@@ -4,13 +4,15 @@ 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 mockUpdateBotRuntime = vi.fn()
+const mockGetMachineForOwner = vi.fn()
+const mockIsBotOnline = vi.fn()
const mockGetUserPublic = vi.fn()
const mockPushBotEventToMachine = vi.fn()
const mockPushAgentModelSwitchToMachine = vi.fn()
-const mockBroadcastToUser = vi.fn()
+const mockPushAgentProviderSwitchToMachine = vi.fn()
const mockLogAudit = vi.fn()
+const mockLogError = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -22,15 +24,22 @@ vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return {
...actual,
+ createLogger: () => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: (...a: unknown[]) => mockLogError(...a),
+ debug: vi.fn(),
+ }),
queries: {
communityBot: {
getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),
updateBot: (...a: unknown[]) => mockUpdateBot(...a),
updateBotModel: (...a: unknown[]) => mockUpdateBotModel(...a),
- getBotWakeContext: (...a: unknown[]) => mockGetBotWakeContext(...a),
+ updateBotRuntime: (...a: unknown[]) => mockUpdateBotRuntime(...a),
+ getMachineForOwner: (...a: unknown[]) => mockGetMachineForOwner(...a),
},
- communityBotAuditLog: {
- insertBotAuditModelChanged: (...a: unknown[]) => mockInsertBotAuditModelChanged(...a),
+ communityMachine: {
+ isBotOnline: (...a: unknown[]) => mockIsBotOnline(...a),
},
user: {
getUserPublic: (...a: unknown[]) => mockGetUserPublic(...a),
@@ -42,9 +51,10 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/community/bot-push", () => ({
pushBotEventToMachine: (...a: unknown[]) => mockPushBotEventToMachine(...a),
pushAgentModelSwitchToMachine: (...a: unknown[]) => mockPushAgentModelSwitchToMachine(...a),
+ pushAgentProviderSwitchToMachine: (...a: unknown[]) => mockPushAgentProviderSwitchToMachine(...a),
}))
vi.mock("@/lib/broadcast", () => ({
- broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),
+ broadcastToUser: vi.fn(),
}))
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: vi.fn(),
@@ -92,14 +102,18 @@ describe("PATCH /api/community/bots/[id]", () => {
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",
+ mockIsBotOnline.mockResolvedValue(true)
+ mockGetMachineForOwner.mockResolvedValue({
+ id: "mac1",
+ availableRuntimes: [
+ { id: "claude", status: "healthy" },
+ { id: "codex", status: "healthy" },
+ ],
})
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.
+ mockPushAgentProviderSwitchToMachine.mockResolvedValue({ sent: 1, deliveryError: false })
mockUpdateBotModel.mockResolvedValue(true)
+ mockUpdateBotRuntime.mockResolvedValue(true)
})
it("updates and pushes bot:updated to the daemon when the name changed", async () => {
@@ -117,8 +131,6 @@ describe("PATCH /api/community/bots/[id]", () => {
mockGetUserPublic.mockResolvedValue(null)
const res = await PATCH(patchReq({ name: "New" }), ctx)
expect(res.status).toBe(500)
- // The row must NOT have been mutated — otherwise a retry sees no diff and
- // never pushes, leaving the daemon prompt permanently stale.
expect(mockUpdateBot).not.toHaveBeenCalled()
expect(mockPushBotEventToMachine).not.toHaveBeenCalled()
})
@@ -132,82 +144,149 @@ describe("PATCH /api/community/bots/[id]", () => {
expect(mockUpdateBot).toHaveBeenCalled()
})
- it("changed model on a wake-ready bot: writes column, pushes new model, applied:true, one audit row", async () => {
+ // Melisa #1294 push-first: push then D1 write; offline/sent===0 never touch D1 runtime columns.
+ it("changed model online: push-first then writes column; from/to on push; no dispatch-time audit", 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",
+ from: null,
+ to: "claude-sonnet-4-6",
config: expect.objectContaining({ model: { kind: "named", name: "claude-sonnet-4-6" } }),
}),
)
- expect(mockInsertBotAuditModelChanged).toHaveBeenCalledTimes(1)
- expect(mockInsertBotAuditModelChanged).toHaveBeenCalledWith(
+ expect(mockUpdateBotModel).toHaveBeenCalledWith(expect.anything(), "b1", "u1", "claude-sonnet-4-6")
+ expect(mockPushAgentModelSwitchToMachine.mock.invocationCallOrder[0]!).toBeLessThan(
+ mockUpdateBotModel.mock.invocationCallOrder[0]!,
+ )
+ expect(mockPushAgentProviderSwitchToMachine).not.toHaveBeenCalled()
+ })
+
+ it("changed provider online: push provider_switch first, then updateBotRuntime (clears model)", async () => {
+ mockUpdateBot.mockResolvedValue({
+ id: "b1", name: "Old", discriminator: "0001", description: "old desc", image: null,
+ })
+ const res = await PATCH(patchReq({ runtime: "codex" }), ctx)
+ expect(res.status).toBe(200)
+ const body = (await res.json()) as { applied: boolean; bot: { runtime: string; modelName: string | null } }
+ expect(body.applied).toBe(true)
+ expect(body.bot.runtime).toBe("codex")
+ expect(body.bot.modelName).toBe(null)
+ expect(mockPushAgentProviderSwitchToMachine).toHaveBeenCalledWith(
expect.anything(),
- expect.objectContaining({ botId: "b1", from: null, to: "claude-sonnet-4-6" }),
+ "mac1",
+ expect.objectContaining({
+ agentId: "b1",
+ from: "claude",
+ to: "codex",
+ config: expect.objectContaining({ runtime: "codex" }),
+ }),
)
+ expect(mockUpdateBotRuntime).toHaveBeenCalledWith(expect.anything(), "b1", "u1", "codex", null)
+ expect(mockPushAgentProviderSwitchToMachine.mock.invocationCallOrder[0]!).toBeLessThan(
+ mockUpdateBotRuntime.mock.invocationCallOrder[0]!,
+ )
+ expect(mockPushAgentModelSwitchToMachine).not.toHaveBeenCalled()
})
- it("changed model, daemon disconnected (sent 0): 200, applied:false, deliveryError:false, no audit", async () => {
+ it("changed model, daemon offline (isBotOnline false): 409, no column write, no push", async () => {
+ mockIsBotOnline.mockResolvedValue(false)
+ const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)
+ expect(res.status).toBe(409)
+ expect(mockUpdateBotModel).not.toHaveBeenCalled()
+ expect(mockUpdateBotRuntime).not.toHaveBeenCalled()
+ expect(mockPushAgentModelSwitchToMachine).not.toHaveBeenCalled()
+ })
+
+ it("changed provider, daemon offline: 409, zero D1 write, no push", async () => {
+ mockIsBotOnline.mockResolvedValue(false)
+ const res = await PATCH(patchReq({ runtime: "codex" }), ctx)
+ expect(res.status).toBe(409)
+ expect(mockUpdateBotRuntime).not.toHaveBeenCalled()
+ expect(mockPushAgentProviderSwitchToMachine).not.toHaveBeenCalled()
+ })
+
+ it("changed model, push sent===0: 409, zero D1 runtime write (no soft-save, no rollback)", async () => {
+ mockGetBotOwnedBy.mockResolvedValue({
+ id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1",
+ runtime: "claude", modelName: "claude-opus-4-6",
+ })
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()
+ expect(res.status).toBe(409)
+ expect(mockUpdateBotModel).not.toHaveBeenCalled()
+ })
+
+ it("changed provider, push sent===0: 409, zero D1 runtime write", async () => {
+ mockGetBotOwnedBy.mockResolvedValue({
+ id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1",
+ runtime: "claude", modelName: "claude-opus-4-6",
+ })
+ mockPushAgentProviderSwitchToMachine.mockResolvedValue({ sent: 0, deliveryError: false })
+ const res = await PATCH(patchReq({ runtime: "codex" }), ctx)
+ expect(res.status).toBe(409)
+ expect(mockUpdateBotRuntime).not.toHaveBeenCalled()
})
- it("changed model, push transport error: 200, applied:false, deliveryError:true, no audit", async () => {
+ it("changed model, push transport error: 503, zero D1 runtime write", async () => {
+ mockGetBotOwnedBy.mockResolvedValue({
+ id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1",
+ runtime: "claude", modelName: "claude-opus-4-6",
+ })
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()
+ expect(res.status).toBe(503)
+ expect(mockUpdateBotModel).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" })
+ // Melisa #1294 / Cecilia #1295: push succeeded but D1 persist failed → explicit
+ // log.error + 5xx (no silent divergence, UI must not toast success).
+ it("changed model, sent>0 but D1 write throws: log.error(bot_runtime_switch_persist_failed) + 500", async () => {
+ mockUpdateBotModel.mockRejectedValue(new Error("d1 down"))
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()
+ expect(res.status).toBe(500)
+ expect(mockPushAgentModelSwitchToMachine).toHaveBeenCalled()
+ expect(mockLogError).toHaveBeenCalledWith(
+ "bot_runtime_switch_persist_failed",
+ expect.objectContaining({ botId: "b1", persistErr: expect.stringContaining("d1 down") }),
+ )
+ })
+
+ it("changed provider, sent>0 but D1 write throws: log.error(bot_runtime_switch_persist_failed) + 500", async () => {
+ mockUpdateBotRuntime.mockRejectedValue(new Error("d1 down"))
+ const res = await PATCH(patchReq({ runtime: "codex" }), ctx)
+ expect(res.status).toBe(500)
+ expect(mockPushAgentProviderSwitchToMachine).toHaveBeenCalled()
+ expect(mockLogError).toHaveBeenCalledWith(
+ "bot_runtime_switch_persist_failed",
+ expect.objectContaining({ botId: "b1" }),
+ )
})
- 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.
+ it("model PATCH on a bot with no binding row after successful push → 500 + persist_failed log", async () => {
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()
+ expect(res.status).toBe(500)
+ expect(mockPushAgentModelSwitchToMachine).toHaveBeenCalled()
+ expect(mockLogError).toHaveBeenCalledWith(
+ "bot_runtime_switch_persist_failed",
+ expect.objectContaining({ botId: "b1" }),
+ )
})
- it("same model / omitted model: no push, no audit, column untouched", async () => {
- // same: before.modelName is null, body sends null
+ it("same model / omitted model: no push, column untouched", async () => {
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 })
@@ -217,24 +296,24 @@ describe("PATCH /api/community/bots/[id]", () => {
expect(mockUpdateBotModel).not.toHaveBeenCalled()
})
- it("model:null on a bot that had one: clears column, pushes default, audits {from, to:null}", async () => {
+ it("model:null on a bot that had one: push default with from/to, then clear column", 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" })
+ mockUpdateBot.mockResolvedValue({ id: "b1", name: "Old", discriminator: "0001", description: "d", image: null })
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 }),
+ expect.objectContaining({
+ from: "claude-opus-4-6",
+ to: null,
+ config: expect.objectContaining({ model: { kind: "default" } }),
+ }),
)
+ expect(mockUpdateBotModel).toHaveBeenCalledWith(expect.anything(), "b1", "u1", null)
})
- it("name AND model changed: both bot:updated and agent:model_switch pushed; audit changedFields includes both", async () => {
+ it("name AND model changed: both bot:updated and model_switch pushed; fields include 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" }))
@@ -245,20 +324,17 @@ describe("PATCH /api/community/bots/[id]", () => {
expect(fields).toContain("model")
})
- it("model on an antigravity bot → 400; runtime null → allowed", async () => {
+ it("model on an antigravity bot → 400", 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)
+ const 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()
+ it("runtime not on machine → 400", async () => {
+ const res = await PATCH(patchReq({ runtime: "gemini" }), ctx)
+ expect(res.status).toBe(400)
+ expect(mockUpdateBotRuntime).not.toHaveBeenCalled()
+ expect(mockPushAgentProviderSwitchToMachine).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.ts
index adba9a25d..619fb8baf 100644
--- a/src/web/src/app/api/community/bots/[id]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.ts
@@ -9,15 +9,21 @@ import {
resolveModelConfig,
runtimeSupportsModel,
formatHandle,
+ createLogger,
} 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, pushAgentModelSwitchToMachine } from "@/lib/community/bot-push"
-import { broadcastToUser } from "@/lib/broadcast"
+import {
+ pushBotEventToMachine,
+ pushAgentModelSwitchToMachine,
+ pushAgentProviderSwitchToMachine,
+} from "@/lib/community/bot-push"
import { fanOutToServerMembers } from "@/lib/community/fanout"
+const log = createLogger({ service: "community-bot-update" })
+
export const GET = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
@@ -38,16 +44,33 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
const nameChanged = body.name !== undefined && body.name !== before.name
const 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 runtimeChanged = body.runtime !== undefined && body.runtime !== before.runtime
+ const targetRuntime = body.runtime ?? before.runtime
+ const nextModel = body.model !== undefined
+ ? (body.model ?? null)
+ : runtimeChanged
+ ? null
+ : undefined
const modelChanged = nextModel !== undefined && nextModel !== (before.modelName ?? null)
+ const restartChanged = runtimeChanged || modelChanged
- // 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)
+ if (restartChanged) {
+ if (!before.machineId || !targetRuntime || !before.runtime) {
+ return writeError("bot has no active runtime binding", 409)
+ }
+ if (!(await queries.communityMachine.isBotOnline(db, id))) {
+ return writeError("bot is offline — bring it online before changing provider or model", 409)
+ }
+ const machine = await queries.communityBot.getMachineForOwner(db, before.machineId, ctx.userId)
+ if (!machine) return writeError("machine not found", 404)
+ const runtime = machine.availableRuntimes.find((item) => item.id === targetRuntime)
+ if (!runtime) return writeError(`runtime ${targetRuntime} not available on this machine`, 400)
+ if (runtime.status === "unhealthy") {
+ return writeError(`runtime ${targetRuntime} is currently unavailable on this machine`, 400)
+ }
+ if (nextModel !== null && nextModel !== undefined && !runtimeSupportsModel(targetRuntime)) {
+ return writeError(`runtime ${targetRuntime} 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,
@@ -81,63 +104,56 @@ 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)
+ if (restartChanged && before.machineId && before.runtime && targetRuntime) {
+ const storedModel = nextModel !== undefined ? nextModel : (before.modelName ?? null)
+ const config = makeRuntimeConfig({
+ runtime: targetRuntime,
+ model: resolveModelConfig(targetRuntime, storedModel),
+ agentName: updated.name,
+ agentHandle: `@${formatHandle(updated.name, updated.discriminator)}`,
+ })
+ const launchId = nanoid()
+ const result = runtimeChanged
+ ? await pushAgentProviderSwitchToMachine(ctx.env, before.machineId, {
+ agentId: id,
+ config,
+ launchId,
+ from: before.runtime,
+ to: targetRuntime,
+ })
+ : await pushAgentModelSwitchToMachine(ctx.env, before.machineId, {
+ agentId: id,
+ config,
+ launchId,
+ from: before.modelName ?? null,
+ to: storedModel,
+ })
+ deliveryError = result.deliveryError
+ applied = result.sent > 0
+ if (!applied) {
+ return deliveryError
+ ? writeError("failed to reach the bot daemon", 503)
+ : writeError("bot is offline — bring it online before changing provider or 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(),
+ try {
+ const wrote = runtimeChanged
+ ? await queries.communityBot.updateBotRuntime(db, id, ctx.userId, targetRuntime, storedModel)
+ : await queries.communityBot.updateBotModel(db, id, ctx.userId, storedModel)
+ if (!wrote) throw new Error("runtime binding disappeared before persistence")
+ } catch (persistErr) {
+ log.error("bot_runtime_switch_persist_failed", {
+ botId: id,
+ machineId: before.machineId,
+ runtimeFrom: before.runtime,
+ runtimeTo: targetRuntime,
+ modelFrom: before.modelName ?? null,
+ modelTo: storedModel,
+ persistErr: String(persistErr),
})
- 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.
- }
- }
- }
+ return writeError("bot switched, but its runtime binding failed to persist", 500)
}
}
@@ -145,6 +161,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
if (body.name !== undefined) changedFields.push("name")
if (body.description !== undefined) changedFields.push("description")
if (body.image !== undefined) changedFields.push("image")
+ if (runtimeChanged) changedFields.push("runtime")
if (modelChanged) changedFields.push("model")
logAudit(db, {
serverId: null,
@@ -161,6 +178,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
name: updated.name,
description: updated.description,
image: updated.image,
+ runtime: targetRuntime,
modelName: nextModel !== undefined ? nextModel : (before.modelName ?? null),
},
applied,
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.ts
index e4dfd2d7d..e984a0550 100644
--- a/src/web/src/components/community/bots/bot-activity-row.test.ts
+++ b/src/web/src/components/community/bots/bot-activity-row.test.ts
@@ -61,6 +61,26 @@ describe("BotActivityRow — model_changed", () => {
})
})
+describe("BotActivityRow — provider_changed", () => {
+ function providerRowText(renderer: TestRenderer.ReactTestRenderer): string {
+ return rowText(renderer, "bot-activity-event-provider_changed")
+ }
+
+ it("renders runtime ids from → to", () => {
+ const renderer = render({
+ id: "e5",
+ kind: "provider_changed",
+ payload: { from: "claude", to: "codex" },
+ sessionId: null,
+ launchId: null,
+ createdAt: "2026-07-26T00:00:00.000Z",
+ })
+ expect(providerRowText(renderer)).toContain("claude")
+ expect(providerRowText(renderer)).toContain("→")
+ expect(providerRowText(renderer)).toContain("codex")
+ })
+})
+
describe("BotActivityRow — error", () => {
it("renders the failure message plus the code · model detail", () => {
const renderer = render({
diff --git a/src/web/src/components/community/bots/bot-activity-row.tsx b/src/web/src/components/community/bots/bot-activity-row.tsx
index 40ac0c015..3852a2972 100644
--- a/src/web/src/components/community/bots/bot-activity-row.tsx
+++ b/src/web/src/components/community/bots/bot-activity-row.tsx
@@ -59,6 +59,7 @@ function kindMeta(kind: AuditKind): { label: string; tone: string } {
if (kind === "session_reset") return { label: "reset", tone: "text-foreground/70" }
if (kind === "nap") return { label: "nap", tone: "text-foreground/70" }
if (kind === "model_changed") return { label: "model", tone: "text-foreground/70" }
+ if (kind === "provider_changed") return { label: "provider", tone: "text-foreground/70" }
if (kind === "error") return { label: "err", tone: "text-destructive" }
return { label: "think", tone: "text-muted-foreground/70" }
}
@@ -141,6 +142,17 @@ function RowBody({
</div>
)
}
+ if (event.kind === "provider_changed") {
+ const p = event.payload as { from?: string; to?: string } | null
+ return (
+ <div
+ data-testid="bot-activity-event-provider_changed"
+ className="truncate font-mono text-[13px] text-foreground"
+ >
+ {p?.from ?? "?"} <span className="text-muted-foreground/60">→</span> {p?.to ?? "?"}
+ </div>
+ )
+ }
if (event.kind === "error") {
const p = event.payload as {
scope?: string
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.ts
index e2b0a687b..a0a5931ed 100644
--- a/src/web/src/components/community/bots/edit-bot-sheet.test.ts
+++ b/src/web/src/components/community/bots/edit-bot-sheet.test.ts
@@ -3,14 +3,23 @@ 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.
+// Online-only UI contract (Ruthann #1274/#1280 / Shelly gate):
+// - provider picker is `bot-provider-picker` radiogroup (same shape as create)
+// - provider change → AlertDialog first; confirm then PATCH; dispatched toast
+// - model switch → "Model switch to … dispatched" only after PATCH succeeds
+// - no offline-saved / next-wake toast copy
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() }))
+vi.mock("sonner", () => ({
+ toast: {
+ success: (m: string) => toastSuccess(m),
+ error: (m: string) => toastError(m),
+ },
+}))
+
+const toastApiError = vi.fn()
+vi.mock("@/lib/api/client", () => ({ toastApiError: (...a: unknown[]) => toastApiError(...a) }))
const updateMutateAsync = vi.fn()
vi.mock("@/hooks/community/use-bots", () => ({
@@ -18,6 +27,23 @@ vi.mock("@/hooks/community/use-bots", () => ({
useUploadBotAvatar: () => ({ mutateAsync: vi.fn() }),
}))
+const useMachinesMock = vi.fn()
+vi.mock("@/hooks/community/use-machines", () => ({
+ useMachines: () => useMachinesMock(),
+}))
+
+const HEALTHY_MACHINES = {
+ machines: [
+ {
+ id: "mac1",
+ availableRuntimes: [
+ { id: "claude", status: "healthy" },
+ { id: "codex", status: "healthy" },
+ ],
+ },
+ ],
+}
+
vi.mock("@/components/ui/sheet", () => {
const React = require("react")
const pass = (name: string) =>
@@ -34,14 +60,70 @@ vi.mock("@/components/ui/sheet", () => {
SheetTitle: pass("title"),
}
})
+
vi.mock("@/components/ui/button", () => {
const React = require("react")
- return { Button: ({ children, onClick }: any) => React.createElement("button", { onClick }, children) }
+ return {
+ Button: ({ children, onClick, disabled }: any) =>
+ React.createElement("button", { onClick, disabled }, children),
+ }
})
-vi.mock("./bot-form-fields", () => ({ BotFormFields: () => require("react").createElement("div") }))
+
+vi.mock("@/components/ui/label", () => ({
+ Label: ({ children }: { children?: React.ReactNode }) =>
+ require("react").createElement("label", null, children),
+}))
+
+vi.mock("@/components/ui/alert-dialog", () => {
+ const React = require("react")
+ return {
+ AlertDialog: ({
+ open,
+ children,
+ }: {
+ open: boolean
+ children?: React.ReactNode
+ }) => (open ? React.createElement("div", { "data-testid": "provider-confirm" }, children) : null),
+ AlertDialogContent: ({ children }: { children?: React.ReactNode }) =>
+ React.createElement("div", null, children),
+ AlertDialogHeader: ({ children }: { children?: React.ReactNode }) =>
+ React.createElement("div", null, children),
+ AlertDialogFooter: ({ children }: { children?: React.ReactNode }) =>
+ React.createElement("div", null, children),
+ AlertDialogTitle: ({ children }: { children?: React.ReactNode }) =>
+ React.createElement("h2", null, children),
+ AlertDialogDescription: ({ children }: { children?: React.ReactNode }) =>
+ React.createElement("p", null, children),
+ AlertDialogCancel: ({ children }: { children?: React.ReactNode }) =>
+ React.createElement("button", { "data-testid": "provider-cancel" }, children),
+ AlertDialogAction: ({
+ children,
+ onClick,
+ }: {
+ children?: React.ReactNode
+ onClick?: () => void
+ }) =>
+ React.createElement(
+ "button",
+ { "data-testid": "provider-confirm-action", onClick },
+ children,
+ ),
+ }
+})
+
+vi.mock("@/components/provider-logo", () => ({
+ ProviderLogo: () => require("react").createElement("span", { "data-mock": "provider-logo" }),
+}))
+
+vi.mock("@/lib/utils", () => ({
+ cn: (...a: unknown[]) => a.filter(Boolean).join(" "),
+}))
+
+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", {
@@ -68,50 +150,165 @@ const BOT: BotSummary = {
machineId: "mac1",
runtime: "claude",
modelName: null,
+ lastRefreshContextAt: null,
+ dailyActivity: [],
}
-function renderAndSwitchModel(response: unknown): { save: () => void } {
- updateMutateAsync.mockResolvedValue(response)
+function renderSheet(bot: BotSummary = BOT): TestRenderer.ReactTestRenderer {
let renderer!: TestRenderer.ReactTestRenderer
act(() => {
renderer = TestRenderer.create(
- React.createElement(EditBotSheet, { bot: BOT, open: true, onOpenChange: vi.fn() }),
+ React.createElement(EditBotSheet, { 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() }) }
+ return renderer
+}
+
+function saveButton(renderer: TestRenderer.ReactTestRenderer) {
+ return renderer.root.find(
+ (n) => n.type === "button" && !n.props["data-testid"] && n.props.children === "Save",
+ )
}
-describe("EditBotSheet — model switch toast copy", () => {
+function pickRuntime(renderer: TestRenderer.ReactTestRenderer, value: string) {
+ const radio = renderer.root.find(
+ (n) => n.type === "input" && n.props.name === "edit-bot-runtime" && n.props.value === value,
+ )
+ act(() => radio.props.onChange({ target: { value } }))
+}
+
+async function flush() {
+ await act(async () => {
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+}
+
+function runtimeRadio(renderer: TestRenderer.ReactTestRenderer, value: string) {
+ return renderer.root.find(
+ (n) => n.type === "input" && n.props.name === "edit-bot-runtime" && n.props.value === value,
+ )
+}
+
+describe("EditBotSheet — model switch toast (online-only)", () => {
+ beforeEach(() => {
+ toastSuccess.mockReset()
+ toastError.mockReset()
+ toastApiError.mockReset()
+ updateMutateAsync.mockReset()
+ useMachinesMock.mockReturnValue(HEALTHY_MACHINES)
+ })
+
+ it("PATCH success → 'Model switch to <new> dispatched'", async () => {
+ updateMutateAsync.mockResolvedValue({ bot: { ...BOT, modelName: "claude-sonnet-4-6" } })
+ const renderer = renderSheet()
+ expect(renderer.root.find((n) => n.props?.["data-testid"] === "bot-provider-picker")).toBeTruthy()
+ act(() => renderer.root.find((n) => n.props?.["data-testid"] === "set-model").props.onClick())
+ act(() => {
+ void saveButton(renderer).props.onClick()
+ })
+ await flush()
+ expect(updateMutateAsync).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "b1", model: "claude-sonnet-4-6" }),
+ )
+ expect(toastSuccess).toHaveBeenCalledWith("Model switch to claude-sonnet-4-6 dispatched")
+ expect(toastSuccess.mock.calls.join(" ")).not.toMatch(/offline|next wake|applies when/i)
+ })
+
+ it("PATCH failure → toastApiError, no success toast", async () => {
+ updateMutateAsync.mockRejectedValue(new Error("Bot offline"))
+ const renderer = renderSheet()
+ act(() => renderer.root.find((n) => n.props?.["data-testid"] === "set-model").props.onClick())
+ act(() => {
+ void saveButton(renderer).props.onClick()
+ })
+ await flush()
+ expect(toastSuccess).not.toHaveBeenCalled()
+ expect(toastApiError).toHaveBeenCalled()
+ })
+})
+
+describe("EditBotSheet — provider switch AlertDialog + toast", () => {
beforeEach(() => {
toastSuccess.mockReset()
toastError.mockReset()
+ toastApiError.mockReset()
updateMutateAsync.mockReset()
+ useMachinesMock.mockReturnValue(HEALTHY_MACHINES)
})
- 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("Save with new provider opens confirm dialog and does not PATCH yet", () => {
+ const renderer = renderSheet()
+ pickRuntime(renderer, "codex")
+ act(() => {
+ void saveButton(renderer).props.onClick()
+ })
+ expect(renderer.root.findAll((n) => n.props?.["data-testid"] === "provider-confirm")).toHaveLength(
+ 1,
+ )
+ expect(updateMutateAsync).not.toHaveBeenCalled()
+ expect(toastSuccess).not.toHaveBeenCalled()
})
- 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("confirm → PATCH with runtime + cleared model, then dispatched toast", async () => {
+ updateMutateAsync.mockResolvedValue({ bot: { ...BOT, runtime: "codex", modelName: null } })
+ const renderer = renderSheet({ ...BOT, modelName: "claude-sonnet-4-6" })
+ pickRuntime(renderer, "codex")
+ act(() => {
+ void saveButton(renderer).props.onClick()
+ })
+ act(() =>
+ renderer.root
+ .find((n) => n.props?.["data-testid"] === "provider-confirm-action")
+ .props.onClick(),
+ )
+ await flush()
+ expect(updateMutateAsync).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "b1",
+ runtime: "codex",
+ model: null,
+ }),
+ )
+ expect(toastSuccess).toHaveBeenCalledWith("Provider switch to codex dispatched")
+ expect(toastSuccess.mock.calls.join(" ")).not.toMatch(/offline|next wake|applies when/i)
+ })
+
+ it("cancel dialog → no PATCH", () => {
+ const renderer = renderSheet()
+ pickRuntime(renderer, "codex")
+ act(() => {
+ void saveButton(renderer).props.onClick()
+ })
+ expect(renderer.root.find((n) => n.props?.["data-testid"] === "provider-cancel")).toBeTruthy()
+ expect(updateMutateAsync).not.toHaveBeenCalled()
+ })
+})
+
+describe("EditBotSheet — current unhealthy runtime stays selectable (Alli #1287 / Ruthann #1289)", () => {
+ beforeEach(() => {
+ useMachinesMock.mockReturnValue({
+ machines: [
+ {
+ id: "mac1",
+ availableRuntimes: [
+ { id: "claude", status: "unhealthy" },
+ { id: "codex", status: "healthy" },
+ { id: "gemini", status: "unhealthy" },
+ ],
+ },
+ ],
+ })
})
- 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")
+ it("selected current runtime is not disabled even when unhealthy; other unhealthy candidates are", () => {
+ const renderer = renderSheet({ ...BOT, runtime: "claude" })
+ const current = runtimeRadio(renderer, "claude")
+ const otherUnhealthy = runtimeRadio(renderer, "gemini")
+ const healthy = runtimeRadio(renderer, "codex")
+ expect(current.props.checked).toBe(true)
+ expect(current.props.disabled).toBe(false)
+ expect(otherUnhealthy.props.disabled).toBe(true)
+ expect(healthy.props.disabled).toBe(false)
})
})
diff --git a/src/web/src/components/community/bots/edit-bot-sheet.tsx b/src/web/src/components/community/bots/edit-bot-sheet.tsx
index 326997404..fbe5b961a 100644
--- a/src/web/src/components/community/bots/edit-bot-sheet.tsx
+++ b/src/web/src/components/community/bots/edit-bot-sheet.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useEffect, useRef, useState } from "react"
+import { useEffect, useMemo, useRef, useState } from "react"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
import {
@@ -13,16 +13,31 @@ import {
SheetTitle,
} from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
+import { Label } from "@/components/ui/label"
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog"
import {
type AvatarDraft,
isPhotoAvatarUrl,
} from "@/components/avatar"
import { serializeBeamSeed, parseBeamSeed } from "@/lib/avatar/seed-url"
+import { ProviderLogo } from "@/components/provider-logo"
import { useUpdateBot, useUploadBotAvatar, type BotSummary } from "@/hooks/community/use-bots"
+import { useMachines } from "@/hooks/community/use-machines"
import { BotFormFields } from "./bot-form-fields"
import { ModelField } from "./model-field"
import { validateBotModel } from "./bot-form-validation"
import { uniqueNamesGenerator, names } from "unique-names-generator"
+import { normalizeRuntimes } from "./create-bot-sheet"
+import { cn } from "@/lib/utils"
function draftFromBot(bot: BotSummary): AvatarDraft {
if (isPhotoAvatarUrl(bot.image)) return { kind: "photo", file: null, previewUrl: bot.image! }
@@ -48,12 +63,23 @@ 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 [runtime, setRuntime] = useState(bot?.runtime ?? "")
+ const [confirmProviderSwitch, setConfirmProviderSwitch] = useState(false)
const [nameError, setNameError] = useState<string | undefined>(undefined)
const [avatarDraft, setAvatarDraft] = useState<AvatarDraft>(() =>
bot ? draftFromBot(bot) : { kind: "procedural", image: serializeBeamSeed("initial") },
)
const update = useUpdateBot()
const uploadBotAvatar = useUploadBotAvatar()
+ const { machines } = useMachines()
+ const selectedMachine = machines.find((machine) => machine.id === bot?.machineId)
+ const runtimeOptions = useMemo(() => {
+ const options = normalizeRuntimes(selectedMachine)
+ if (runtime && !options.some((option) => option.id === runtime)) {
+ options.push({ id: runtime, unhealthy: true })
+ }
+ return options
+ }, [selectedMachine, runtime])
// Re-sync the form fields from `bot` each time a *new* edit target opens
// (keyed by id, not by every `bot` reference change — the parent's
@@ -67,8 +93,10 @@ export function EditBotSheet({
setName(bot.name)
setDescription(bot.description ?? "")
setModel(bot.modelName ?? null)
+ setRuntime(bot.runtime)
setAvatarDraft(draftFromBot(bot))
setNameError(undefined)
+ setConfirmProviderSwitch(false)
}, [open, bot])
function updateName(value: string) {
@@ -81,7 +109,13 @@ export function EditBotSheet({
setNameError(undefined)
}
- async function submit() {
+ function selectRuntime(next: string) {
+ if (next === runtime) return
+ setRuntime(next)
+ setModel(null)
+ }
+
+ async function performSubmit() {
if (!bot) return
if (!name.trim()) {
setNameError("Name is required")
@@ -93,11 +127,12 @@ export function EditBotSheet({
return
}
const modelChanged = model !== (bot.modelName ?? null)
+ const runtimeChanged = runtime !== bot.runtime
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.
- const res = await update.mutateAsync({
+ await update.mutateAsync({
id: bot.id,
name: name.trim(),
description: description.trim() || undefined,
@@ -105,6 +140,7 @@ export function EditBotSheet({
// Only send `model` when it actually changed, so an unrelated edit
// never triggers a stop-and-rewake.
...(modelChanged ? { model } : {}),
+ ...(runtimeChanged ? { runtime } : {}),
})
let avatarFailed = false
if (avatarDraft.kind === "photo" && avatarDraft.file) {
@@ -116,15 +152,11 @@ export function EditBotSheet({
}
}
if (!avatarFailed) {
- if (modelChanged) {
+ if (runtimeChanged) {
+ toast.success(`Provider switch to ${runtime} dispatched`)
+ } else 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")
- }
+ toast.success(`Model switch to ${label} dispatched`)
} else {
toast.success("Bot updated")
}
@@ -135,6 +167,19 @@ export function EditBotSheet({
}
}
+ function submit() {
+ if (!bot) return
+ if (!name.trim()) {
+ setNameError("Name is required")
+ return
+ }
+ if (runtime !== bot.runtime) {
+ setConfirmProviderSwitch(true)
+ return
+ }
+ void performSubmit()
+ }
+
return (
<Sheet open={open} onOpenChange={onOpenChange} disablePointerDismissal>
<SheetContent
@@ -145,7 +190,7 @@ export function EditBotSheet({
<SheetHeader>
<SheetTitle>Edit {bot?.name ?? "bot"}</SheetTitle>
<SheetDescription>
- Name and description edits take effect on the bot&apos;s next wake trigger. A model change applies right away if the bot is online.
+ Name and description edits take effect on the next wake. Provider and model switches require the bot to be online.
</SheetDescription>
</SheetHeader>
@@ -161,7 +206,54 @@ export function EditBotSheet({
nameError={nameError}
/>
{bot && (
- <ModelField runtime={bot.runtime} value={model} onChange={setModel} />
+ <>
+ <div className="flex flex-col gap-2">
+ <Label className="text-xs text-muted-foreground">Runtime</Label>
+ {runtimeOptions.length === 0 ? (
+ <p className="text-xs text-muted-foreground">
+ This machine has no runtimes installed.
+ </p>
+ ) : (
+ <div
+ className="flex flex-col gap-2"
+ role="radiogroup"
+ aria-label="Runtime"
+ data-testid="bot-provider-picker"
+ >
+ {runtimeOptions.map((option) => {
+ const selected = runtime === option.id
+ const disabled = option.unhealthy && !selected
+ return (
+ <label
+ key={option.id}
+ className={cn(
+ "flex items-center gap-2 rounded-lg border p-2 cursor-pointer transition-colors",
+ selected ? "border-primary bg-primary/5" : "border-border/50 hover:border-foreground/20",
+ disabled && "opacity-40 pointer-events-none",
+ )}
+ >
+ <input
+ type="radio"
+ name="edit-bot-runtime"
+ value={option.id}
+ checked={selected}
+ disabled={disabled}
+ onChange={() => selectRuntime(option.id)}
+ className="accent-primary size-3.5"
+ />
+ <ProviderLogo provider={option.id} className="size-4 shrink-0" />
+ <span className="text-sm">{option.id}</span>
+ {option.unhealthy && (
+ <span className="ml-auto text-xs text-muted-foreground">unavailable</span>
+ )}
+ </label>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ <ModelField runtime={runtime} value={model} onChange={setModel} />
+ </>
)}
</SheetBody>
@@ -174,6 +266,27 @@ export function EditBotSheet({
</Button>
</SheetFooter>
</SheetContent>
+ <AlertDialog open={confirmProviderSwitch} onOpenChange={setConfirmProviderSwitch}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Switch provider and reset this session?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Switching from {bot?.runtime} to {runtime} starts a fresh session. The bot cannot resume its current provider session.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ setConfirmProviderSwitch(false)
+ void performSubmit()
+ }}
+ >
+ Switch provider
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</Sheet>
)
}
diff --git a/src/web/src/hooks/community/use-bot-audit-log.ts b/src/web/src/hooks/community/use-bot-audit-log.ts
index 515e48ef2..e0e949baa 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" | "nap" | "model_changed" | "error"
+export type AuditKind = "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "provider_changed" | "error"
export type AuditEvent = {
id: string
@@ -124,4 +124,3 @@ export function useBotAuditLog(botId: string | null | undefined) {
isFetchingNextPage: query.isFetchingNextPage,
}
}
-
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index 14ac7bda0..021dfaa88 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -14,7 +14,7 @@ export type BotSummary = {
runtime: string
modelName: string | null
// Context lifecycle (my-bots #516): when the agent last refreshed its context
- // (nap OR session reset), ISO string, null if it never has. Rendered as the
+ // (nap, session reset, or provider switch), ISO string, null if it never has. Rendered as the
// awake-duration "Awake 17h" (Gus #672/#674 — how long the agent has been
// awake since that refresh, not "X ago"); null (never refreshed) omits it.
lastRefreshContextAt: string | null
@@ -82,9 +82,10 @@ export type UpdateBotInput = {
image?: string | null
// Explicit `null` clears a set model; `undefined` leaves it untouched.
model?: string | null
+ runtime?: string
}
export type UpdateBotResponse = {
- bot: BotSummary
+ bot: Pick<BotSummary, "id" | "name" | "description" | "image" | "runtime" | "modelName">
applied?: boolean
deliveryError?: boolean
}
@@ -103,6 +104,7 @@ export function useUpdateBot() {
// 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 } : {}),
+ ...("runtime" in input ? { runtime: input.runtime } : {}),
}),
}),
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.ts
index 150b900a4..21e68280f 100644
--- a/src/web/src/lib/community/audit-log-payload.test.ts
+++ b/src/web/src/lib/community/audit-log-payload.test.ts
@@ -55,6 +55,14 @@ describe("parseAuditLogPayload", () => {
to: "claude-opus-4-6",
})
})
+ it("parses a well-shaped provider_changed payload (required from/to runtimes)", () => {
+ expect(
+ parseAuditLogPayload("provider_changed", JSON.stringify({ from: "claude", to: "codex" })),
+ ).toEqual({ from: "claude", to: "codex" })
+ })
+ it("rejects a provider_changed payload missing from/to", () => {
+ expect(parseAuditLogPayload("provider_changed", JSON.stringify({ from: "claude" }))).toBe(null)
+ })
it("parses a well-shaped session_reset payload (single/reset_all trigger)", () => {
expect(parseAuditLogPayload("session_reset", JSON.stringify({ trigger: "single" }))).toEqual({
trigger: "single",
diff --git a/src/web/src/lib/community/audit-log-payload.ts b/src/web/src/lib/community/audit-log-payload.ts
index 1c33dd3b2..36c48053e 100644
--- a/src/web/src/lib/community/audit-log-payload.ts
+++ b/src/web/src/lib/community/audit-log-payload.ts
@@ -4,6 +4,7 @@ import {
AuditLogThinkingPayloadSchema,
AuditLogWakeTriggerPayloadSchema,
AuditLogModelChangedPayloadSchema,
+ AuditLogProviderChangedPayloadSchema,
AuditLogSessionResetPayloadSchema,
AuditLogNapPayloadSchema,
AuditLogErrorPayloadSchema,
@@ -46,6 +47,10 @@ export function parseAuditLogPayload(
const r = AuditLogModelChangedPayloadSchema.safeParse(json)
return r.success ? r.data : null
}
+ case "provider_changed": {
+ const r = AuditLogProviderChangedPayloadSchema.safeParse(json)
+ return r.success ? r.data : null
+ }
case "session_reset": {
const r = AuditLogSessionResetPayloadSchema.safeParse(json)
return r.success ? r.data : null
diff --git a/src/web/src/lib/community/bot-push.test.ts b/src/web/src/lib/community/bot-push.test.ts
index 416701e53..2efad7b5d 100644
--- a/src/web/src/lib/community/bot-push.test.ts
+++ b/src/web/src/lib/community/bot-push.test.ts
@@ -5,7 +5,11 @@ vi.mock("@/lib/broadcast", () => ({
wsDoFetch: (...a: unknown[]) => wsDoFetch(...a),
}))
-import { pushAgentResetToMachine, pushAgentModelSwitchToMachine } from "./bot-push"
+import {
+ pushAgentResetToMachine,
+ pushAgentModelSwitchToMachine,
+ pushAgentProviderSwitchToMachine,
+} from "./bot-push"
const FAKE_ENV = { WS_DO_WORKER: {}, DEV_WS_DO_URL: undefined } as unknown as Env
@@ -76,38 +80,116 @@ describe("pushAgentModelSwitchToMachine", () => {
mode: { kind: "default" as const },
}
- it("POSTs to /forward-agent-model-switch with the narrow body and returns { sent, deliveryError:false }", async () => {
+ it("POSTs to /forward-agent-model-switch with from/to 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",
+ from: null,
+ to: "claude-sonnet-4-6",
})
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).toEqual({
+ agentId: "bot-1",
+ config: CFG,
+ launchId: "l-1",
+ from: null,
+ to: "claude-sonnet-4-6",
+ })
expect(body.type).toBeUndefined()
})
it("distinguishes offline (sent:0, deliveryError:false) from a transport error (deliveryError:true)", async () => {
+ const args = {
+ agentId: "b",
+ config: CFG,
+ launchId: "l",
+ from: "a" as string | null,
+ to: "b" as string | null,
+ }
// 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 })
+ expect(await pushAgentModelSwitchToMachine(FAKE_ENV, "m", args)).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 })
+ expect(await pushAgentModelSwitchToMachine(FAKE_ENV, "m", args)).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 })
+ expect(await pushAgentModelSwitchToMachine(FAKE_ENV, "m", args)).toEqual({
+ sent: 0,
+ deliveryError: true,
+ })
+ })
+})
+
+describe("pushAgentProviderSwitchToMachine", () => {
+ beforeEach(() => {
+ wsDoFetch.mockReset()
+ })
+
+ const CFG = {
+ version: 1 as const,
+ runtime: "codex",
+ model: { kind: "default" as const },
+ mode: { kind: "default" as const },
+ }
+
+ it("POSTs to /forward-agent-provider-switch with from/to attribution", async () => {
+ wsDoFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+ const result = await pushAgentProviderSwitchToMachine(FAKE_ENV, "machine-1", {
+ agentId: "bot-1",
+ config: CFG,
+ launchId: "l-1",
+ from: "claude",
+ to: "codex",
+ })
+ 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-provider-switch")
+ const body = JSON.parse(init.body as string)
+ expect(body).toEqual({
+ agentId: "bot-1",
+ config: CFG,
+ launchId: "l-1",
+ from: "claude",
+ to: "codex",
+ })
+ })
+
+ it("returns deliveryError on non-ok / thrown fetch; sent:0 offline is not an error", async () => {
+ const args = {
+ agentId: "b",
+ config: CFG,
+ launchId: "l",
+ from: "claude",
+ to: "codex",
+ }
+ wsDoFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 0 }), { status: 200 }))
+ expect(await pushAgentProviderSwitchToMachine(FAKE_ENV, "m", args)).toEqual({
+ sent: 0,
+ deliveryError: false,
+ })
+ wsDoFetch.mockResolvedValue(new Response("boom", { status: 503 }))
+ expect(await pushAgentProviderSwitchToMachine(FAKE_ENV, "m", args)).toEqual({
+ sent: 0,
+ deliveryError: true,
+ })
+ wsDoFetch.mockRejectedValue(new Error("network"))
+ expect(await pushAgentProviderSwitchToMachine(FAKE_ENV, "m", args)).toEqual({
+ sent: 0,
+ deliveryError: true,
+ })
})
})
diff --git a/src/web/src/lib/community/bot-push.ts b/src/web/src/lib/community/bot-push.ts
index ebd41e053..cd0a62127 100644
--- a/src/web/src/lib/community/bot-push.ts
+++ b/src/web/src/lib/community/bot-push.ts
@@ -203,20 +203,28 @@ export async function pushAgentNapToMachine(
* `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`).
+ * returns `deliveryError: false`. The route maps those to 503 and 409;
+ * completion audit is written later when the switched launch reports its
+ * `agent_session`.
*/
export async function pushAgentModelSwitchToMachine(
env: Env,
machineId: string,
- args: { agentId: string; config: RuntimeConfig; launchId: string },
+ args: {
+ agentId: string
+ config: RuntimeConfig
+ launchId: string
+ from: string | null
+ to: string | null
+ },
): 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,
+ from: args.from,
+ to: args.to,
})
try {
const res = await wsDoFetch(
@@ -246,3 +254,39 @@ export async function pushAgentModelSwitchToMachine(
return { sent: 0, deliveryError: true }
}
}
+
+export async function pushAgentProviderSwitchToMachine(
+ env: Env,
+ machineId: string,
+ args: {
+ agentId: string
+ config: RuntimeConfig
+ launchId: string
+ from: string
+ to: string
+ },
+): Promise<{ sent: number; deliveryError: boolean }> {
+ const path = `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-agent-provider-switch`
+ const body = JSON.stringify(args)
+ try {
+ const res = await wsDoFetch(
+ env,
+ path,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body,
+ },
+ { label: machineId, type: "agent:provider_switch" },
+ )
+ if (!res.ok) {
+ log.warn("agent:provider_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:provider_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.ts
index 7a1a475bf..09e96e2e9 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 = 200
export type BotAuditEventEntry = {
id: string
botId: string
- kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "error"
+ kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "provider_changed" | "error"
payload: unknown
sessionId?: string | null
launchId?: string | null
diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.ts
index 166d239f3..972413523 100644
--- a/src/ws-do/src/index.test.ts
+++ b/src/ws-do/src/index.test.ts
@@ -610,10 +610,14 @@ describe("ws-do router", () => {
})
describe("POST /community-machine/by-id/:machineId/forward-agent-model-switch", () => {
+ // from/to are required for DO pending attribution; outer body has no `type`
+ // — the inner DO endpoint `/push-model-switch` stamps the wire frame.
const validBody = {
agentId: "bot-1",
config: { version: 1, runtime: "claude", model: { kind: "named", name: "claude-sonnet-4-6" }, mode: { kind: "default" } },
launchId: "l-1",
+ from: null as string | null,
+ to: "claude-sonnet-4-6" as string | null,
}
beforeEach(() => {
@@ -621,7 +625,7 @@ describe("ws-do router", () => {
mockGetActiveDoNamesForMachine.mockResolvedValue([])
})
- it("forwards a { type:'agent:model_switch', ... } frame to each DO's /push and aggregates sent", async () => {
+ it("forwards attribution body to DO /push-model-switch (no type on inner body)", 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", {
@@ -631,10 +635,16 @@ describe("ws-do router", () => {
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")
+ expect(stubReq.url).toBe("http://internal/push-model-switch")
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).toEqual({
+ agentId: "bot-1",
+ config: validBody.config,
+ launchId: "l-1",
+ from: null,
+ to: "claude-sonnet-4-6",
+ })
+ expect(parsed.type).toBeUndefined()
expect(parsed.config.model).toEqual({ kind: "named", name: "claude-sonnet-4-6" })
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ sent: 1 })
@@ -653,7 +663,7 @@ describe("ws-do router", () => {
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" }),
+ body: JSON.stringify({ agentId: "bot-1", config: "nope", launchId: "l-1", from: null, to: "x" }),
})
const res = await handler.fetch(req, env as any)
expect(res.status).toBe(400)
@@ -661,6 +671,20 @@ describe("ws-do router", () => {
expect(doMock.stubFetch).not.toHaveBeenCalled()
})
+ it("rejects missing from/to 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: validBody.config,
+ launchId: "l-1",
+ }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ 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",
@@ -673,6 +697,73 @@ describe("ws-do router", () => {
})
})
+ describe("POST /community-machine/by-id/:machineId/forward-agent-provider-switch", () => {
+ const validBody = {
+ agentId: "bot-1",
+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },
+ launchId: "l-1",
+ from: "claude",
+ to: "codex",
+ }
+
+ beforeEach(() => {
+ mockGetActiveDoNamesForMachine.mockReset()
+ mockGetActiveDoNamesForMachine.mockResolvedValue([])
+ })
+
+ it("forwards attribution body to DO /push-provider-switch (no type on inner body)", 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-provider-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-provider-switch")
+ const parsed = JSON.parse(await stubReq.text())
+ expect(parsed).toEqual({
+ agentId: "bot-1",
+ config: validBody.config,
+ launchId: "l-1",
+ from: "claude",
+ to: "codex",
+ })
+ expect(parsed.type).toBeUndefined()
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 1 })
+ })
+
+ it("rejects missing from/to with 400", async () => {
+ const req = new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-agent-provider-switch",
+ {
+ method: "POST",
+ body: JSON.stringify({
+ agentId: "bot-1",
+ config: validBody.config,
+ launchId: "l-1",
+ }),
+ },
+ )
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("zero active doNames → { sent: 0 }", async () => {
+ const req = new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-agent-provider-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.ts
index 46579094d..b7520da1e 100644
--- a/src/ws-do/src/index.ts
+++ b/src/ws-do/src/index.ts
@@ -509,12 +509,9 @@ export default {
}
// 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`.
+ // owner-triggered model switch. `from`/`to` stay server-side for completion
+ // attribution; the machine DO forwards only the daemon's existing
+ // `agent:model_switch` frame.
const forwardAgentModelSwitch = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-model-switch$/)
if (forwardAgentModelSwitch && request.method === "POST") {
const machineId = decodeURIComponent(forwardAgentModelSwitch[1])
@@ -531,13 +528,13 @@ export default {
return Response.json({ error: "invalid payload" }, { status: 400 })
}
const raw = payload as Record<string, unknown>
- const allowedKeys = new Set(["agentId", "config", "launchId"])
+ const allowedKeys = new Set(["agentId", "config", "launchId", "from", "to"])
for (const key of Object.keys(raw)) {
if (!allowedKeys.has(key)) {
return Response.json({ error: "invalid payload" }, { status: 400 })
}
}
- const { agentId, config, launchId } = raw
+ const { agentId, config, launchId, from, to } = raw
if (typeof agentId !== "string" || agentId.length === 0) {
return Response.json({ error: "invalid payload" }, { status: 400 })
}
@@ -547,6 +544,9 @@ export default {
if (!config || typeof config !== "object") {
return Response.json({ error: "invalid payload" }, { status: 400 })
}
+ if ((from !== null && typeof from !== "string") || (to !== null && typeof to !== "string")) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
let doNames: string[] = []
try {
@@ -560,7 +560,7 @@ export default {
if (doNames.length === 0) {
return Response.json({ sent: 0 })
}
- const frame = JSON.stringify({ type: "agent:model_switch", agentId, config, launchId })
+ const frame = JSON.stringify({ agentId, config, launchId, from, to })
let delivered = 0
let transientFailure = false
for (const dn of doNames) {
@@ -568,7 +568,7 @@ export default {
const stub = env.WS_DO.get(doId)
try {
const res = await stub.fetch(
- new Request("http://internal/push", {
+ new Request("http://internal/push-model-switch", {
method: "POST",
headers: { "content-type": "application/json" },
body: frame,
@@ -594,6 +594,79 @@ export default {
return Response.json({ sent: delivered })
}
+ const forwardAgentProviderSwitch = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-provider-switch$/)
+ if (forwardAgentProviderSwitch && request.method === "POST") {
+ const machineId = decodeURIComponent(forwardAgentProviderSwitch[1])
+ const reqLog = log.child({ traceId, machineId })
+
+ 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", "from", "to"])
+ for (const key of Object.keys(raw)) {
+ if (!allowedKeys.has(key)) return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ const { agentId, config, launchId, from, to } = raw
+ if (
+ typeof agentId !== "string" || agentId.length === 0 ||
+ typeof launchId !== "string" || launchId.length === 0 ||
+ !config || typeof config !== "object" ||
+ typeof from !== "string" || from.length === 0 ||
+ typeof to !== "string" || to.length === 0
+ ) {
+ 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 provider 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({ agentId, config, launchId, from, to })
+ 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-provider-switch", {
+ 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 provider switch" }, { status: 503 })
+ }
+ return Response.json({ sent: delivered })
+ }
+
// POST /community-machine/by-id/<machineId>/forward-agent-nap — agent
// self-initiated `agent:nap` push. Twin of /forward-agent-reset but the
// allowlist additionally carries the mandatory `handoff` string (the
diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.ts
index 15a2f97cc..4e3750c92 100644
--- a/src/ws-do/src/ws-durable.test.ts
+++ b/src/ws-do/src/ws-durable.test.ts
@@ -95,6 +95,8 @@ const mockGetBotBindingWithOwner = vi.fn<(db: unknown, botId: string) => Promise
const mockInsertBotActivityEventAndPrune = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
const mockInsertBotAuditSessionReset = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
const mockInsertBotAuditNap = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
+const mockInsertBotAuditModelChanged = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
+const mockInsertBotAuditProviderChanged = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
const mockTouchBotRefreshContext = vi.fn<(db: unknown, botId: string, now: string) => Promise<void>>().mockResolvedValue(undefined)
const mockUpdateProfile = vi
.fn<(db: unknown, userId: string, data: { statusEmoji?: string | null; statusText?: string | null }) => Promise<unknown>>()
@@ -399,6 +401,8 @@ vi.mock("@alook/shared", () => {
insertBotActivityEventAndPrune: (...a: any[]) => mockInsertBotActivityEventAndPrune(...a),
insertBotAuditSessionReset: (...a: any[]) => mockInsertBotAuditSessionReset(...a),
insertBotAuditNap: (...a: any[]) => mockInsertBotAuditNap(...a),
+ insertBotAuditModelChanged: (...a: any[]) => mockInsertBotAuditModelChanged(...a),
+ insertBotAuditProviderChanged: (...a: any[]) => mockInsertBotAuditProviderChanged(...a),
},
user: {
getUserInternal: (...a: [unknown, string]) => mockGetUserInternal(...a),
@@ -1949,11 +1953,15 @@ describe("WebSocketDurableObject", () => {
beforeEach(() => {
mockInsertBotAuditSessionReset.mockReset()
mockInsertBotAuditNap.mockReset()
+ mockInsertBotAuditModelChanged.mockReset()
+ mockInsertBotAuditProviderChanged.mockReset()
mockTouchBotRefreshContext.mockReset()
mockGetBotBindingWithOwner.mockReset()
mockStubFetch.mockClear()
mockInsertBotAuditSessionReset.mockResolvedValue({ id: "bae_reset", createdAt: "2025-06-01T10:00:00.000Z" })
mockInsertBotAuditNap.mockResolvedValue({ id: "bae_nap", createdAt: "2025-06-01T11:00:00.000Z" })
+ mockInsertBotAuditModelChanged.mockResolvedValue({ id: "bae_model", createdAt: "2025-06-01T12:00:00.000Z" })
+ mockInsertBotAuditProviderChanged.mockResolvedValue({ id: "bae_provider", createdAt: "2025-06-01T13:00:00.000Z" })
mockTouchBotRefreshContext.mockResolvedValue(undefined)
mockGetBotBindingWithOwner.mockResolvedValue({
machineId: "cm_1",
@@ -1974,6 +1982,17 @@ describe("WebSocketDurableObject", () => {
store.set("community-machine-identity", { userId: "u_1", machineId: "cm_1", credentialHash: "0".repeat(64) })
}
+ // record-iff-sent>0: pending is only written when a live community-machine
+ // socket accepts the forward. Seed one so /push and /push-*-switch tests
+ // exercise the completion landing (offline → sent=0 → no pending).
+ function onlineDaemon() {
+ const { durable, store, getWebSockets } = createDO()
+ seedIdentity(store)
+ const daemon = machineWs()
+ getWebSockets.mockReturnValue([daemon])
+ return { durable, store, daemon }
+ }
+
// Helper: push a frame through /push (records pending attribution), matching
// how the index worker forwards reset/nap frames to this DO.
async function pushFrame(durable: any, body: unknown) {
@@ -1986,6 +2005,16 @@ describe("WebSocketDurableObject", () => {
)
}
+ async function pushSwitch(durable: any, kind: "provider" | "model", body: Record<string, unknown>) {
+ await durable.fetch(
+ new (globalThis.Request as any)(`http://internal/push-${kind}-switch`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ )
+ }
+
function auditBroadcast() {
return mockStubFetch.mock.calls
.map((c: any[]) => c[0] as Request)
@@ -1993,8 +2022,7 @@ describe("WebSocketDurableObject", () => {
}
it("single reset: agent_session writes session_reset audit + stamps awake in lockstep + broadcasts", async () => {
- const { durable, store } = createDO()
- seedIdentity(store)
+ const { durable } = onlineDaemon()
// Dispatch: an agent:reset frame is forwarded → records launchId→single.
await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
// Completion: the reborn agent's agent_session lands.
@@ -2028,8 +2056,7 @@ describe("WebSocketDurableObject", () => {
})
it("two agent_session frames for the same launch write the reset audit ONCE (claim-first evict, no double record)", async () => {
- const { durable, store } = createDO()
- seedIdentity(store)
+ const { durable } = onlineDaemon()
await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
// Two agent_session frames arrive back-to-back for the SAME launch (e.g. a
// runtime that announces its session twice). The pending trigger must be
@@ -2042,8 +2069,7 @@ describe("WebSocketDurableObject", () => {
})
it("batch reset: each agent's agent_session writes session_reset with trigger reset_all", async () => {
- const { durable, store } = createDO()
- seedIdentity(store)
+ const { durable } = onlineDaemon()
// Dispatch: ONE machine:reset_all frame carrying two launches.
await pushFrame(durable, {
type: "machine:reset_all",
@@ -2077,8 +2103,7 @@ describe("WebSocketDurableObject", () => {
})
it("nap: agent_session writes nap audit (trigger nap) + stamps awake in lockstep + broadcasts", async () => {
- const { durable, store } = createDO()
- seedIdentity(store)
+ const { durable } = onlineDaemon()
await pushFrame(durable, { type: "agent:nap", agentId: "bot_1", config: {}, launchId: "l_nap", handoff: "note" })
await durable.webSocketMessage(
machineWs() as any,
@@ -2096,8 +2121,7 @@ describe("WebSocketDurableObject", () => {
})
it("fire-once: a replayed agent_session for the same launch writes nothing the second time", async () => {
- const { durable, store } = createDO()
- seedIdentity(store)
+ const { durable } = onlineDaemon()
await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
const frame = JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" })
await durable.webSocketMessage(machineWs() as any, frame)
@@ -2122,9 +2146,123 @@ describe("WebSocketDurableObject", () => {
expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
})
- it("cold-start fail branch B (agent_wake_ack error): evicts pending, no audit/awake, and a later replayed agent_session stays silent", async () => {
- const { durable, store } = createDO()
+ it("offline push (sent===0): records no pending — later agent_session writes nothing", async () => {
+ const { durable, store, getWebSockets } = createDO()
seedIdentity(store)
+ getWebSockets.mockReturnValue([])
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_offline" })
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_offline" }),
+ )
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ })
+
+ // Cecilia #1270: landing must dispatch by pending.kind — provider stamps
+ // awake; model does not; payloads stay in their namespaces.
+ it("provider_switch: agent_session writes provider_changed {from,to} + stamps awake (not model_changed)", async () => {
+ const { durable } = onlineDaemon()
+ await pushSwitch(durable, "provider", {
+ agentId: "bot_1",
+ config: { runtime: "codex" },
+ launchId: "l_prov",
+ from: "claude",
+ to: "codex",
+ })
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_prov" }),
+ )
+
+ expect(mockInsertBotAuditProviderChanged).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_1", launchId: "l_prov", from: "claude", to: "codex" }),
+ )
+ expect(mockInsertBotAuditModelChanged).not.toHaveBeenCalled()
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(expect.anything(), "bot_1", "2025-06-01T13:00:00.000Z")
+ const body = JSON.parse(await (auditBroadcast()!).clone().text()) as Record<string, unknown>
+ expect(body).toMatchObject({
+ kind: "provider_changed",
+ payload: { from: "claude", to: "codex" },
+ launchId: "l_prov",
+ })
+ })
+
+ // Cecilia #1279: provider PATCH clears model as a binding side-effect, but
+ // landing must emit exactly one provider_changed — never a sibling model_changed.
+ it("provider_switch with cleared model in config → exactly one provider_changed, zero model_changed", async () => {
+ const { durable } = onlineDaemon()
+ await pushSwitch(durable, "provider", {
+ agentId: "bot_1",
+ // Mirrors route after provider switch: runtime flipped + model null→default.
+ config: { runtime: "codex", model: { kind: "default" } },
+ launchId: "l_prov_clear_model",
+ from: "claude",
+ to: "codex",
+ })
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({
+ type: "agent_session",
+ agentId: "bot_1",
+ sessionId: "s_new",
+ launchId: "l_prov_clear_model",
+ }),
+ )
+
+ expect(mockInsertBotAuditProviderChanged).toHaveBeenCalledTimes(1)
+ expect(mockInsertBotAuditProviderChanged).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ botId: "bot_1",
+ launchId: "l_prov_clear_model",
+ from: "claude",
+ to: "codex",
+ }),
+ )
+ expect(mockInsertBotAuditModelChanged).not.toHaveBeenCalled()
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ const broadcasts = mockStubFetch.mock.calls
+ .map((c: any[]) => c[0] as Request)
+ .filter((r: Request) => r.url.endsWith("/broadcast"))
+ expect(broadcasts).toHaveLength(1)
+ const body = JSON.parse(await broadcasts[0]!.clone().text()) as Record<string, unknown>
+ expect(body.kind).toBe("provider_changed")
+ expect(body.kind).not.toBe("model_changed")
+ })
+
+ it("model_switch: agent_session writes model_changed {from,to} and does NOT stamp awake", async () => {
+ const { durable } = onlineDaemon()
+ await pushSwitch(durable, "model", {
+ agentId: "bot_1",
+ config: { model: { kind: "named", name: "opus" } },
+ launchId: "l_model",
+ from: null,
+ to: "opus",
+ })
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_model" }),
+ )
+
+ expect(mockInsertBotAuditModelChanged).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_1", launchId: "l_model", from: null, to: "opus" }),
+ )
+ expect(mockInsertBotAuditProviderChanged).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ const body = JSON.parse(await (auditBroadcast()!).clone().text()) as Record<string, unknown>
+ expect(body).toMatchObject({
+ kind: "model_changed",
+ payload: { from: null, to: "opus" },
+ launchId: "l_model",
+ })
+ })
+
+ it("cold-start fail branch B (agent_wake_ack error): evicts pending, no audit/awake, and a later replayed agent_session stays silent", async () => {
+ const { durable } = onlineDaemon()
await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
// Enroll fail / spawn threw → wake_ack error for this launch.
await durable.webSocketMessage(
@@ -2142,8 +2280,7 @@ describe("WebSocketDurableObject", () => {
})
it("cold-start fail branch A (session.error runtime_not_available): evicts pending, no audit/awake", async () => {
- const { durable, store } = createDO()
- seedIdentity(store)
+ const { durable } = onlineDaemon()
await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
// Runtime not installed → session.error carrying the launchId (Melisa's source half).
await durable.webSocketMessage(
diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.ts
index 4a57cf663..939162fd9 100644
--- a/src/ws-do/src/ws-durable.ts
+++ b/src/ws-do/src/ws-durable.ts
@@ -72,17 +72,26 @@ interface CommunityMachineHandle {
const IDENTITY_KEY = "community-machine-identity"
const HANDLE_KEY = "community-machine-handle"
const RUNTIME_ERROR_KEY = "community-machine-runtime-error"
-// Per-launch pending reset/nap attribution. Written when a reset/nap frame is
-// forwarded to this machine's daemon (dispatch), read + deleted when the
-// reborn agent's `agent_session` lands (completion). ctx.storage, NOT an
+// Per-launch restart attribution. Written only when a reset, nap, model switch,
+// or provider switch reaches this machine's daemon; read + deleted when the
+// resulting `agent_session` lands. ctx.storage, NOT an
// in-memory Map: the DO can hibernate between dispatch and agent_session, and
// a dropped entry would make a real reset silently write nothing (fire-once
// reads it as "never dispatched"). See plans/reset-nap-completion-rehome.md §6.
-const RESET_PENDING_PREFIX = "reset-pending:"
-const resetPendingKey = (launchId: string) => RESET_PENDING_PREFIX + launchId
+const RESTART_PENDING_PREFIX = "reset-pending:"
+const restartPendingKey = (launchId: string) => RESTART_PENDING_PREFIX + launchId
-/** Trigger for a pending reset/nap launch — the entry-point that dispatched it. */
type ResetTrigger = "single" | "reset_all" | "nap"
+type RestartAttribution =
+ | { kind: "session_reset"; trigger: "single" | "reset_all" }
+ | { kind: "nap" }
+ | { kind: "model_switch"; from: string | null; to: string | null }
+ | { kind: "provider_switch"; from: string; to: string }
+
+function normalizeRestartAttribution(value: ResetTrigger | RestartAttribution): RestartAttribution {
+ if (typeof value !== "string") return value
+ return value === "nap" ? { kind: "nap" } : { kind: "session_reset", trigger: value }
+}
export class WebSocketDurableObject extends DurableObject<Env> {
/**
@@ -186,15 +195,60 @@ export class WebSocketDurableObject extends DurableObject<Env> {
// daemon. Best-effort — if the daemon isn't connected, drops silently.
// Cold-start warmup on reconnect re-syncs authoritative state.
const body = await request.text()
- // Reset/nap/reset_all frames pass through here on their way to the
- // daemon — the moment we know both the launchId(s) AND which entry-point
- // dispatched them. Record the pending attribution NOW (first-write, never
- // later than the reborn `agent_session` could arrive — §6.2) so the
- // completion landing can look it up. Trigger is derived from the frame
- // type, so it structurally cannot disagree with the endpoint (§ Cecilia
- // #933). Done before the forward so a fast cold-start can't beat the write.
- await this.recordPendingResets(body)
+ // Reset/nap/reset_all frames pass through here on their way to the daemon.
+ // Persist attribution only when at least one daemon socket received them.
+ // Starting the storage write before yielding keeps a fast completion
+ // behind the Durable Object input gate.
const sent = this.forwardToCommunityMachine(body)
+ if (sent > 0) await this.recordPendingRestarts(body)
+ return new Response(JSON.stringify({ sent }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+
+ if (
+ request.method === "POST" &&
+ (url.pathname === "/push-model-switch" || url.pathname === "/push-provider-switch")
+ ) {
+ let payload: unknown
+ try {
+ payload = await request.json()
+ } catch {
+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
+ }
+ if (!payload || typeof payload !== "object") {
+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
+ }
+ const raw = payload as Record<string, unknown>
+ const { agentId, config, launchId, from, to } = raw
+ if (
+ typeof agentId !== "string" || agentId.length === 0 ||
+ typeof launchId !== "string" || launchId.length === 0 ||
+ !config || typeof config !== "object"
+ ) {
+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
+ }
+ const providerSwitch = url.pathname === "/push-provider-switch"
+ if (
+ providerSwitch
+ ? typeof from !== "string" || from.length === 0 || typeof to !== "string" || to.length === 0
+ : (from !== null && typeof from !== "string") || (to !== null && typeof to !== "string")
+ ) {
+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
+ }
+ const frame = JSON.stringify({
+ type: providerSwitch ? "agent:reset" : "agent:model_switch",
+ agentId,
+ config,
+ launchId,
+ })
+ const sent = this.forwardToCommunityMachine(frame)
+ if (sent > 0) {
+ const attribution: RestartAttribution = providerSwitch
+ ? { kind: "provider_switch", from: from as string, to: to as string }
+ : { kind: "model_switch", from: from as string | null, to: to as string | null }
+ await this.ctx.storage.put<RestartAttribution>(restartPendingKey(launchId), attribution)
+ }
return new Response(JSON.stringify({ sent }), {
headers: { "Content-Type": "application/json" },
})
@@ -931,8 +985,8 @@ export class WebSocketDurableObject extends DurableObject<Env> {
return
}
- // `agent_session` — the reborn agent is really up and has a session. This
- // is the completion signal for a reset/nap: if this launch has pending
+ // `agent_session` — the restarted agent is really up and has a session. This
+ // is the completion signal for a reset, nap, model switch, or provider switch: if this launch has pending
// attribution (recorded at dispatch in `/push`), write its audit + awake
// stamp + broadcast NOW (not at dispatch), then consume the entry so a
// replayed `agent_session` for the same launch can't double-write
@@ -951,8 +1005,9 @@ export class WebSocketDurableObject extends DurableObject<Env> {
// object's single-threaded turn: the second frame reads null and returns.
// (normalizer dedup removes the double-frame SOURCE; this makes the
// consume race-proof for any future double-frame, cross-runtime.)
- const trigger = await this.ctx.storage.get<ResetTrigger>(resetPendingKey(launchId))
- if (!trigger) return // not a reset/nap launch, or already consumed
+ const stored = await this.ctx.storage.get<ResetTrigger | RestartAttribution>(restartPendingKey(launchId))
+ if (!stored) return
+ const attribution = normalizeRestartAttribution(stored)
await this.evictPendingReset(launchId)
const db = createDb(this.env.DB)
await this.handleFrameForBoundBot({
@@ -967,28 +1022,48 @@ export class WebSocketDurableObject extends DurableObject<Env> {
// "slept" vs "was reset" (red line ④). actorId never travels: reset
// is owner-only, so the actor IS the bot owner, resolved right here
// from the binding (red line ⑥ — attribution stays server-side).
- const inserted =
- trigger === "nap"
- ? await queries.communityBotAuditLog.insertBotAuditNap(db, {
+ const inserted = attribution.kind === "nap"
+ ? await queries.communityBotAuditLog.insertBotAuditNap(db, { botId: agentId, launchId })
+ : attribution.kind === "session_reset"
+ ? await queries.communityBotAuditLog.insertBotAuditSessionReset(db, {
botId: agentId,
launchId,
+ trigger: attribution.trigger,
})
- : await queries.communityBotAuditLog.insertBotAuditSessionReset(db, {
- botId: agentId,
- launchId,
- trigger,
- })
+ : attribution.kind === "model_switch"
+ ? await queries.communityBotAuditLog.insertBotAuditModelChanged(db, {
+ botId: agentId,
+ launchId,
+ from: attribution.from,
+ to: attribution.to,
+ })
+ : await queries.communityBotAuditLog.insertBotAuditProviderChanged(db, {
+ botId: agentId,
+ launchId,
+ from: attribution.from,
+ to: attribution.to,
+ })
if (!inserted) return
// Stamp awake (lastRefreshContextAt) in lockstep with the audit row,
// using the row's createdAt so the my-bots "Awake Nh" indicator can
// never drift from the audit event.
- await queries.communityBot.touchBotRefreshContext(db, agentId, inserted.createdAt)
- const payload = trigger === "nap" ? { trigger: "nap" } : { trigger }
+ if (attribution.kind !== "model_switch") {
+ await queries.communityBot.touchBotRefreshContext(db, agentId, inserted.createdAt)
+ }
+ const payload = attribution.kind === "nap"
+ ? { trigger: "nap" }
+ : attribution.kind === "session_reset"
+ ? { trigger: attribution.trigger }
+ : { from: attribution.from, to: attribution.to }
await this.notifyUserDO(binding.ownerUserId, {
type: WS_EVENTS.BOT_AUDIT_EVENT,
botId: agentId,
id: inserted.id,
- kind: trigger === "nap" ? "nap" : "session_reset",
+ kind: attribution.kind === "provider_switch"
+ ? "provider_changed"
+ : attribution.kind === "model_switch"
+ ? "model_changed"
+ : attribution.kind,
payload,
sessionId: null,
launchId,
@@ -1215,7 +1290,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {
* (`agent_wake_ack` error / `session.error`). Best-effort parse — a malformed
* frame just records nothing and forwards as before.
*/
- private async recordPendingResets(body: string): Promise<void> {
+ private async recordPendingRestarts(body: string): Promise<void> {
let frame: unknown
try {
frame = JSON.parse(body)
@@ -1224,27 +1299,29 @@ export class WebSocketDurableObject extends DurableObject<Env> {
}
if (!frame || typeof frame !== "object") return
const f = frame as { type?: unknown }
- const put = async (launchId: unknown, trigger: ResetTrigger) => {
+ const put = async (launchId: unknown, attribution: RestartAttribution) => {
if (typeof launchId !== "string" || launchId.length === 0) return
- await this.ctx.storage.put<ResetTrigger>(resetPendingKey(launchId), trigger)
+ await this.ctx.storage.put<RestartAttribution>(restartPendingKey(launchId), attribution)
}
if (f.type === "agent:reset") {
- await put((f as { launchId?: unknown }).launchId, "single")
+ await put((f as { launchId?: unknown }).launchId, { kind: "session_reset", trigger: "single" })
} else if (f.type === "agent:nap") {
- await put((f as { launchId?: unknown }).launchId, "nap")
+ await put((f as { launchId?: unknown }).launchId, { kind: "nap" })
} else if (f.type === "machine:reset_all") {
const resets = (f as { resets?: unknown }).resets
if (Array.isArray(resets)) {
for (const r of resets) {
- if (r && typeof r === "object") await put((r as { launchId?: unknown }).launchId, "reset_all")
+ if (r && typeof r === "object") {
+ await put((r as { launchId?: unknown }).launchId, { kind: "session_reset", trigger: "reset_all" })
+ }
}
}
}
}
- /** Drop a pending reset/nap entry (consumed on completion, or evicted on failure). */
+ /** Drop a pending restart entry (consumed on completion, or evicted on failure). */
private async evictPendingReset(launchId: string): Promise<void> {
- await this.ctx.storage.delete(resetPendingKey(launchId))
+ await this.ctx.storage.delete(restartPendingKey(launchId))
}
/** Optimistic overlay clear — no-op when nothing is stashed. */