Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-5163 fix(agents): rebind the Agent Builder carrier when the runtime is switched (#5780)

Bohan Jiang168620fc15aa
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index e8496de8b0..cef0974e5c 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -44,6 +44,64 @@ describe("ApiClient label response schemas", () => {
});
});
+describe("ApiClient agent builder runtime switch", () => {
+ it("PATCHes the session runtime endpoint and returns the runtime the server bound", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ runtime_id: "runtime-b" }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await expect(
+ client.switchAgentBuilderRuntime("session-1", { runtime_id: "runtime-b" }),
+ ).resolves.toEqual({ runtime_id: "runtime-b" });
+
+ const call = fetchMock.mock.calls[0] as [string, RequestInit];
+ expect(call[0]).toContain("/api/agent-builder/sessions/session-1/runtime");
+ expect(call[1].method).toBe("PATCH");
+ expect(JSON.parse(String(call[1].body))).toEqual({ runtime_id: "runtime-b" });
+ });
+
+ it("falls back to the requested runtime id for a malformed success body", async () => {
+ // A 2xx means the rebind committed onto the runtime we asked for, so the
+ // fallback must say so. Reporting "unknown" here would leave the picker on
+ // the old runtime while the conversation executes on the new one — the very
+ // split this endpoint exists to close.
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ runtime_id: 42 }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await expect(
+ client.switchAgentBuilderRuntime("session-1", { runtime_id: "runtime-b" }),
+ ).resolves.toEqual({ runtime_id: "runtime-b" });
+ });
+
+ it("rejects without a fallback when the switch is refused", async () => {
+ // 409 (a reply in flight) means nothing was committed, so the caller must
+ // see a rejection and keep the old runtime selected.
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ error: "stop the current reply before switching runtime" }), {
+ status: 409,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await expect(
+ client.switchAgentBuilderRuntime("session-1", { runtime_id: "runtime-b" }),
+ ).rejects.toBeInstanceOf(ApiError);
+ });
+});
+
describe("ApiClient notification preferences", () => {
it("sends atomic preference updates with PATCH", async () => {
const fetchMock = vi.fn().mockResolvedValue(
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index feaadbbc89..c9568c04d1 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -18,6 +18,7 @@ import type {
AgentTemplateSummary,
CreateAgentFromTemplateRequest,
CreateAgentFromTemplateResponse,
+ AgentBuilderRuntimeSwitch,
AgentBuilderSession,
UpdateAgentRequest,
AgentEnvResponse,
@@ -173,7 +174,9 @@ import {
CloudRuntimeNodeListSchema,
CloudRuntimeNodeSchema,
CreateAgentFromTemplateResponseSchema,
+ AgentBuilderRuntimeSwitchSchema,
AgentBuilderSessionSchema,
+ agentBuilderRuntimeSwitchFallback,
DashboardAgentRunTimeListSchema,
DashboardRunTimeDailyListSchema,
DashboardUsageByAgentListSchema,
@@ -1008,6 +1011,29 @@ export class ApiClient {
);
}
+ /** Rebinds a live builder conversation to another runtime. Callers must not
+ * show the new runtime as selected until this resolves — the whole point is
+ * that the UI's runtime and the executing runtime agree.
+ *
+ * A non-2xx throws before we get here and nothing was committed. Reaching the
+ * parse means the server bound `data.runtime_id`, so that is the fallback for
+ * an unparseable body — see agentBuilderRuntimeSwitchFallback. */
+ async switchAgentBuilderRuntime(
+ sessionId: string,
+ data: { runtime_id: string },
+ ): Promise<AgentBuilderRuntimeSwitch> {
+ const raw = await this.fetch<unknown>(
+ `/api/agent-builder/sessions/${sessionId}/runtime`,
+ { method: "PATCH", body: JSON.stringify(data) },
+ );
+ return parseWithFallback(
+ raw,
+ AgentBuilderRuntimeSwitchSchema,
+ agentBuilderRuntimeSwitchFallback(data.runtime_id),
+ { endpoint: "PATCH /api/agent-builder/sessions/{id}/runtime" },
+ );
+ }
+
async listAgentTemplates(): Promise<AgentTemplateSummary[]> {
const raw = await this.fetch<unknown>("/api/agent-templates");
return parseWithFallback(
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 2b60a35542..1daf79e20a 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -3,6 +3,7 @@ import type {
Agent,
AgentTemplate,
AgentTemplateSummary,
+ AgentBuilderRuntimeSwitch,
AgentBuilderSession,
Attachment,
AutopilotRun,
@@ -983,6 +984,20 @@ export const EMPTY_AGENT_BUILDER_SESSION: AgentBuilderSession = {
runtime_id: "",
};
+export const AgentBuilderRuntimeSwitchSchema = z.object({
+ runtime_id: z.string(),
+}).loose();
+
+// This endpoint returns 2xx only after the carrier has been bound to the
+// runtime the caller asked for; anything else is a thrown error and no commit.
+// So the safe fallback for an unparseable SUCCESS body is the requested id, not
+// an empty one: the rebind did happen, and reporting "unknown" would leave the
+// picker showing a runtime that is no longer executing — the exact split this
+// endpoint exists to close.
+export const agentBuilderRuntimeSwitchFallback = (
+ requestedRuntimeID: string,
+): AgentBuilderRuntimeSwitch => ({ runtime_id: requestedRuntimeID });
+
// Squad list responses carry lightweight membership previews used by hover
// cards. The preview fields are additive API fields, so older backends default
// cleanly to no preview instead of breaking newer frontends.
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 14c6dae27a..894ce03386 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -523,6 +523,13 @@ export interface AgentBuilderSession {
runtime_id: string;
}
+/** Result of rebinding a live builder conversation to another runtime.
+ * `runtime_id` is the runtime the server actually bound — the caller must
+ * wait for it before showing the new runtime as selected. */
+export interface AgentBuilderRuntimeSwitch {
+ runtime_id: string;
+}
+
/** Agent template summary — fields needed by the picker grid. Does NOT
* include `instructions` to keep the list payload small; the detail
* endpoint or the create flow returns the full template body. */
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 323a5334ed..791c0f6a23 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -22,6 +22,7 @@ export type {
CreateRuntimeProfileRequest,
UpdateRuntimeProfileRequest,
CreateAgentRequest,
+ AgentBuilderRuntimeSwitch,
AgentBuilderSession,
AgentTemplate,
AgentTemplateSummary,
diff --git a/packages/views/agents/components/agent-creation-studio.tsx b/packages/views/agents/components/agent-creation-studio.tsx
index fd604a0146..de18c98010 100644
--- a/packages/views/agents/components/agent-creation-studio.tsx
+++ b/packages/views/agents/components/agent-creation-studio.tsx
@@ -169,6 +169,7 @@ export function AgentCreationStudio() {
const [builderSessionId, setBuilderSessionId] = useState("");
const [builderStarting, setBuilderStarting] = useState(false);
const [builderClosing, setBuilderClosing] = useState(false);
+ const [builderSwitchingRuntime, setBuilderSwitchingRuntime] = useState(false);
const [builderError, setBuilderError] = useState<string | null>(null);
const [builderRestoreDraft, setBuilderRestoreDraft] = useState<{
id: string;
@@ -511,9 +512,52 @@ export function AgentCreationStudio() {
}
};
+ // Rebinds the conversation's execution runtime on the server BEFORE the draft
+ // reflects the new selection. Updating the draft first is what produced
+ // MUL-5163: the picker showed runtime B while every subsequent message still
+ // ran on the runtime the session was created with.
+ const switchBuilderRuntime = async (runtimeId: string) => {
+ if (!runtimeId || runtimeId === draft.runtimeId) return;
+ // Before the conversation exists there is no carrier to rebind, so the
+ // picker is still plain draft state.
+ if (!builderSessionId) {
+ setDraft((current) => ({ ...current, runtimeId, model: "" }));
+ return;
+ }
+ if (builderSwitchingRuntime) return;
+ setBuilderSwitchingRuntime(true);
+ setBuilderError(null);
+ try {
+ const result = await api.switchAgentBuilderRuntime(builderSessionId, {
+ runtime_id: runtimeId,
+ });
+ // Follow the runtime the server says it bound. Resolving here at all means
+ // the rebind committed, so refusing to move the draft would leave the
+ // picker pointing at a runtime that no longer executes anything — the same
+ // split this whole change removes. The client fallback already resolves an
+ // unparseable success body to the requested id.
+ const boundRuntimeId = result.runtime_id || runtimeId;
+ // Model ids are per-runtime; clear it so the new runtime resolves its own
+ // default instead of keeping one it may not serve.
+ setDraft((current) => ({ ...current, runtimeId: boundRuntimeId, model: "" }));
+ toast.success(t(($) => $.creation_studio.builder.switch_runtime_success));
+ } catch (error) {
+ setBuilderError(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.creation_studio.builder.switch_runtime_failed),
+ );
+ } finally {
+ setBuilderSwitchingRuntime(false);
+ }
+ };
+
const sendBuilderMessage = async (content: string): Promise<boolean> => {
const text = content.trim();
- if (!text || !builderSessionId || builderPending) return false;
+ // builderSwitchingRuntime blocks the send while a rebind is in flight: the
+ // server serialises the two anyway, but letting the message through would
+ // mean the user cannot tell which runtime answered it.
+ if (!text || !builderSessionId || builderPending || builderSwitchingRuntime) return false;
setBuilderError(null);
try {
const encodedContent = encodeBuilderInput(
@@ -864,6 +908,11 @@ export function AgentCreationStudio() {
members={members}
currentUserId={currentUser?.id ?? null}
createError={createError}
+ onRuntimeSelect={(runtimeId) => {
+ void switchBuilderRuntime(runtimeId);
+ }}
+ runtimeSwitchPending={builderPending}
+ runtimeSwitchInFlight={builderSwitchingRuntime}
/>
</div>
<StudioFooter
@@ -1057,6 +1106,9 @@ function ConfigurationPanel({
currentUserId,
createError,
compact = false,
+ onRuntimeSelect,
+ runtimeSwitchPending = false,
+ runtimeSwitchInFlight = false,
}: {
draft: AgentDraft;
onChange: (draft: AgentDraft) => void;
@@ -1066,11 +1118,30 @@ function ConfigurationPanel({
currentUserId: string | null;
createError: string | null;
compact?: boolean;
+ /** Builder sessions rebind the server-side carrier instead of only editing
+ * the draft. Absent for the plain create flows, where the draft is the only
+ * state that exists. */
+ onRuntimeSelect?: (runtimeId: string) => void;
+ /** A builder reply is in flight, so the server would refuse the rebind. */
+ runtimeSwitchPending?: boolean;
+ /** A rebind request is in flight. */
+ runtimeSwitchInFlight?: boolean;
}) {
const { t } = useT("agents");
const selectedRuntime = runtimes.find((runtime) => runtime.id === draft.runtimeId) ?? null;
const set = <K extends keyof AgentDraft>(key: K, value: AgentDraft[K]) => onChange({ ...draft, [key]: value });
const otherMembers = members.filter((member) => member.user_id !== currentUserId);
+ const runtimeLocked = runtimeSwitchPending || runtimeSwitchInFlight;
+ const handleRuntimeSelect = (id: string) => {
+ if (id === draft.runtimeId) return;
+ if (onRuntimeSelect) {
+ onRuntimeSelect(id);
+ return;
+ }
+ // Model is per-runtime; clear it on runtime change so the new
+ // runtime resolves its own default instead of a stale value.
+ onChange({ ...draft, runtimeId: id, model: "" });
+ };
return (
<div className={cn("space-y-8", compact && "space-y-6")}>
@@ -1167,24 +1238,33 @@ function ConfigurationPanel({
>
<SettingsCard>
<div className={cn("grid gap-4 px-4 py-4", !compact && "sm:grid-cols-2")}>
- <RuntimePicker
- runtimes={runtimes}
- runtimesLoading={runtimesLoading}
- members={members}
- currentUserId={currentUserId}
- selectedRuntimeId={draft.runtimeId}
- onSelect={(id) => {
- // Model is per-runtime; clear it on runtime change so the new
- // runtime resolves its own default instead of a stale value.
- if (id !== draft.runtimeId) onChange({ ...draft, runtimeId: id, model: "" });
- }}
- />
+ <div className="min-w-0">
+ <RuntimePicker
+ runtimes={runtimes}
+ runtimesLoading={runtimesLoading}
+ members={members}
+ currentUserId={currentUserId}
+ selectedRuntimeId={draft.runtimeId}
+ onSelect={handleRuntimeSelect}
+ disabled={runtimeLocked}
+ />
+ {/* A silently greyed-out picker is the worst version of this: the
+ user reaches for it exactly when the current runtime has gone
+ wrong, so say what unblocks it instead of just refusing. */}
+ {runtimeSwitchPending && (
+ <p className="mt-1.5 text-xs text-muted-foreground">
+ {t(($) => $.creation_studio.builder.switch_runtime_pending)}
+ </p>
+ )}
+ </div>
<ModelDropdown
runtimeId={selectedRuntime?.id ?? null}
runtimeOnline={selectedRuntime?.status === "online"}
value={draft.model}
onChange={(value) => set("model", value)}
- disabled={!selectedRuntime}
+ // A successful switch clears the model, so an edit made while the
+ // rebind is in flight would be silently discarded.
+ disabled={!selectedRuntime || runtimeSwitchInFlight}
/>
</div>
</SettingsCard>
diff --git a/packages/views/agents/components/runtime-picker.test.tsx b/packages/views/agents/components/runtime-picker.test.tsx
new file mode 100644
index 0000000000..1ecb7561ae
--- /dev/null
+++ b/packages/views/agents/components/runtime-picker.test.tsx
@@ -0,0 +1,123 @@
+// @vitest-environment jsdom
+
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { render, fireEvent, cleanup } from "@testing-library/react";
+import type { MemberWithUser, RuntimeDevice } from "@multica/core/types";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../locales/en/common.json";
+import enAgents from "../../locales/en/agents.json";
+import enIssues from "../../locales/en/issues.json";
+
+// ActorAvatar pulls workspace context this unit test doesn't provide.
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: () => null,
+}));
+
+// Provider logos are inline SVGs with no behavior under test.
+vi.mock("../../runtimes/components/provider-logo", () => ({
+ ProviderLogo: () => null,
+}));
+
+import { RuntimePicker } from "./runtime-picker";
+
+const TEST_RESOURCES = {
+ en: { common: enCommon, agents: enAgents, issues: enIssues },
+};
+
+const ME = "user-me";
+
+const MEMBERS = [{ user_id: ME, name: "Me", role: "member" }] as unknown as MemberWithUser[];
+
+function makeRuntime(overrides: Partial<RuntimeDevice>): RuntimeDevice {
+ return {
+ id: "rt",
+ workspace_id: "ws-1",
+ daemon_id: "daemon-1",
+ name: "Claude (host.local)",
+ runtime_mode: "local",
+ provider: "claude",
+ launch_header: "",
+ status: "online",
+ device_info: "host.local · macOS (arm64)",
+ metadata: {},
+ owner_id: ME,
+ visibility: "private",
+ last_seen_at: "2026-07-11T00:00:00Z",
+ created_at: "2026-07-01T00:00:00Z",
+ updated_at: "2026-07-01T00:00:00Z",
+ ...overrides,
+ } as RuntimeDevice;
+}
+
+const RUNTIMES = [
+ makeRuntime({ id: "rt-a", name: "Claude (a.local)" }),
+ makeRuntime({ id: "rt-b", name: "Claude (b.local)", provider: "codex" }),
+];
+
+function renderPicker(props: Partial<React.ComponentProps<typeof RuntimePicker>> = {}) {
+ const onSelect = vi.fn();
+ const utils = render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <RuntimePicker
+ runtimes={RUNTIMES}
+ members={MEMBERS}
+ currentUserId={ME}
+ selectedRuntimeId="rt-a"
+ onSelect={onSelect}
+ {...props}
+ />
+ </I18nProvider>,
+ );
+ return { ...utils, onSelect };
+}
+
+function trigger(container: HTMLElement): HTMLButtonElement {
+ const element = container.querySelector<HTMLButtonElement>('[data-slot="popover-trigger"]');
+ if (!element) throw new Error("runtime picker trigger not rendered");
+ return element;
+}
+
+describe("RuntimePicker (creation studio)", () => {
+ beforeEach(() => cleanup());
+ afterEach(() => cleanup());
+
+ it("opens the runtime list on click", () => {
+ const { container } = renderPicker();
+ fireEvent.click(trigger(container));
+ expect(trigger(container).getAttribute("aria-expanded")).toBe("true");
+ });
+
+ // A builder session rebinds its execution runtime on the server. While that
+ // request is in flight the selection cannot be honoured yet, so the picker
+ // must refuse to open rather than let the user queue a second, conflicting
+ // choice (MUL-5163).
+ it("cannot be opened while disabled", () => {
+ const { container, onSelect } = renderPicker({ disabled: true });
+ expect(trigger(container).disabled).toBe(true);
+ fireEvent.click(trigger(container));
+ expect(trigger(container).getAttribute("aria-expanded")).not.toBe("true");
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
+ // Switching the Mine/All tab re-selects the first usable runtime in the new
+ // list, so it is a second path into onSelect. Leaving it live while disabled
+ // would let a locked picker start a switch the server then has to refuse.
+ it("does not select through the Mine/All filter while disabled", () => {
+ const { container, onSelect } = renderPicker({
+ runtimes: [
+ ...RUNTIMES,
+ makeRuntime({ id: "rt-other", name: "Claude (other.local)", owner_id: "user-other", visibility: "public" }),
+ ],
+ disabled: true,
+ });
+ const filters = [...container.querySelectorAll("button")].filter(
+ (button) => button.getAttribute("data-slot") !== "popover-trigger",
+ );
+ expect(filters.length).toBeGreaterThan(0);
+ for (const button of filters) {
+ expect(button.disabled).toBe(true);
+ fireEvent.click(button);
+ }
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/agents/components/runtime-picker.tsx b/packages/views/agents/components/runtime-picker.tsx
index 37424e0281..d43a6a8729 100644
--- a/packages/views/agents/components/runtime-picker.tsx
+++ b/packages/views/agents/components/runtime-picker.tsx
@@ -33,6 +33,7 @@ export function RuntimePicker({
currentUserId,
selectedRuntimeId,
onSelect,
+ disabled = false,
}: {
runtimes: RuntimeDevice[];
runtimesLoading?: boolean;
@@ -40,6 +41,9 @@ export function RuntimePicker({
currentUserId: string | null;
selectedRuntimeId: string;
onSelect: (id: string) => void;
+ /** Blocks opening the picker while the selection cannot be honoured yet
+ * (e.g. a builder reply or a runtime rebind is in flight). */
+ disabled?: boolean;
}) {
const { t } = useT("agents");
const [open, setOpen] = useState(false);
@@ -109,11 +113,15 @@ export function RuntimePicker({
{t(($) => $.create_dialog.runtime_label)}
</Label>
{hasOtherRuntimes && (
+ // These are not just a view filter: changing tab re-selects the first
+ // usable runtime in the new list, so they are a second way to fire
+ // onSelect and must honour `disabled` alongside the trigger.
<div className="flex items-center gap-0.5 rounded-md bg-muted p-0.5">
<button
type="button"
+ disabled={disabled}
onClick={() => handleFilterChange("mine")}
- className={`rounded px-2 py-0.5 text-xs font-medium transition-colors ${
+ className={`rounded px-2 py-0.5 text-xs font-medium transition-colors disabled:pointer-events-none disabled:opacity-50 ${
filter === "mine"
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground"
@@ -123,8 +131,9 @@ export function RuntimePicker({
</button>
<button
type="button"
+ disabled={disabled}
onClick={() => handleFilterChange("all")}
- className={`rounded px-2 py-0.5 text-xs font-medium transition-colors ${
+ className={`rounded px-2 py-0.5 text-xs font-medium transition-colors disabled:pointer-events-none disabled:opacity-50 ${
filter === "all"
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground"
@@ -136,14 +145,15 @@ export function RuntimePicker({
)}
</div>
<Popover
- open={open}
+ open={open && !disabled}
onOpenChange={(next) => {
+ if (disabled) return;
setOpen(next);
if (!next) setSearch("");
}}
>
<PopoverTrigger
- disabled={runtimes.length === 0 && !runtimesLoading}
+ disabled={disabled || (runtimes.length === 0 && !runtimesLoading)}
className="flex w-full min-w-0 items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 mt-1.5 text-left text-sm transition-colors hover:bg-muted disabled:pointer-events-none disabled:opacity-50"
>
{runtimesLoading ? (
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index 1572dd428b..a8aa8a6a01 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -337,6 +337,9 @@
"start_failed": "Could not start Agent Builder.",
"send_failed": "Could not send your message.",
"stop_failed": "Could not stop the current generation.",
+ "switch_runtime_failed": "Could not switch runtime. The conversation is still running on the previous one.",
+ "switch_runtime_pending": "Stop the current reply to switch runtime.",
+ "switch_runtime_success": "Runtime switched. Your draft is kept and the conversation continues on the new runtime with a fresh model session.",
"chat_title": "Agent Builder",
"chat_hint": "Shape the requirements through conversation and refine the configuration beside it.",
"runtime_online": "Runtime online",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 37bf2953ee..8ac62d985e 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -765,6 +765,9 @@
"start_failed": "Agent Builder を開始できませんでした。",
"send_failed": "メッセージを送信できませんでした。",
"stop_failed": "現在の生成を停止できませんでした。",
+ "switch_runtime_failed": "ランタイムを切り替えられませんでした。会話は引き続き元のランタイムで実行されています。",
+ "switch_runtime_pending": "現在の返信を停止するとランタイムを切り替えられます。",
+ "switch_runtime_success": "ランタイムを切り替えました。下書き設定はそのまま残り、以降の会話は新しいランタイムで新しいモデルセッションとして続きます。",
"chat_title": "Agent Builder",
"chat_hint": "会話で要件を整理し、隣の設定を調整します。",
"runtime_online": "ランタイムはオンライン",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 0132a52d04..96107dd345 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -765,6 +765,9 @@
"start_failed": "Agent Builder를 시작하지 못했습니다.",
"send_failed": "메시지를 보내지 못했습니다.",
"stop_failed": "현재 생성을 중지하지 못했습니다.",
+ "switch_runtime_failed": "런타임을 전환하지 못했습니다. 대화는 이전 런타임에서 계속 실행됩니다.",
+ "switch_runtime_pending": "현재 답변을 중지하면 런타임을 전환할 수 있습니다.",
+ "switch_runtime_success": "런타임을 전환했습니다. 설정 초안은 유지되며, 이후 대화는 새 런타임에서 새로운 모델 세션으로 이어집니다.",
"chat_title": "Agent Builder",
"chat_hint": "대화로 요구 사항을 정리하고 옆의 설정을 다듬으세요.",
"runtime_online": "런타임 온라인",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index f22824dc05..9d249f6130 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -328,6 +328,9 @@
"start_failed": "无法启动 Agent Builder。",
"send_failed": "无法发送消息。",
"stop_failed": "无法停止当前生成任务。",
+ "switch_runtime_failed": "切换运行时失败,对话仍在原来的运行时上执行。",
+ "switch_runtime_pending": "停止当前回复后即可切换运行时。",
+ "switch_runtime_success": "已切换运行时。配置草稿保留,后续对话将在新运行时上重新开始一段模型会话。",
"chat_title": "Agent Builder",
"chat_hint": "通过对话梳理需求,并持续完善右侧配置。",
"runtime_online": "运行时在线",
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index a559cc7701..f4d8b0f2e5 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1234,7 +1234,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/", h.ListAgentTemplates)
r.Get("/{slug}", h.GetAgentTemplate)
})
- r.Post("/api/agent-builder/sessions", h.CreateAgentBuilderSession)
+ r.Route("/api/agent-builder/sessions", func(r chi.Router) {
+ r.Post("/", h.CreateAgentBuilderSession)
+ r.Patch("/{sessionId}/runtime", h.SwitchAgentBuilderRuntime)
+ })
// Skills
r.Route("/api/skills", func(r chi.Router) {
diff --git a/server/internal/handler/agent_builder.go b/server/internal/handler/agent_builder.go
index a9eb5e8236..31aa6a2db5 100644
--- a/server/internal/handler/agent_builder.go
+++ b/server/internal/handler/agent_builder.go
@@ -7,6 +7,7 @@ import (
"net/http"
"strings"
+ "github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -73,30 +74,10 @@ func (h *Handler) CreateAgentBuilderSession(w http.ResponseWriter, r *http.Reque
if !ok {
return
}
- runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
+ runtime, ok := h.resolveBuilderRuntime(w, r, workspaceID, workspaceUUID, runtimeID, "start")
if !ok {
return
}
- runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{
- ID: runtimeUUID,
- WorkspaceID: workspaceUUID,
- })
- if err != nil {
- writeError(w, http.StatusBadRequest, "invalid runtime_id")
- return
- }
- member, ok := h.workspaceMember(w, r, workspaceID)
- if !ok {
- return
- }
- if !canUseRuntimeForAgent(member, runtime) {
- writeError(w, http.StatusForbidden, "this runtime is private; only its owner or a workspace admin can use it")
- return
- }
- if runtime.Status != "online" {
- writeError(w, http.StatusConflict, "runtime must be online to start an agent builder session")
- return
- }
flowID := uuid.NewString()
ownerUUID := parseUUID(userID)
@@ -160,3 +141,175 @@ func (h *Handler) CreateAgentBuilderSession(w http.ResponseWriter, r *http.Reque
RuntimeID: runtimeID,
})
}
+
+// resolveBuilderRuntime loads a runtime the caller is allowed to execute a
+// builder conversation on. Shared by session create and runtime switch so both
+// enforce the same three gates in the same order: it exists in this workspace,
+// this member may use it (private runtimes stay owner/admin-only), and it is
+// online. verb names the attempted action in the offline error so the two call
+// sites read naturally.
+func (h *Handler) resolveBuilderRuntime(w http.ResponseWriter, r *http.Request, workspaceID string, workspaceUUID pgtype.UUID, runtimeID, verb string) (db.AgentRuntime, bool) {
+ runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
+ if !ok {
+ return db.AgentRuntime{}, false
+ }
+ runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{
+ ID: runtimeUUID,
+ WorkspaceID: workspaceUUID,
+ })
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid runtime_id")
+ return db.AgentRuntime{}, false
+ }
+ member, ok := h.workspaceMember(w, r, workspaceID)
+ if !ok {
+ return db.AgentRuntime{}, false
+ }
+ if !canUseRuntimeForAgent(member, runtime) {
+ writeError(w, http.StatusForbidden, "this runtime is private; only its owner or a workspace admin can use it")
+ return db.AgentRuntime{}, false
+ }
+ if runtime.Status != "online" {
+ writeError(w, http.StatusConflict, fmt.Sprintf("runtime must be online to %s an agent builder session", verb))
+ return db.AgentRuntime{}, false
+ }
+ return runtime, true
+}
+
+type SwitchAgentBuilderRuntimeRequest struct {
+ RuntimeID string `json:"runtime_id"`
+}
+
+type SwitchAgentBuilderRuntimeResponse struct {
+ RuntimeID string `json:"runtime_id"`
+}
+
+// SwitchAgentBuilderRuntime re-points a live builder conversation at another
+// runtime. The live-draft runtime picker used to mutate React state only, so the
+// UI could show runtime B while every subsequent message still enqueued against
+// the carrier agent frozen to runtime A at session create time (MUL-5163).
+//
+// The rebind runs under LockChatSessionForRuntimeBind, the same row lock
+// SendDirectChatMessage takes, so "no reply is in flight" and "the carrier now
+// points at B" are decided in one serialised step. Without that lock a send that
+// had already read runtime A could still land its task after this handler
+// returned success — reproducing the exact inconsistency this endpoint exists to
+// remove.
+//
+// chat_session.runtime_id is deliberately left pointing at the old runtime: the
+// daemon only resumes a stored provider session when that pointer matches the
+// claiming task's runtime, so leaving it stale is what makes B start a fresh
+// provider session instead of resuming A's. Multica-side chat history and the
+// draft are untouched.
+func (h *Handler) SwitchAgentBuilderRuntime(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ var req SwitchAgentBuilderRuntimeRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ runtimeID := strings.TrimSpace(req.RuntimeID)
+ if runtimeID == "" {
+ writeError(w, http.StatusBadRequest, "runtime_id is required")
+ return
+ }
+
+ // Creator-only, like every other write on a chat session.
+ session, ok := h.loadChatSessionForUser(w, r, userID, workspaceID, chi.URLParam(r, "sessionId"))
+ if !ok {
+ return
+ }
+ if session.Status != "active" {
+ writeError(w, http.StatusBadRequest, "chat session is archived")
+ return
+ }
+
+ // Only builder carriers may be rebound. A user-authored agent changes runtime
+ // through the agent update path, which has its own permission model — this
+ // endpoint must not become a second, weaker way in.
+ agent, err := h.Queries.GetAgent(r.Context(), session.AgentID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load chat agent")
+ return
+ }
+ if !isAgentBuilderCarrier(agent) {
+ writeError(w, http.StatusNotFound, "agent builder session not found")
+ return
+ }
+
+ workspaceUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ runtime, ok := h.resolveBuilderRuntime(w, r, workspaceID, workspaceUUID, runtimeID, "switch")
+ if !ok {
+ return
+ }
+
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to switch agent builder runtime")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ if _, err := qtx.LockChatSessionForRuntimeBind(r.Context(), session.ID); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "chat session not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to lock chat session")
+ return
+ }
+
+ // Checked under the lock, so a send cannot slip in behind it. A task that is
+ // still queued on an offline runtime also counts as pending — the client is
+ // expected to stop it first, which restores the message to the composer.
+ if _, err := qtx.GetPendingChatTask(r.Context(), session.ID); err == nil {
+ writeError(w, http.StatusConflict, "stop the current reply before switching runtime")
+ return
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusInternalServerError, "failed to check pending builder task")
+ return
+ }
+
+ // Model ids are per-runtime, so the carrier's model is cleared rather than
+ // carried over; the new runtime resolves its own default.
+ updated, err := qtx.RebindAgentBuilderRuntime(r.Context(), db.RebindAgentBuilderRuntimeParams{
+ ID: agent.ID,
+ RuntimeID: runtime.ID,
+ RuntimeMode: runtime.RuntimeMode,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "agent builder session not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to switch agent builder runtime")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to commit agent builder runtime switch")
+ return
+ }
+
+ writeJSON(w, http.StatusOK, SwitchAgentBuilderRuntimeResponse{
+ RuntimeID: uuidToString(updated.RuntimeID),
+ })
+}
+
+// isAgentBuilderCarrier reports whether an agent is a hidden builder execution
+// carrier. Mirrors the kind/system_key guard the builder SQL statements carry, so
+// the handler rejects a non-builder session before reaching the database rather
+// than relying on an UPDATE matching zero rows.
+func isAgentBuilderCarrier(agent db.Agent) bool {
+ return agent.Kind == "system" &&
+ agent.SystemKey.Valid &&
+ strings.HasPrefix(agent.SystemKey.String, "agent_builder:")
+}
diff --git a/server/internal/handler/agent_builder_test.go b/server/internal/handler/agent_builder_test.go
index 2f1c566c1b..d8d4079848 100644
--- a/server/internal/handler/agent_builder_test.go
+++ b/server/internal/handler/agent_builder_test.go
@@ -7,6 +7,12 @@ import (
"net/http/httptest"
"strings"
"testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
func TestAgentBuilderInstructionsConstrainModelsToRuntimeCatalog(t *testing.T) {
@@ -159,3 +165,639 @@ func TestCreateAgentAttachesSkillsInCreateTransaction(t *testing.T) {
t.Fatalf("welcome chat sessions = %d, want 1", introSessions)
}
}
+
+// newBuilderSession starts a builder conversation on testRuntimeID and registers
+// cleanup for the carrier agents the flow creates.
+func newBuilderSession(t *testing.T) CreateAgentBuilderSessionResponse {
+ t.Helper()
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `
+ DELETE FROM agent
+ WHERE workspace_id = $1 AND kind = 'system' AND system_key LIKE 'agent_builder:%'
+ `, testWorkspaceID)
+ })
+
+ w := httptest.NewRecorder()
+ testHandler.CreateAgentBuilderSession(w, newRequest(http.MethodPost, "/api/agent-builder/sessions", map[string]any{
+ "runtime_id": testRuntimeID,
+ "model": "model-pinned-to-runtime-a",
+ }))
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateAgentBuilderSession: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var session CreateAgentBuilderSessionResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &session); err != nil {
+ t.Fatalf("decode create response: %v", err)
+ }
+ return session
+}
+
+// newTestRuntime inserts an extra runtime in the fixture workspace so switch
+// tests have somewhere to move to.
+func newTestRuntime(t *testing.T, name, status string) string {
+ t.Helper()
+ var runtimeID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at
+ )
+ VALUES ($1, NULL, $2, 'cloud', $3, $4, 'switch test runtime', '{}'::jsonb, $5, now())
+ RETURNING id
+ `, testWorkspaceID, name, strings.ToLower(strings.ReplaceAll(name, " ", "_")), status, testUserID).Scan(&runtimeID); err != nil {
+ t.Fatalf("create runtime %q: %v", name, err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)
+ })
+ return runtimeID
+}
+
+func switchBuilderRuntime(t *testing.T, sessionID, runtimeID string) *httptest.ResponseRecorder {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := withURLParams(
+ newRequest(http.MethodPatch, "/api/agent-builder/sessions/"+sessionID+"/runtime", map[string]any{
+ "runtime_id": runtimeID,
+ }),
+ "sessionId", sessionID,
+ )
+ testHandler.SwitchAgentBuilderRuntime(w, req)
+ return w
+}
+
+func TestSwitchAgentBuilderRuntimeRebindsCarrier(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ session := newBuilderSession(t)
+ target := newTestRuntime(t, "Builder Switch Target", "online")
+
+ w := switchBuilderRuntime(t, session.SessionID, target)
+ if w.Code != http.StatusOK {
+ t.Fatalf("SwitchAgentBuilderRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var response SwitchAgentBuilderRuntimeResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode switch response: %v", err)
+ }
+ if response.RuntimeID != target {
+ t.Fatalf("response runtime = %q, want %q", response.RuntimeID, target)
+ }
+
+ // The carrier is what stamps a chat task's runtime, so this row — not the
+ // client's local selection — is the fix.
+ var boundRuntimeID, boundRuntimeMode string
+ var boundModel pgtype.Text
+ if err := testPool.QueryRow(ctx, `
+ SELECT runtime_id::text, runtime_mode, model FROM agent WHERE id = $1
+ `, session.BuilderAgentID).Scan(&boundRuntimeID, &boundRuntimeMode, &boundModel); err != nil {
+ t.Fatalf("load builder carrier: %v", err)
+ }
+ if boundRuntimeID != target {
+ t.Fatalf("carrier runtime = %q, want %q", boundRuntimeID, target)
+ }
+ if boundRuntimeMode != "cloud" {
+ t.Fatalf("carrier runtime_mode = %q, want cloud", boundRuntimeMode)
+ }
+ if boundModel.Valid {
+ t.Fatalf("carrier model should be cleared on rebind, got %q", boundModel.String)
+ }
+
+ // Left deliberately stale: the daemon only resumes a stored provider session
+ // when this pointer matches the claiming task's runtime, so keeping the old
+ // value is what makes the new runtime start a fresh session.
+ var sessionRuntimeID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT runtime_id::text FROM chat_session WHERE id = $1
+ `, session.SessionID).Scan(&sessionRuntimeID); err != nil {
+ t.Fatalf("load chat session: %v", err)
+ }
+ if sessionRuntimeID != testRuntimeID {
+ t.Fatalf("chat_session.runtime_id = %q, want the original %q", sessionRuntimeID, testRuntimeID)
+ }
+}
+
+func TestSwitchAgentBuilderRuntimeRejectsOfflineTarget(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ session := newBuilderSession(t)
+ offline := newTestRuntime(t, "Builder Switch Offline", "offline")
+
+ if w := switchBuilderRuntime(t, session.SessionID, offline); w.Code != http.StatusConflict {
+ t.Fatalf("offline target: expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestSwitchAgentBuilderRuntimeRejectsWhileReplyPending(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ session := newBuilderSession(t)
+ target := newTestRuntime(t, "Builder Switch Pending Target", "online")
+
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO agent_task_queue (agent_id, chat_session_id, status, priority, context, runtime_id)
+ VALUES ($1, $2, 'running', 2, '{}'::jsonb, $3)
+ `, session.BuilderAgentID, session.SessionID, testRuntimeID); err != nil {
+ t.Fatalf("insert pending task: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE chat_session_id = $1`, session.SessionID)
+ })
+
+ if w := switchBuilderRuntime(t, session.SessionID, target); w.Code != http.StatusConflict {
+ t.Fatalf("pending reply: expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestSwitchAgentBuilderRuntimeRejectsNonBuilderSession(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ target := newTestRuntime(t, "Builder Switch Foreign Target", "online")
+
+ // A user-authored agent changes runtime through the agent update path; this
+ // endpoint must not be a second way in.
+ var userAgentID, userSessionID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id
+ )
+ VALUES ($1, 'Builder Switch User Agent', '', 'cloud', '{}'::jsonb, $2, 'workspace', 'public_to', 1, $3)
+ RETURNING id
+ `, testWorkspaceID, testRuntimeID, testUserID).Scan(&userAgentID); err != nil {
+ t.Fatalf("create user agent: %v", err)
+ }
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id)
+ VALUES ($1, $2, $3, 'Not a builder', $4)
+ RETURNING id
+ `, testWorkspaceID, userAgentID, testUserID, testRuntimeID).Scan(&userSessionID); err != nil {
+ t.Fatalf("create user chat session: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, userSessionID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, userAgentID)
+ })
+
+ if w := switchBuilderRuntime(t, userSessionID, target); w.Code != http.StatusNotFound {
+ t.Fatalf("user agent session: expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var stillBound string
+ if err := testPool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, userAgentID).Scan(&stillBound); err != nil {
+ t.Fatalf("reload user agent: %v", err)
+ }
+ if stillBound != testRuntimeID {
+ t.Fatalf("user agent runtime changed to %q; the builder endpoint must never touch it", stillBound)
+ }
+}
+
+// The regression this whole change exists for: a send that loaded the agent
+// before a rebind committed must still enqueue on the runtime the session is
+// bound to NOW. SendDirectChatMessage is handed the stale agent on purpose here
+// — that is exactly what its caller does when the two requests interleave.
+func TestSendDirectChatMessageUsesCurrentlyBoundRuntime(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ created := newBuilderSession(t)
+ target := newTestRuntime(t, "Builder Send Rebind Target", "online")
+
+ sessionUUID := parseUUID(created.SessionID)
+ session, err := testHandler.Queries.GetChatSession(ctx, sessionUUID)
+ if err != nil {
+ t.Fatalf("load chat session: %v", err)
+ }
+ staleAgent, err := testHandler.Queries.GetAgent(ctx, parseUUID(created.BuilderAgentID))
+ if err != nil {
+ t.Fatalf("load builder carrier: %v", err)
+ }
+ if uuidToString(staleAgent.RuntimeID) != testRuntimeID {
+ t.Fatalf("carrier should start on %q, got %q", testRuntimeID, uuidToString(staleAgent.RuntimeID))
+ }
+
+ if w := switchBuilderRuntime(t, created.SessionID, target); w.Code != http.StatusOK {
+ t.Fatalf("SwitchAgentBuilderRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE chat_session_id = $1`, created.SessionID)
+ })
+
+ sent, err := testHandler.TaskService.SendDirectChatMessage(
+ ctx, session, staleAgent, parseUUID(testUserID), "hello after the switch", nil, "member", parseUUID(testUserID),
+ )
+ if err != nil {
+ t.Fatalf("SendDirectChatMessage: %v", err)
+ }
+ if got := uuidToString(sent.Task.RuntimeID); got != target {
+ t.Fatalf("task runtime = %q, want the rebound runtime %q — a stale in-flight send must not resurrect the old runtime", got, target)
+ }
+}
+
+// holderBackendPID returns the server-side PID of the backend serving tx, so a
+// waiter can later be attributed to this specific lock holder.
+func holderBackendPID(t *testing.T, ctx context.Context, tx pgx.Tx) int {
+ t.Helper()
+ var pid int
+ if err := tx.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&pid); err != nil {
+ t.Fatalf("read holder backend pid: %v", err)
+ }
+ return pid
+}
+
+// waitForWaiterBlockedBy blocks until some backend is waiting on a lock held by
+// holderPID, which is how the interleaving tests below observe "the other side
+// is parked on our chat_session row" without guessing at timings.
+//
+// pg_blocking_pids is what makes this specific. `go test ./...` runs package
+// test binaries in parallel against one DATABASE_URL, so a probe for "any
+// Lock-waiting backend" could match an unrelated package and let the holder
+// commit early — after which the path under test would start clean, read the
+// committed state, and pass even with its lock removed. Attributing the waiter
+// to this transaction's PID removes that false-green path.
+//
+// Returns false only after the deadline with no attributable waiter, which is
+// the signal that the path under test never took the lock. A probe error is
+// fatal rather than swallowed: a permissions or connectivity failure must not
+// be reported as "that path is not locking".
+func waitForWaiterBlockedBy(t *testing.T, holderPID int, timeout time.Duration) bool {
+ t.Helper()
+ deadline := time.Now().Add(timeout)
+ for {
+ var waiting int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM pg_stat_activity
+ WHERE datname = current_database()
+ AND state = 'active'
+ AND wait_event_type = 'Lock'
+ AND $1::int = ANY(pg_blocking_pids(pid))
+ `, holderPID).Scan(&waiting); err != nil {
+ t.Fatalf("probe pg_stat_activity for waiters blocked by pid %d: %v", holderPID, err)
+ }
+ if waiting > 0 {
+ return true
+ }
+ if time.Now().After(deadline) {
+ return false
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+// A rebind that has not committed yet must hold off a concurrent send, and the
+// send must then observe the NEW runtime. This is the half of the protocol the
+// lock owns: with the lock removed the send reads straight through the
+// uncommitted rebind under READ COMMITTED, sees the pre-switch runtime, and
+// enqueues the reply on the runtime the user just switched away from.
+func TestSendDirectChatMessageWaitsForUncommittedRebind(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ created := newBuilderSession(t)
+ target := newTestRuntime(t, "Builder Interleave Send Target", "online")
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE chat_session_id = $1`, created.SessionID)
+ })
+
+ session, err := testHandler.Queries.GetChatSession(ctx, parseUUID(created.SessionID))
+ if err != nil {
+ t.Fatalf("load chat session: %v", err)
+ }
+ // The agent as the send handler would have loaded it: still on runtime A.
+ staleAgent, err := testHandler.Queries.GetAgent(ctx, parseUUID(created.BuilderAgentID))
+ if err != nil {
+ t.Fatalf("load builder carrier: %v", err)
+ }
+
+ // Hold an uncommitted rebind, exactly as SwitchAgentBuilderRuntime does.
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin rebind tx: %v", err)
+ }
+ defer tx.Rollback(context.Background())
+ holderPID := holderBackendPID(t, ctx, tx)
+ qtx := testHandler.Queries.WithTx(tx)
+ if _, err := qtx.LockChatSessionForRuntimeBind(ctx, session.ID); err != nil {
+ t.Fatalf("lock chat session: %v", err)
+ }
+ targetRuntime, err := testHandler.Queries.GetAgentRuntimeForWorkspace(ctx, db.GetAgentRuntimeForWorkspaceParams{
+ ID: parseUUID(target),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("load target runtime: %v", err)
+ }
+ if _, err := qtx.RebindAgentBuilderRuntime(ctx, db.RebindAgentBuilderRuntimeParams{
+ ID: staleAgent.ID,
+ RuntimeID: targetRuntime.ID,
+ RuntimeMode: targetRuntime.RuntimeMode,
+ }); err != nil {
+ t.Fatalf("rebind carrier: %v", err)
+ }
+
+ type sendResult struct {
+ task db.AgentTaskQueue
+ err error
+ }
+ results := make(chan sendResult, 1)
+ go func() {
+ sent, err := testHandler.TaskService.SendDirectChatMessage(
+ context.Background(), session, staleAgent, parseUUID(testUserID),
+ "sent while the rebind was still open", nil, "member", parseUUID(testUserID),
+ )
+ if err != nil {
+ results <- sendResult{err: err}
+ return
+ }
+ results <- sendResult{task: sent.Task}
+ }()
+
+ if !waitForWaiterBlockedBy(t, holderPID, 10*time.Second) {
+ select {
+ case got := <-results:
+ t.Fatalf("send completed (err=%v, runtime=%q) while an uncommitted rebind held the chat_session lock; the send path is not taking the lock",
+ got.err, uuidToString(got.task.RuntimeID))
+ default:
+ t.Fatalf("send never blocked on the chat_session lock held by pid %d; the send path is not taking the lock", holderPID)
+ }
+ }
+ select {
+ case got := <-results:
+ t.Fatalf("send returned (err=%v) before the rebind committed", got.err)
+ default:
+ }
+
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatalf("commit rebind: %v", err)
+ }
+
+ select {
+ case got := <-results:
+ if got.err != nil {
+ t.Fatalf("SendDirectChatMessage after commit: %v", got.err)
+ }
+ if runtimeID := uuidToString(got.task.RuntimeID); runtimeID != target {
+ t.Fatalf("task runtime = %q, want the rebound runtime %q", runtimeID, target)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("send did not complete after the rebind committed")
+ }
+}
+
+// The mirror image: a send that has not committed yet must hold off a rebind,
+// and the rebind must then see the now-visible pending task and refuse. Without
+// the lock on the switch side, GetPendingChatTask cannot see the uncommitted
+// task, so the switch reports success while a reply is already in flight on the
+// old runtime — the same "UI says B, execution is A" split, one turn later.
+func TestSwitchAgentBuilderRuntimeWaitsForUncommittedSend(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ created := newBuilderSession(t)
+ target := newTestRuntime(t, "Builder Interleave Switch Target", "online")
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE chat_session_id = $1`, created.SessionID)
+ })
+
+ // Hold an uncommitted send: the chat_session lock plus its task row, in the
+ // order SendDirectChatMessage takes them.
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin send tx: %v", err)
+ }
+ defer tx.Rollback(context.Background())
+ holderPID := holderBackendPID(t, ctx, tx)
+ qtx := testHandler.Queries.WithTx(tx)
+ if _, err := qtx.LockChatSessionForRuntimeBind(ctx, parseUUID(created.SessionID)); err != nil {
+ t.Fatalf("lock chat session: %v", err)
+ }
+ if _, err := tx.Exec(ctx, `
+ INSERT INTO agent_task_queue (agent_id, chat_session_id, status, priority, context, runtime_id)
+ VALUES ($1, $2, 'queued', 2, '{}'::jsonb, $3)
+ `, created.BuilderAgentID, created.SessionID, testRuntimeID); err != nil {
+ t.Fatalf("insert in-flight task: %v", err)
+ }
+
+ codes := make(chan int, 1)
+ go func() {
+ w := httptest.NewRecorder()
+ req := withURLParams(
+ newRequest(http.MethodPatch, "/api/agent-builder/sessions/"+created.SessionID+"/runtime", map[string]any{
+ "runtime_id": target,
+ }),
+ "sessionId", created.SessionID,
+ )
+ testHandler.SwitchAgentBuilderRuntime(w, req)
+ codes <- w.Code
+ }()
+
+ if !waitForWaiterBlockedBy(t, holderPID, 10*time.Second) {
+ select {
+ case code := <-codes:
+ t.Fatalf("switch returned %d while an uncommitted send held the chat_session lock; the switch path is not taking the lock", code)
+ default:
+ t.Fatalf("switch never blocked on the chat_session lock held by pid %d; the switch path is not taking the lock", holderPID)
+ }
+ }
+
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatalf("commit send: %v", err)
+ }
+
+ select {
+ case code := <-codes:
+ if code != http.StatusConflict {
+ t.Fatalf("switch returned %d after the send committed, want 409 — a reply is in flight", code)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("switch did not complete after the send committed")
+ }
+
+ // And the carrier must be untouched: a refused switch cannot half-apply.
+ var boundRuntimeID string
+ if err := testPool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, created.BuilderAgentID).Scan(&boundRuntimeID); err != nil {
+ t.Fatalf("reload builder carrier: %v", err)
+ }
+ if boundRuntimeID != testRuntimeID {
+ t.Fatalf("carrier runtime = %q after a refused switch, want the original %q", boundRuntimeID, testRuntimeID)
+ }
+}
+
+func TestSwitchAgentBuilderRuntimeEnforcesRuntimeAndSessionOwnership(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ // A plain member, so canUseRuntimeForAgent's owner/admin bypass does not
+ // apply — the fixture user is the workspace owner and may legitimately use
+ // anyone's private runtime.
+ var plainMemberID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO "user" (name, email) VALUES ('Builder Switch Plain Member', '[email protected]')
+ RETURNING id
+ `).Scan(&plainMemberID); err != nil {
+ t.Fatalf("create plain member user: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, plainMemberID)
+ })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')
+ `, testWorkspaceID, plainMemberID); err != nil {
+ t.Fatalf("add plain member: %v", err)
+ }
+
+ // The fixture runtime is private to the workspace owner, so start this
+ // member's session on a public one.
+ var publicRuntimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, visibility, last_seen_at
+ )
+ VALUES ($1, NULL, 'Builder Switch Public', 'cloud', 'builder_switch_public', 'online', 'public', '{}'::jsonb, $2, 'public', now())
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&publicRuntimeID); err != nil {
+ t.Fatalf("create public runtime: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, publicRuntimeID)
+ })
+
+ // That member's own builder session, so the creator gate passes and the
+ // runtime gate is what we are actually testing.
+ createW := httptest.NewRecorder()
+ testHandler.CreateAgentBuilderSession(createW, newRequestAs(plainMemberID, http.MethodPost, "/api/agent-builder/sessions", map[string]any{
+ "runtime_id": publicRuntimeID,
+ }))
+ if createW.Code != http.StatusCreated {
+ t.Fatalf("CreateAgentBuilderSession as plain member: expected 201, got %d: %s", createW.Code, createW.Body.String())
+ }
+ var created CreateAgentBuilderSessionResponse
+ if err := json.Unmarshal(createW.Body.Bytes(), &created); err != nil {
+ t.Fatalf("decode create response: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `
+ DELETE FROM agent
+ WHERE workspace_id = $1 AND kind = 'system' AND system_key LIKE 'agent_builder:%'
+ `, testWorkspaceID)
+ })
+
+ // The workspace owner's private runtime is not a legal target for them.
+ var privateRuntimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, visibility, last_seen_at
+ )
+ VALUES ($1, NULL, 'Builder Switch Private', 'cloud', 'builder_switch_private', 'online', 'private', '{}'::jsonb, $2, 'private', now())
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&privateRuntimeID); err != nil {
+ t.Fatalf("create private runtime: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, privateRuntimeID)
+ })
+
+ forbiddenW := httptest.NewRecorder()
+ testHandler.SwitchAgentBuilderRuntime(forbiddenW, withURLParams(
+ newRequestAs(plainMemberID, http.MethodPatch, "/api/agent-builder/sessions/"+created.SessionID+"/runtime", map[string]any{
+ "runtime_id": privateRuntimeID,
+ }),
+ "sessionId", created.SessionID,
+ ))
+ if forbiddenW.Code != http.StatusForbidden {
+ t.Fatalf("someone else's private runtime: expected 403, got %d: %s", forbiddenW.Code, forbiddenW.Body.String())
+ }
+
+ // And a session the caller does not own is not theirs to rebind, whatever
+ // their workspace role — this one is issued by the workspace owner.
+ target := newTestRuntime(t, "Builder Switch Ownership Target", "online")
+ if w := switchBuilderRuntime(t, created.SessionID, target); w.Code != http.StatusForbidden {
+ t.Fatalf("someone else's session: expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var boundRuntimeID string
+ if err := testPool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, created.BuilderAgentID).Scan(&boundRuntimeID); err != nil {
+ t.Fatalf("reload builder carrier: %v", err)
+ }
+ if boundRuntimeID != publicRuntimeID {
+ t.Fatalf("carrier runtime = %q after refused switches, want the original %q", boundRuntimeID, publicRuntimeID)
+ }
+}
+
+// The probe above is only as good as its attribution: a database-wide "is
+// anything waiting on a lock?" check would match another package's test binary
+// on the shared DATABASE_URL and let the interleaving tests commit their holder
+// early, turning them green even with the lock under test removed. This pins the
+// property directly — a waiter blocked by a DIFFERENT backend must not count.
+func TestWaitForWaiterBlockedByIgnoresUnrelatedWaiters(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ mine := newBuilderSession(t)
+ theirs := newBuilderSession(t)
+
+ // Our holder: locks our own session and blocks nobody.
+ holderTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin holder tx: %v", err)
+ }
+ defer holderTx.Rollback(context.Background())
+ holderPID := holderBackendPID(t, ctx, holderTx)
+ if _, err := holderTx.Exec(ctx, `SELECT id FROM chat_session WHERE id = $1 FOR UPDATE`, mine.SessionID); err != nil {
+ t.Fatalf("hold our own session lock: %v", err)
+ }
+
+ // An unrelated holder on a different row, plus a backend parked behind it —
+ // the shape of another package's test running against the same database.
+ otherTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin unrelated holder tx: %v", err)
+ }
+ defer otherTx.Rollback(context.Background())
+ otherPID := holderBackendPID(t, ctx, otherTx)
+ if _, err := otherTx.Exec(ctx, `SELECT id FROM chat_session WHERE id = $1 FOR UPDATE`, theirs.SessionID); err != nil {
+ t.Fatalf("hold unrelated session lock: %v", err)
+ }
+
+ blocked := make(chan struct{})
+ go func() {
+ defer close(blocked)
+ waiterTx, err := testPool.Begin(context.Background())
+ if err != nil {
+ return
+ }
+ defer waiterTx.Rollback(context.Background())
+ _, _ = waiterTx.Exec(context.Background(), `SELECT id FROM chat_session WHERE id = $1 FOR UPDATE`, theirs.SessionID)
+ }()
+
+ // The unrelated waiter is genuinely parked, so a database-wide probe would
+ // fire here.
+ if !waitForWaiterBlockedBy(t, otherPID, 10*time.Second) {
+ t.Fatal("the unrelated waiter never blocked; this test cannot prove anything")
+ }
+ // Attributed to our holder, it must not.
+ if waitForWaiterBlockedBy(t, holderPID, 500*time.Millisecond) {
+ t.Fatal("probe matched a waiter blocked by another backend; the interleaving tests could commit their holder early and pass with the lock removed")
+ }
+
+ if err := otherTx.Rollback(ctx); err != nil {
+ t.Fatalf("release unrelated lock: %v", err)
+ }
+ select {
+ case <-blocked:
+ case <-time.After(10 * time.Second):
+ t.Fatal("unrelated waiter did not finish after its blocker released")
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 2900d42085..741d28d4b2 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1499,7 +1499,8 @@ type DirectChatSendResult struct {
//
// The caller must have already gated the session and preflighted the agent
// (archived / no-runtime), passing the loaded agent in; this method trusts those
-// checks and does no further agent validation.
+// permission checks. It does NOT trust the agent's runtime_id: that field is
+// re-read inside the transaction (see below).
func (s *TaskService) SendDirectChatMessage(ctx context.Context, session db.ChatSession, agent db.Agent, initiatorUserID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, uploaderType string, uploaderID pgtype.UUID) (*DirectChatSendResult, error) {
// Build the per-task Composio overlay before the transaction — it can do
// network I/O and must not run with a DB transaction open.
@@ -1519,9 +1520,28 @@ func (s *TaskService) SendDirectChatMessage(ctx context.Context, session db.Chat
var out DirectChatSendResult
if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ // Serialise this send against a concurrent runtime rebind of the same
+ // session (MUL-5163). The lock must be taken first and the agent re-read
+ // under it: the runtime_id the caller loaded can already be stale by the
+ // time we get here, and a send blocked behind a rebind would otherwise
+ // resume and stamp its task with the runtime the switch just moved away
+ // from — leaving the user with a "switched" confirmation and a reply
+ // running on the old runtime. Locking chat_session first also matches the
+ // delete path's lock order, so the two cannot deadlock.
+ if _, err := qtx.LockChatSessionForRuntimeBind(ctx, session.ID); err != nil {
+ return fmt.Errorf("lock chat session: %w", err)
+ }
+ carrier, err := qtx.GetAgent(ctx, session.AgentID)
+ if err != nil {
+ return fmt.Errorf("reload chat agent: %w", err)
+ }
+ if !carrier.RuntimeID.Valid {
+ return ErrChatTaskAgentNoRuntime
+ }
+
task, err := qtx.CreateChatTask(ctx, db.CreateChatTaskParams{
AgentID: session.AgentID,
- RuntimeID: agent.RuntimeID,
+ RuntimeID: carrier.RuntimeID,
Priority: 2, // medium priority for chat; matches EnqueueChatTask
ChatSessionID: session.ID,
InitiatorUserID: initiatorUserID,
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 44f85cb22b..084222f2d9 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -4353,6 +4353,79 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, runtim
return items, nil
}
+const rebindAgentBuilderRuntime = `-- name: RebindAgentBuilderRuntime :one
+UPDATE agent
+SET runtime_id = $1,
+ runtime_mode = $2,
+ model = $3,
+ updated_at = now()
+WHERE id = $4 AND kind = 'system' AND system_key LIKE 'agent_builder:%'
+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills
+`
+
+type RebindAgentBuilderRuntimeParams struct {
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ RuntimeMode string `json:"runtime_mode"`
+ Model pgtype.Text `json:"model"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// Re-points a builder carrier at another runtime mid-conversation. The carrier
+// is what SendDirectChatMessage reads to stamp a chat task's runtime_id, so this
+// UPDATE is the only thing that actually moves subsequent replies; the live-draft
+// picker alone never did. model is reset wholesale because model ids are
+// per-runtime — the new runtime resolves its own default instead of inheriting an
+// id it may not serve. The kind/system_key guard mirrors DeleteSystemAgentByID so
+// this path can never touch a user-authored agent.
+//
+// Callers MUST hold LockChatSessionForRuntimeBind on the owning chat_session for
+// the whole transaction, otherwise a concurrent send can stamp a task with the
+// pre-switch runtime after the pending-task check has already passed (MUL-5163).
+//
+// chat_session.runtime_id is deliberately left untouched: the daemon only resumes
+// a stored provider session when chat_session.runtime_id matches the claiming
+// task's runtime (see the chat claim path), so leaving the old pointer in place is
+// exactly what makes the new runtime start a fresh provider session.
+func (q *Queries) RebindAgentBuilderRuntime(ctx context.Context, arg RebindAgentBuilderRuntimeParams) (Agent, error) {
+ row := q.db.QueryRow(ctx, rebindAgentBuilderRuntime,
+ arg.RuntimeID,
+ arg.RuntimeMode,
+ arg.Model,
+ arg.ID,
+ )
+ var i Agent
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.AvatarUrl,
+ &i.RuntimeMode,
+ &i.RuntimeConfig,
+ &i.Visibility,
+ &i.Status,
+ &i.MaxConcurrentTasks,
+ &i.OwnerID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Description,
+ &i.RuntimeID,
+ &i.Instructions,
+ &i.ArchivedAt,
+ &i.ArchivedBy,
+ &i.CustomEnv,
+ &i.CustomArgs,
+ &i.McpConfig,
+ &i.Model,
+ &i.ThinkingLevel,
+ &i.ComposioToolkitAllowlist,
+ &i.PermissionMode,
+ &i.Kind,
+ &i.SystemKey,
+ &i.DisabledRuntimeSkills,
+ )
+ return i, err
+}
+
const reclaimStaleDispatchedTaskForRuntime = `-- name: ReclaimStaleDispatchedTaskForRuntime :one
UPDATE agent_task_queue
SET dispatched_at = now(),
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 4457f05e0d..d682e63f17 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -1046,6 +1046,35 @@ func (q *Queries) LockChatSessionForDelete(ctx context.Context, id pgtype.UUID)
return id_2, err
}
+const lockChatSessionForRuntimeBind = `-- name: LockChatSessionForRuntimeBind :one
+SELECT id FROM chat_session
+WHERE id = $1
+FOR UPDATE
+`
+
+// Acquires an exclusive (FOR UPDATE) row lock on chat_session(id), serialising
+// "which runtime does this session execute on" against "enqueue the next task".
+//
+// Both SendDirectChatMessage and the agent-builder runtime switch take this lock
+// for their whole transaction. Without it the two are a read-then-write race: a
+// send reads the carrier agent's runtime_id, the switch then passes its
+// pending-task check and rebinds the carrier, and the send finally inserts a task
+// still stamped with the pre-switch runtime — so the user is told the switch
+// succeeded while their message runs on the old runtime (MUL-5163).
+//
+// The lock alone is not sufficient: the send path must also re-read the agent
+// INSIDE the locked transaction, because a send blocked at INSERT would otherwise
+// resume and write the runtime_id it read before blocking.
+//
+// Same row and same lock mode as LockChatSessionForDelete, and both take it as
+// their first statement, so the delete path and this one cannot deadlock.
+func (q *Queries) LockChatSessionForRuntimeBind(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockChatSessionForRuntimeBind, id)
+ var id_2 pgtype.UUID
+ err := row.Scan(&id_2)
+ return id_2, err
+}
+
const lockChatSessionForTask = `-- name: LockChatSessionForTask :one
SELECT cs.id
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 1da59ddf2b..a89addc33f 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -61,6 +61,31 @@ RETURNING *;
DELETE FROM agent
WHERE id = $1 AND kind = 'system' AND system_key LIKE 'agent_builder:%';
+-- name: RebindAgentBuilderRuntime :one
+-- Re-points a builder carrier at another runtime mid-conversation. The carrier
+-- is what SendDirectChatMessage reads to stamp a chat task's runtime_id, so this
+-- UPDATE is the only thing that actually moves subsequent replies; the live-draft
+-- picker alone never did. model is reset wholesale because model ids are
+-- per-runtime — the new runtime resolves its own default instead of inheriting an
+-- id it may not serve. The kind/system_key guard mirrors DeleteSystemAgentByID so
+-- this path can never touch a user-authored agent.
+--
+-- Callers MUST hold LockChatSessionForRuntimeBind on the owning chat_session for
+-- the whole transaction, otherwise a concurrent send can stamp a task with the
+-- pre-switch runtime after the pending-task check has already passed (MUL-5163).
+--
+-- chat_session.runtime_id is deliberately left untouched: the daemon only resumes
+-- a stored provider session when chat_session.runtime_id matches the claiming
+-- task's runtime (see the chat claim path), so leaving the old pointer in place is
+-- exactly what makes the new runtime start a fresh provider session.
+UPDATE agent
+SET runtime_id = @runtime_id,
+ runtime_mode = @runtime_mode,
+ model = sqlc.narg('model'),
+ updated_at = now()
+WHERE id = @id AND kind = 'system' AND system_key LIKE 'agent_builder:%'
+RETURNING *;
+
-- name: UpdateAgent :one
-- composio_toolkit_allowlist is set wholesale: the API layer is responsible
-- for normalising the request payload to either (a) the new slug list — sent
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index bb1a7d87be..b72f9036f9 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -132,6 +132,27 @@ SELECT id FROM chat_session
WHERE id = $1
FOR UPDATE;
+-- name: LockChatSessionForRuntimeBind :one
+-- Acquires an exclusive (FOR UPDATE) row lock on chat_session(id), serialising
+-- "which runtime does this session execute on" against "enqueue the next task".
+--
+-- Both SendDirectChatMessage and the agent-builder runtime switch take this lock
+-- for their whole transaction. Without it the two are a read-then-write race: a
+-- send reads the carrier agent's runtime_id, the switch then passes its
+-- pending-task check and rebinds the carrier, and the send finally inserts a task
+-- still stamped with the pre-switch runtime — so the user is told the switch
+-- succeeded while their message runs on the old runtime (MUL-5163).
+--
+-- The lock alone is not sufficient: the send path must also re-read the agent
+-- INSIDE the locked transaction, because a send blocked at INSERT would otherwise
+-- resume and write the runtime_id it read before blocking.
+--
+-- Same row and same lock mode as LockChatSessionForDelete, and both take it as
+-- their first statement, so the delete path and this one cannot deadlock.
+SELECT id FROM chat_session
+WHERE id = $1
+FOR UPDATE;
+
-- name: DeleteChatSession :exec
-- Hard delete. chat_message rows cascade via FK ON DELETE CASCADE; the
-- chat_session_id on agent_task_queue is set NULL by FK so completed/failed