Skip to content

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

Go

MUL-5642: fix(agents): stop the creation studio polling, and stop it losing work (#6307)

Naiyuan Qinga5c1d44701d8
diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsx
index 6a1db5b751..accaef575a 100644
--- a/apps/desktop/src/renderer/src/routes.tsx
+++ b/apps/desktop/src/renderer/src/routes.tsx
@@ -20,7 +20,11 @@ import { MyIssuesPage } from "@multica/views/my-issues";
import { SkillsPage } from "@multica/views/skills";
import { DesktopRuntimesPage } from "./components/desktop-runtimes-page";
import { DesktopAgentsPage } from "./components/desktop-agents-page";
-import { AgentCreationStudio } from "@multica/views/agents";
+import {
+ AiCreateAgentPage,
+ ChooseCreateMethodPage,
+ ManualCreateAgentPage,
+} from "@multica/views/agents";
import { SquadsPage, SquadDetailPage as SquadDetailPageView } from "@multica/views/squads/components";
import { InboxPage } from "@multica/views/inbox";
import { ChatPage } from "@multica/views/chat";
@@ -179,7 +183,21 @@ export const appRoutes: RouteObject[] = [
handle: { title: "Skill" },
},
{ path: "agents", element: <DesktopAgentsPage />, handle: { title: "Agents" } },
- { path: "agents/new", element: <AgentCreationStudio />, handle: { title: "Create Agent" } },
+ {
+ path: "agents/new",
+ element: <ChooseCreateMethodPage />,
+ handle: { title: "Create Agent" },
+ },
+ {
+ path: "agents/new/manual",
+ element: <ManualCreateAgentPage />,
+ handle: { title: "Create Agent" },
+ },
+ {
+ path: "agents/new/ai",
+ element: <AiCreateAgentPage />,
+ handle: { title: "Create Agent" },
+ },
{
path: "agents/:id",
element: <AgentDetailPage />,
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/ai/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/ai/page.tsx
new file mode 100644
index 0000000000..9f00f3793e
--- /dev/null
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/ai/page.tsx
@@ -0,0 +1,5 @@
+import { AiCreateAgentPage } from "@multica/views/agents";
+
+export default function NewAgentAiRoute() {
+ return <AiCreateAgentPage />;
+}
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/manual/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/manual/page.tsx
new file mode 100644
index 0000000000..33e82d36c0
--- /dev/null
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/manual/page.tsx
@@ -0,0 +1,5 @@
+import { ManualCreateAgentPage } from "@multica/views/agents";
+
+export default function NewAgentManualRoute() {
+ return <ManualCreateAgentPage />;
+}
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/page.tsx
index f2551163c0..8dfc637274 100644
--- a/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/page.tsx
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/page.tsx
@@ -1,5 +1,5 @@
-import { AgentCreationStudio } from "@multica/views/agents";
+import { ChooseCreateMethodPage } from "@multica/views/agents";
export default function NewAgentRoute() {
- return <AgentCreationStudio />;
+ return <ChooseCreateMethodPage />;
}
diff --git a/packages/core/agents/builder-protocol.test.ts b/packages/core/agents/builder-protocol.test.ts
new file mode 100644
index 0000000000..71aec0f687
--- /dev/null
+++ b/packages/core/agents/builder-protocol.test.ts
@@ -0,0 +1,258 @@
+import { describe, expect, it } from "vitest";
+import {
+ decodeBuilderInput,
+ encodeBuilderInput,
+ mergeBuilderDraft,
+ parseBuilderDraft,
+ pickBuilderRestore,
+ stripBuilderDraft,
+} from "./builder-protocol";
+import type { AgentDraft } from "./draft";
+
+const draft = (): AgentDraft => ({
+ name: "Old name",
+ description: "Old description",
+ instructions: "Old instructions",
+ avatarUrl: null,
+ runtimeId: "runtime-1",
+ model: "model-1",
+ thinkingLevel: "",
+ serviceTier: "",
+ skillIds: new Set(["skill-1"]),
+ permissionScope: "private",
+ memberIds: new Set(),
+ teamIds: new Set(),
+});
+
+describe("agent builder protocol", () => {
+ it("parses and hides the structured draft block", () => {
+ const content =
+ 'Here is a first draft.\n<agent_draft>{"name":"Researcher","permission_scope":"workspace"}</agent_draft>';
+
+ expect(parseBuilderDraft(content)).toEqual({
+ name: "Researcher",
+ permission_scope: "workspace",
+ });
+ expect(stripBuilderDraft(content)).toBe("Here is a first draft.");
+ expect(parseBuilderDraft("<agent_draft>not json</agent_draft>")).toBeNull();
+ });
+
+ // Streaming delivers the reply token by token, so for the seconds it takes to
+ // emit the JSON there is an opening tag and no closing one. The closed-form
+ // pattern cannot match that, and the raw payload scrolled past the user on
+ // every turn.
+ it("hides a block that is still being streamed", () => {
+ expect(
+ stripBuilderDraft('Here you go.\n<agent_draft>{"name":"Rel'),
+ ).toBe("Here you go.");
+ });
+
+ it("repairs literal line breaks emitted inside the instructions string", () => {
+ const content = `<agent_draft>{"name":"Reviewer","instructions":"# Role
+Review every change.
+
+# Output
+Return findings."}</agent_draft>`;
+
+ expect(parseBuilderDraft(content)).toEqual({
+ name: "Reviewer",
+ instructions: "# Role\nReview every change.\n\n# Output\nReturn findings.",
+ });
+ });
+
+ it("round-trips only the user's natural-language request for chat display", () => {
+ const content = encodeBuilderInput(
+ "Create a release manager",
+ draft(),
+ [],
+ [],
+ { id: "runtime-1", name: "Codex", provider: "codex" },
+ [{ id: "gpt-5.5", label: "GPT-5.5", provider: "openai" }],
+ );
+
+ expect(decodeBuilderInput(content)).toBe("Create a release manager");
+ expect(JSON.parse(content.slice(content.indexOf("\n") + 1))).toMatchObject({
+ selected_runtime: {
+ id: "runtime-1",
+ name: "Codex",
+ provider: "codex",
+ },
+ available_runtime_models: [
+ { id: "gpt-5.5", label: "GPT-5.5", provider: "openai" },
+ ],
+ });
+ expect(decodeBuilderInput("ordinary chat message")).toBe(
+ "ordinary chat message",
+ );
+ });
+
+ // The builder chat is a real chat_session, so cancelling a started-but-empty
+ // run defers the empty/non-empty judgment (#5219): the cancel response carries
+ // no restore_to_input and the prompt arrives later as a durable draft-restore
+ // row holding the ENCODED message. Handing that to the composer raw would show
+ // the user a wall of JSON instead of the sentence they typed.
+ it("decodes a durable draft restore before the builder composer adopts it", () => {
+ const encoded = encodeBuilderInput(
+ "Create a release manager",
+ draft(),
+ [],
+ [],
+ { id: "runtime-1", name: "Codex", provider: "codex" },
+ [],
+ );
+
+ expect(pickBuilderRestore(null, { id: "msg-1", content: encoded })).toEqual({
+ id: "msg-1",
+ content: "Create a release manager",
+ });
+ expect(pickBuilderRestore(null, null)).toBeNull();
+ });
+
+ // The synchronous answer (task never started) is already decoded and already
+ // in hand; it must not be displaced by a durable row for the same cancel.
+ it("prefers the synchronous cancel answer over a durable restore", () => {
+ expect(
+ pickBuilderRestore(
+ { id: "msg-1", content: "Create a release manager" },
+ { id: "msg-1", content: "should not win" },
+ ),
+ ).toEqual({ id: "msg-1", content: "Create a release manager" });
+ });
+
+ it("merges safe fields and rejects unknown workspace references", () => {
+ const result = mergeBuilderDraft(
+ draft(),
+ {
+ name: "Release manager",
+ model: 123,
+ skill_ids: ["skill-2", "unknown-skill"],
+ permission_scope: "members",
+ member_ids: ["member-1", "unknown-member"],
+ },
+ new Set(["skill-1", "skill-2"]),
+ new Set(["member-1"]),
+ new Set(["model-1"]),
+ );
+
+ expect(result.name).toBe("Release manager");
+ expect(result.model).toBe("model-1");
+ expect([...result.skillIds]).toEqual(["skill-2"]);
+ expect(result.permissionScope).toBe("members");
+ expect([...result.memberIds]).toEqual(["member-1"]);
+ });
+
+ it("accepts catalog models and rejects invented or cross-runtime models", () => {
+ const validModelIds = new Set(["gpt-5.5", "gpt-5.3-codex"]);
+
+ expect(
+ mergeBuilderDraft(
+ draft(),
+ { model: "gpt-5.5" },
+ new Set(),
+ new Set(),
+ validModelIds,
+ ).model,
+ ).toBe("gpt-5.5");
+ expect(
+ mergeBuilderDraft(
+ draft(),
+ { model: "claude-3-5-sonnet" },
+ new Set(),
+ new Set(),
+ validModelIds,
+ ).model,
+ ).toBe("model-1");
+ expect(
+ mergeBuilderDraft(
+ draft(),
+ { model: "invented-model" },
+ new Set(),
+ new Set(),
+ validModelIds,
+ ).model,
+ ).toBe("model-1");
+ expect(
+ mergeBuilderDraft(
+ draft(),
+ { model: "" },
+ new Set(),
+ new Set(),
+ validModelIds,
+ ).model,
+ ).toBe("");
+ });
+
+ it("preserves a user-selected custom model when the catalog is unavailable", () => {
+ expect(
+ mergeBuilderDraft(
+ draft(),
+ { model: "invented-model" },
+ new Set(),
+ new Set(),
+ null,
+ ).model,
+ ).toBe("model-1");
+ expect(
+ mergeBuilderDraft(draft(), { model: "model-1" }, new Set(), new Set(), null)
+ .model,
+ ).toBe("model-1");
+ expect(
+ mergeBuilderDraft(
+ draft(),
+ { model: "invented-model" },
+ new Set(),
+ new Set(),
+ new Set(),
+ ).model,
+ ).toBe("model-1");
+ expect(
+ mergeBuilderDraft(draft(), { model: "" }, new Set(), new Set(), new Set())
+ .model,
+ ).toBe("model-1");
+ });
+
+ it("keeps the overrides while the AI builder leaves the model alone", () => {
+ const current = {
+ ...draft(),
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ };
+
+ expect(
+ mergeBuilderDraft(
+ current,
+ { name: "Renamed" },
+ new Set(),
+ new Set(),
+ new Set(["model-1"]),
+ ),
+ ).toMatchObject({
+ name: "Renamed",
+ model: "model-1",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ });
+ });
+
+ it("drops the overrides when the AI builder moves the model", () => {
+ const current = {
+ ...draft(),
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ };
+
+ expect(
+ mergeBuilderDraft(
+ current,
+ { model: "gpt-5.4-mini" },
+ new Set(),
+ new Set(),
+ new Set(["model-1", "gpt-5.4-mini"]),
+ ),
+ ).toMatchObject({
+ model: "gpt-5.4-mini",
+ thinkingLevel: "",
+ serviceTier: "",
+ });
+ });
+});
diff --git a/packages/core/agents/builder-protocol.ts b/packages/core/agents/builder-protocol.ts
new file mode 100644
index 0000000000..7120d934bc
--- /dev/null
+++ b/packages/core/agents/builder-protocol.ts
@@ -0,0 +1,269 @@
+import type { RuntimeDevice, RuntimeModel } from "../types";
+import type { AgentDraft } from "./draft";
+
+/**
+ * Wire format between the Agent Creation Studio and the hidden builder agent.
+ *
+ * Two asymmetric directions:
+ * - Outbound, the composer's plain text is wrapped in a JSON envelope that
+ * also carries the current draft and the catalogs the builder may pick IDs
+ * from, so every turn re-states the full decision context.
+ * - Inbound, the builder appends one `<agent_draft>` JSON block to its natural
+ * language reply; the block updates the form and is stripped before the
+ * message is rendered.
+ *
+ * Both directions are parsed defensively: a CLI-backed model can emit slightly
+ * malformed JSON, and a draft that fails to parse must degrade to "no form
+ * update" rather than breaking the conversation.
+ */
+const BUILDER_INPUT_PREFIX = "MULTICA_AGENT_BUILDER_INPUT\n";
+
+export interface BuilderDraftPayload {
+ name?: unknown;
+ description?: unknown;
+ instructions?: unknown;
+ model?: unknown;
+ skill_ids?: unknown;
+ permission_scope?: unknown;
+ member_ids?: unknown;
+}
+
+export function parseBuilderDraft(content: string): BuilderDraftPayload | null {
+ const match = content.match(/<agent_draft>([\s\S]*?)<\/agent_draft>/);
+ if (!match?.[1]) return null;
+ try {
+ const value = JSON.parse(match[1]);
+ return value && typeof value === "object"
+ ? (value as BuilderDraftPayload)
+ : null;
+ } catch {
+ // Some CLI-backed models emit literal newlines in the Markdown
+ // instructions string even when asked for compact JSON. Repair only JSON
+ // control characters that occur inside strings; object structure and all
+ // other syntax still have to pass JSON.parse.
+ try {
+ const value = JSON.parse(escapeJsonStringControlCharacters(match[1]));
+ return value && typeof value === "object"
+ ? (value as BuilderDraftPayload)
+ : null;
+ } catch {
+ return null;
+ }
+ }
+}
+
+function escapeJsonStringControlCharacters(value: string): string {
+ let result = "";
+ let inString = false;
+ let escaped = false;
+
+ for (const character of value) {
+ if (!inString) {
+ result += character;
+ if (character === '"') inString = true;
+ continue;
+ }
+ if (escaped) {
+ result += character;
+ escaped = false;
+ continue;
+ }
+ if (character === "\\") {
+ result += character;
+ escaped = true;
+ continue;
+ }
+ if (character === '"') {
+ result += character;
+ inString = false;
+ continue;
+ }
+ if (character === "\n") {
+ result += "\\n";
+ } else if (character === "\r") {
+ result += "\\r";
+ } else if (character === "\t") {
+ result += "\\t";
+ } else {
+ result += character;
+ }
+ }
+
+ return result;
+}
+
+/**
+ * Removes the structured block from a reply before a human reads it. The block
+ * is machinery — it drives the configuration form — and the form is where its
+ * effect is already visible, so the transcript keeps only the prose.
+ *
+ * Two patterns, not one. The closed form is what history holds. The unclosed
+ * one is what streaming produces: the reply arrives token by token, so for the
+ * seconds it takes to emit the JSON there is an opening tag and no closing tag,
+ * which the closed-form pattern cannot match — the raw payload used to scroll
+ * past the reader on every single turn.
+ *
+ * The leading `\s*` takes the whitespace the model left between its prose and
+ * the block, so removing it does not strand a blank line.
+ */
+export function stripBuilderDraft(content: string): string {
+ return content
+ .replace(/\s*<agent_draft>[\s\S]*?<\/agent_draft>/g, "")
+ .replace(/\s*<agent_draft>[\s\S]*$/, "")
+ .trim();
+}
+
+export function encodeBuilderInput(
+ request: string,
+ draft: AgentDraft,
+ skills: Array<{ id: string; name: string; description: string }>,
+ members: Array<{ user_id: string; name: string }>,
+ runtime: Pick<RuntimeDevice, "id" | "name" | "provider"> | null,
+ models: RuntimeModel[] | null,
+): string {
+ return (
+ BUILDER_INPUT_PREFIX +
+ JSON.stringify(
+ {
+ user_request: request,
+ current_draft: {
+ name: draft.name,
+ description: draft.description,
+ instructions: draft.instructions,
+ model: draft.model,
+ skill_ids: [...draft.skillIds],
+ permission_scope: draft.permissionScope,
+ member_ids: [...draft.memberIds],
+ },
+ selected_runtime: runtime
+ ? {
+ id: runtime.id,
+ name: runtime.name,
+ provider: runtime.provider,
+ }
+ : null,
+ available_runtime_models:
+ models === null
+ ? null
+ : models.map((model) => ({
+ id: model.id,
+ label: model.label,
+ provider: model.provider,
+ })),
+ available_workspace_skills: skills.map((skill) => ({
+ id: skill.id,
+ name: skill.name,
+ description: skill.description,
+ })),
+ available_workspace_members: members.map((member) => ({
+ id: member.user_id,
+ name: member.name,
+ })),
+ },
+ null,
+ 2,
+ )
+ );
+}
+
+export function decodeBuilderInput(content: string): string {
+ if (!content.startsWith(BUILDER_INPUT_PREFIX)) return content;
+ try {
+ const parsed = JSON.parse(content.slice(BUILDER_INPUT_PREFIX.length)) as {
+ user_request?: unknown;
+ };
+ return typeof parsed.user_request === "string"
+ ? parsed.user_request
+ : content;
+ } catch {
+ return content;
+ }
+}
+
+export interface BuilderRestore {
+ id: string;
+ content: string;
+}
+
+/**
+ * Chooses which cancelled prompt the builder composer should adopt (#5219).
+ *
+ * Two sources, never both: cancelling a task the daemon never started answers
+ * synchronously (`cancelled_chat_message.restore_to_input`), while cancelling a
+ * started-but-empty one defers the judgment and delivers the prompt later as a
+ * durable chat_draft_restore row. The durable copy is the raw chat_message
+ * content, i.e. still in the builder's encoded wire form, so it is decoded here
+ * exactly as the synchronous path decodes its own.
+ *
+ * The session id is deliberately not carried over: the builder composer keys its
+ * draft by `agent-builder:<id>`, so ChatInput's session guard would never match
+ * a raw session id — and it does not need to, since this composer only ever
+ * shows the builder session.
+ */
+export function pickBuilderRestore(
+ synchronous: BuilderRestore | null,
+ durable: { id: string; content: string } | null,
+): BuilderRestore | null {
+ if (synchronous) return synchronous;
+ if (!durable) return null;
+ return { id: durable.id, content: decodeBuilderInput(durable.content) };
+}
+
+export function mergeBuilderDraft(
+ current: AgentDraft,
+ payload: BuilderDraftPayload,
+ validSkillIds: Set<string>,
+ validMemberIds: Set<string>,
+ validModelIds: ReadonlySet<string> | null,
+): AgentDraft {
+ const scope =
+ payload.permission_scope === "workspace" ||
+ payload.permission_scope === "members" ||
+ payload.permission_scope === "private"
+ ? payload.permission_scope
+ : current.permissionScope;
+ const skillIds = Array.isArray(payload.skill_ids)
+ ? payload.skill_ids.filter(
+ (id): id is string => typeof id === "string" && validSkillIds.has(id),
+ )
+ : [...current.skillIds];
+ const memberIds = Array.isArray(payload.member_ids)
+ ? payload.member_ids.filter(
+ (id): id is string => typeof id === "string" && validMemberIds.has(id),
+ )
+ : [...current.memberIds];
+ // The current value may be a deliberate custom entry from ModelDropdown,
+ // so preserving it is always safe. Only catalog IDs may be introduced by
+ // the builder; failed discovery therefore cannot turn into fail-open input.
+ const model =
+ typeof payload.model === "string" &&
+ (payload.model === current.model ||
+ (validModelIds !== null &&
+ validModelIds.size > 0 &&
+ (payload.model === "" || validModelIds.has(payload.model))))
+ ? payload.model
+ : current.model;
+
+ return {
+ ...current,
+ name: typeof payload.name === "string" ? payload.name : current.name,
+ description:
+ typeof payload.description === "string"
+ ? payload.description
+ : current.description,
+ instructions:
+ typeof payload.instructions === "string"
+ ? payload.instructions
+ : current.instructions,
+ model,
+ // The builder can move the model, which invalidates whatever thinking /
+ // speed the user picked for the previous one. It never sets these two
+ // itself, so an unchanged model simply preserves them.
+ thinkingLevel: model === current.model ? current.thinkingLevel : "",
+ serviceTier: model === current.model ? current.serviceTier : "",
+ skillIds: new Set(skillIds),
+ permissionScope: scope,
+ memberIds: new Set(scope === "members" ? memberIds : []),
+ teamIds: current.teamIds,
+ };
+}
diff --git a/packages/core/agents/draft.test.ts b/packages/core/agents/draft.test.ts
new file mode 100644
index 0000000000..5fb0077100
--- /dev/null
+++ b/packages/core/agents/draft.test.ts
@@ -0,0 +1,267 @@
+import { describe, expect, it } from "vitest";
+import type { Agent, RuntimeDevice } from "../types";
+import {
+ applyDraftModelChange,
+ applyDraftRuntimeChange,
+ buildCreateAgentRequest,
+ buildDuplicateDraft,
+ buildInvocationTargets,
+ deriveDuplicateAccess,
+ isDraftDescriptionWithinLimit,
+ type AgentDraft,
+} from "./draft";
+
+const draft = (): AgentDraft => ({
+ name: "Old name",
+ description: "Old description",
+ instructions: "Old instructions",
+ avatarUrl: null,
+ runtimeId: "runtime-1",
+ model: "model-1",
+ thinkingLevel: "",
+ serviceTier: "",
+ skillIds: new Set(["skill-1"]),
+ permissionScope: "private",
+ memberIds: new Set(),
+ teamIds: new Set(),
+});
+
+const CODEX_RUNTIME: RuntimeDevice = {
+ id: "runtime-1",
+ workspace_id: "ws-1",
+ name: "Codex laptop",
+ provider: "codex",
+ status: "online",
+ owner_id: "user-1",
+ visibility: "private",
+} as RuntimeDevice;
+
+const OTHER_RUNTIME: RuntimeDevice = {
+ ...CODEX_RUNTIME,
+ id: "runtime-2",
+ name: "Spare laptop",
+} as RuntimeDevice;
+
+const sourceAgent = (overrides: Partial<Agent> = {}): Agent =>
+ ({
+ id: "agent-1",
+ workspace_id: "ws-1",
+ runtime_id: "runtime-1",
+ name: "Fast Codex",
+ description: "Ships quickly",
+ instructions: "Be quick",
+ avatar_url: null,
+ runtime_mode: "managed",
+ runtime_config: {},
+ custom_args: ["--verbose"],
+ visibility: "private",
+ permission_mode: "private",
+ invocation_targets: [],
+ status: "idle",
+ max_concurrent_tasks: 9,
+ model: "gpt-5.6-sol",
+ thinking_level: "high",
+ service_tier: "priority",
+ owner_id: "user-1",
+ skills: [{ id: "skill-1", name: "Review", description: "" }],
+ created_at: "2026-07-28T00:00:00Z",
+ updated_at: "2026-07-28T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+ ...overrides,
+ }) as Agent;
+
+describe("duplicate access", () => {
+ it("preserves scoped member and team grants when duplicating an agent", () => {
+ const access = deriveDuplicateAccess({
+ permission_mode: "public_to",
+ invocation_targets: [
+ { target_type: "member", target_id: "member-1" },
+ { target_type: "team", target_id: "team-1" },
+ ],
+ });
+ const duplicateDraft = {
+ ...draft(),
+ ...access,
+ };
+
+ expect(access.permissionScope).toBe("members");
+ expect(buildInvocationTargets(duplicateDraft)).toEqual([
+ { target_type: "member", target_id: "member-1" },
+ { target_type: "team", target_id: "team-1" },
+ ]);
+ });
+
+ it("keeps workspace-wide duplicate access workspace-wide", () => {
+ expect(
+ deriveDuplicateAccess({
+ permission_mode: "public_to",
+ invocation_targets: [{ target_type: "workspace", target_id: null }],
+ }).permissionScope,
+ ).toBe("workspace");
+ });
+});
+
+// MUL-5390: thinking_level / service_tier are runtime + model scoped. The create
+// flow never exposed them, so a Fast Codex agent could only be configured after
+// the fact and a Duplicate silently dropped the setting.
+describe("agent draft execution overrides", () => {
+ it("sends the selected thinking level and service tier", () => {
+ const request = buildCreateAgentRequest({
+ draft: {
+ ...draft(),
+ model: "gpt-5.6-sol",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ },
+ runtimeId: "runtime-1",
+ });
+
+ expect(request).toMatchObject({
+ runtime_id: "runtime-1",
+ model: "gpt-5.6-sol",
+ thinking_level: "high",
+ service_tier: "priority",
+ });
+ });
+
+ it("omits empty overrides instead of sending an empty string", () => {
+ const request = buildCreateAgentRequest({
+ draft: { ...draft(), model: "" },
+ runtimeId: "runtime-1",
+ });
+
+ expect(request.model).toBeUndefined();
+ expect(request.thinking_level).toBeUndefined();
+ expect(request.service_tier).toBeUndefined();
+ expect("thinking_level" in request).toBe(true);
+ expect(JSON.parse(JSON.stringify(request))).not.toHaveProperty(
+ "thinking_level",
+ );
+ });
+
+ it("carries the runtime-independent duplicate config", () => {
+ const request = buildCreateAgentRequest({
+ draft: { ...draft(), thinkingLevel: "high", serviceTier: "priority" },
+ runtimeId: "runtime-1",
+ duplicateSource: sourceAgent(),
+ });
+
+ expect(request.custom_args).toEqual(["--verbose"]);
+ expect(request.max_concurrent_tasks).toBe(9);
+ expect(request.thinking_level).toBe("high");
+ });
+
+ it.each([0, -1, 51])(
+ "omits an invalid historical duplicate concurrency of %i",
+ (maxConcurrentTasks) => {
+ const request = buildCreateAgentRequest({
+ draft: draft(),
+ runtimeId: "runtime-1",
+ duplicateSource: sourceAgent({
+ max_concurrent_tasks: maxConcurrentTasks,
+ }),
+ });
+
+ expect(request.max_concurrent_tasks).toBeUndefined();
+ expect(request).not.toHaveProperty("max_concurrent_tasks");
+ },
+ );
+
+ it("clears model, thinking level and service tier on a runtime change", () => {
+ const current = {
+ ...draft(),
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ };
+
+ expect(applyDraftRuntimeChange(current, "runtime-2")).toMatchObject({
+ runtimeId: "runtime-2",
+ model: "",
+ thinkingLevel: "",
+ serviceTier: "",
+ });
+ });
+
+ it("clears only the per-model overrides on a model change", () => {
+ const current = {
+ ...draft(),
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ };
+ const next = applyDraftModelChange(current, "gpt-5.4-mini");
+
+ expect(next).toMatchObject({
+ runtimeId: "runtime-1",
+ model: "gpt-5.4-mini",
+ thinkingLevel: "",
+ serviceTier: "",
+ });
+ // Re-selecting the same model must not wipe a choice the user just made.
+ expect(applyDraftModelChange(current, "model-1")).toBe(current);
+ });
+
+ it("copies the execution config when the duplicate stays on its runtime", () => {
+ const duplicate = buildDuplicateDraft(sourceAgent(), {
+ runtimes: [CODEX_RUNTIME],
+ currentUserId: "user-1",
+ fallbackRuntimeId: "runtime-1",
+ nameSuffix: " copy",
+ });
+
+ expect(duplicate).toMatchObject({
+ name: "Fast Codex copy",
+ runtimeId: "runtime-1",
+ model: "gpt-5.6-sol",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ });
+ expect([...duplicate.skillIds]).toEqual(["skill-1"]);
+ });
+
+ it("drops the execution config when the duplicate falls back to another runtime", () => {
+ // Source runtime is gone from the list (deleted, or private to someone
+ // else), so the draft lands on the fallback. Keeping the source model here
+ // is what persisted a cross-provider model before MUL-5390.
+ const duplicate = buildDuplicateDraft(sourceAgent(), {
+ runtimes: [OTHER_RUNTIME],
+ currentUserId: "user-1",
+ fallbackRuntimeId: "runtime-2",
+ nameSuffix: " copy",
+ });
+
+ expect(duplicate).toMatchObject({
+ runtimeId: "runtime-2",
+ model: "",
+ thinkingLevel: "",
+ serviceTier: "",
+ });
+ });
+
+ it("drops the execution config when the source runtime is private to someone else", () => {
+ const duplicate = buildDuplicateDraft(sourceAgent(), {
+ runtimes: [
+ { ...CODEX_RUNTIME, owner_id: "user-2" } as RuntimeDevice,
+ { ...OTHER_RUNTIME, owner_id: "user-1" } as RuntimeDevice,
+ ],
+ currentUserId: "user-1",
+ fallbackRuntimeId: "runtime-2",
+ nameSuffix: " copy",
+ });
+
+ expect(duplicate).toMatchObject({
+ runtimeId: "runtime-2",
+ model: "",
+ thinkingLevel: "",
+ serviceTier: "",
+ });
+ });
+
+ it("enforces the 255-rune description limit the create API applies", () => {
+ expect(isDraftDescriptionWithinLimit("a".repeat(255))).toBe(true);
+ expect(isDraftDescriptionWithinLimit("a".repeat(256))).toBe(false);
+ // Runes, not UTF-16 units: 255 CJK characters are exactly at the limit.
+ expect(isDraftDescriptionWithinLimit("汉".repeat(255))).toBe(true);
+ expect(isDraftDescriptionWithinLimit("汉".repeat(256))).toBe(false);
+ });
+});
diff --git a/packages/core/agents/draft.ts b/packages/core/agents/draft.ts
new file mode 100644
index 0000000000..12c89abb33
--- /dev/null
+++ b/packages/core/agents/draft.ts
@@ -0,0 +1,244 @@
+import { isRuntimeUsableForUser } from "../runtimes/access";
+import type {
+ Agent,
+ AgentInvocationTargetInput,
+ AgentPermissionScope,
+ CreateAgentRequest,
+ RuntimeDevice,
+} from "../types";
+import {
+ AGENT_DESCRIPTION_MAX_LENGTH,
+ AGENT_MAX_CONCURRENT_TASKS_MAX,
+ AGENT_MAX_CONCURRENT_TASKS_MIN,
+} from "./constants";
+
+// Declared with the other agent wire types so `StoredAgentDraft` can name it
+// without types/ having to import from agents/.
+export type { AgentPermissionScope };
+
+/**
+ * The in-progress configuration of an agent being created. Shared by every
+ * creation surface (manual, duplicate, AI builder) so the same field set is
+ * validated, seeded and submitted the same way regardless of entry point.
+ */
+export interface AgentDraft {
+ name: string;
+ description: string;
+ instructions: string;
+ avatarUrl: string | null;
+ runtimeId: string;
+ model: string;
+ /** Runtime-native reasoning/effort token, scoped to `model`. */
+ thinkingLevel: string;
+ /** Runtime-native execution tier (Codex Speed), scoped to `model`. */
+ serviceTier: string;
+ skillIds: Set<string>;
+ permissionScope: AgentPermissionScope;
+ memberIds: Set<string>;
+ /** Team grants are not editable in this form yet, but duplicates must preserve them. */
+ teamIds: Set<string>;
+}
+
+export const EMPTY_AGENT_DRAFT: AgentDraft = {
+ name: "",
+ description: "",
+ instructions: "",
+ avatarUrl: null,
+ runtimeId: "",
+ model: "",
+ thinkingLevel: "",
+ serviceTier: "",
+ skillIds: new Set(),
+ permissionScope: "private",
+ memberIds: new Set(),
+ teamIds: new Set(),
+};
+
+/**
+ * Draft fields whose only meaning comes from the currently selected
+ * runtime + model pair. A runtime change invalidates all three; a model
+ * change invalidates the two that hang off the exact model catalog. Keeping
+ * them together is what stops an orphan `thinking_level` / `service_tier`
+ * from being persisted for a model that never advertised it — the daemon
+ * would silently fall back at execution time and the settings page would
+ * disagree with what actually ran (MUL-5390).
+ */
+export function applyDraftRuntimeChange(
+ draft: AgentDraft,
+ runtimeId: string,
+): AgentDraft {
+ return {
+ ...draft,
+ runtimeId,
+ model: "",
+ thinkingLevel: "",
+ serviceTier: "",
+ };
+}
+
+/** Model change: drop the per-model capability overrides, keep the runtime. */
+export function applyDraftModelChange(
+ draft: AgentDraft,
+ model: string,
+): AgentDraft {
+ if (model === draft.model) return draft;
+ return { ...draft, model, thinkingLevel: "", serviceTier: "" };
+}
+
+/**
+ * Mirrors the server's `utf8.RuneCountInString` check (agent.go:1013). The
+ * textarea's `maxLength` covers typing and pasting, but a duplicated agent or
+ * an AI-builder draft can seed a longer value programmatically — without this
+ * the create button would submit into a guaranteed 400.
+ */
+export function isDraftDescriptionWithinLimit(description: string): boolean {
+ return [...description].length <= AGENT_DESCRIPTION_MAX_LENGTH;
+}
+
+export function buildInvocationTargets(
+ draft: AgentDraft,
+): AgentInvocationTargetInput[] {
+ if (draft.permissionScope === "private") return [];
+ if (draft.permissionScope === "workspace") {
+ return [{ target_type: "workspace" }];
+ }
+ return [
+ ...[...draft.memberIds].map((targetId) => ({
+ target_type: "member" as const,
+ target_id: targetId,
+ })),
+ ...[...draft.teamIds].map((targetId) => ({
+ target_type: "team" as const,
+ target_id: targetId,
+ })),
+ ];
+}
+
+export function deriveDuplicateAccess(
+ agent: Pick<Agent, "permission_mode" | "invocation_targets">,
+): Pick<AgentDraft, "permissionScope" | "memberIds" | "teamIds"> {
+ if (agent.permission_mode !== "public_to") {
+ return {
+ permissionScope: "private",
+ memberIds: new Set(),
+ teamIds: new Set(),
+ };
+ }
+
+ const targets = agent.invocation_targets ?? [];
+ if (targets.some((target) => target.target_type === "workspace")) {
+ return {
+ permissionScope: "workspace",
+ memberIds: new Set(),
+ teamIds: new Set(),
+ };
+ }
+
+ const memberIds = targets
+ .filter((target) => target.target_type === "member" && target.target_id)
+ .map((target) => target.target_id as string);
+ const teamIds = targets
+ .filter((target) => target.target_type === "team" && target.target_id)
+ .map((target) => target.target_id as string);
+ if (memberIds.length === 0 && teamIds.length === 0) {
+ return {
+ permissionScope: "private",
+ memberIds: new Set(),
+ teamIds: new Set(),
+ };
+ }
+ return {
+ permissionScope: "members",
+ memberIds: new Set(memberIds),
+ teamIds: new Set(teamIds),
+ };
+}
+
+/**
+ * Seeds the create draft from the agent being duplicated.
+ *
+ * `model` / `thinkingLevel` / `serviceTier` only mean something on the runtime
+ * they were chosen for, so they ride along only when the copy stays on that
+ * exact runtime. When the source runtime is gone, private to somebody else or
+ * offline, the draft falls back to another runtime and the three are cleared
+ * for the user to pick again — the same rule `multica agent copy` already
+ * enforces server-side (cmd_agent_copy.go). Before MUL-5390 the fallback kept
+ * the source `model` and silently persisted a cross-provider value.
+ */
+export function buildDuplicateDraft(
+ source: Agent,
+ options: {
+ runtimes: RuntimeDevice[];
+ currentUserId: string | null;
+ fallbackRuntimeId: string;
+ nameSuffix: string;
+ },
+): AgentDraft {
+ const keepsRuntime =
+ !!source.runtime_id &&
+ options.runtimes.some(
+ (runtime) =>
+ runtime.id === source.runtime_id &&
+ isRuntimeUsableForUser(runtime, options.currentUserId),
+ );
+ return {
+ ...EMPTY_AGENT_DRAFT,
+ name: `${source.name}${options.nameSuffix}`,
+ description: source.description ?? "",
+ instructions: source.instructions ?? "",
+ avatarUrl: source.avatar_url ?? null,
+ runtimeId: keepsRuntime
+ ? (source.runtime_id as string)
+ : options.fallbackRuntimeId,
+ model: keepsRuntime ? source.model ?? "" : "",
+ thinkingLevel: keepsRuntime ? source.thinking_level ?? "" : "",
+ serviceTier: keepsRuntime ? source.service_tier ?? "" : "",
+ skillIds: new Set(source.skills.map((skill) => skill.id)),
+ ...deriveDuplicateAccess(source),
+ };
+}
+
+/**
+ * Assembles the `POST /api/agents` body. Empty execution overrides are omitted
+ * rather than sent as `""` so the runtime resolves its own default, and the
+ * duplicate-only fields are the runtime-independent ones (`custom_args`,
+ * concurrency) — mirroring `multica agent copy`.
+ */
+export function buildCreateAgentRequest(options: {
+ draft: AgentDraft;
+ runtimeId: string;
+ /** Template attribution for the `agent_created` event, not a template create. */
+ template?: string;
+ duplicateSource?: Agent | null;
+}): CreateAgentRequest {
+ const { draft, runtimeId, template, duplicateSource } = options;
+ const request: CreateAgentRequest = {
+ name: draft.name.trim(),
+ description: draft.description.trim(),
+ instructions: draft.instructions.trim() || undefined,
+ avatar_url: draft.avatarUrl ?? undefined,
+ runtime_id: runtimeId,
+ model: draft.model.trim() || undefined,
+ thinking_level: draft.thinkingLevel.trim() || undefined,
+ service_tier: draft.serviceTier.trim() || undefined,
+ permission_mode:
+ draft.permissionScope === "private" ? "private" : "public_to",
+ invocation_targets: buildInvocationTargets(draft),
+ skill_ids: [...draft.skillIds],
+ template,
+ };
+ if (duplicateSource) {
+ if (duplicateSource.custom_args.length > 0) {
+ request.custom_args = duplicateSource.custom_args;
+ }
+ const sourceConcurrency = duplicateSource.max_concurrent_tasks;
+ if (
+ Number.isInteger(sourceConcurrency) &&
+ sourceConcurrency >= AGENT_MAX_CONCURRENT_TASKS_MIN &&
+ sourceConcurrency <= AGENT_MAX_CONCURRENT_TASKS_MAX
+ ) {
+ request.max_concurrent_tasks = sourceConcurrency;
+ }
+ }
+ return request;
+}
diff --git a/packages/core/agents/index.ts b/packages/core/agents/index.ts
index a0e8180a4a..e22fa7070b 100644
--- a/packages/core/agents/index.ts
+++ b/packages/core/agents/index.ts
@@ -1,4 +1,8 @@
export * from "./types";
+export * from "./draft";
+export * from "./stored-draft";
+export * from "./manual-draft-store";
+export * from "./builder-protocol";
export * from "./derive-presence";
export * from "./failure-reason";
export * from "./effective-access";
diff --git a/packages/core/agents/manual-draft-store.test.ts b/packages/core/agents/manual-draft-store.test.ts
new file mode 100644
index 0000000000..33367be449
--- /dev/null
+++ b/packages/core/agents/manual-draft-store.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it } from "vitest";
+import { EMPTY_AGENT_DRAFT } from "./draft";
+import {
+ MANUAL_DRAFT_BLANK_OWNER,
+ manualDraftEntryHasContent,
+ manualDraftOwner,
+ setManualDraftEntry,
+ type ManualAgentDrafts,
+ type ManualDraftEntry,
+} from "./manual-draft-store";
+import { toStoredAgentDraft } from "./stored-draft";
+
+const entry = (
+ overrides: Partial<typeof EMPTY_AGENT_DRAFT> = {},
+): ManualDraftEntry => ({
+ runtimeId: "runtime-1",
+ draft: toStoredAgentDraft({ ...EMPTY_AGENT_DRAFT, ...overrides }, null),
+});
+
+describe("manual agent drafts", () => {
+ // A blank agent and a copy of agent X are different pieces of work, and a
+ // copy of X is not a copy of Y.
+ it("scopes a draft to what is being created", () => {
+ expect(manualDraftOwner(null)).toBe(MANUAL_DRAFT_BLANK_OWNER);
+ expect(manualDraftOwner("agent-1")).toBe("duplicate:agent-1");
+ expect(manualDraftOwner("agent-1")).not.toBe(manualDraftOwner("agent-2"));
+ });
+
+ // The regression this keying exists for: with one shared slot, opening a
+ // second flow overwrote the first before the user typed a character.
+ it("leaves other owners' drafts alone", () => {
+ const drafts: ManualAgentDrafts = setManualDraftEntry(
+ { byOwner: {} },
+ "duplicate:agent-A",
+ entry({ name: "Half-finished copy of A" }),
+ );
+
+ const afterOpeningBlank = setManualDraftEntry(
+ drafts,
+ MANUAL_DRAFT_BLANK_OWNER,
+ entry({ name: "Something else" }),
+ );
+ const afterOpeningB = setManualDraftEntry(
+ afterOpeningBlank,
+ "duplicate:agent-B",
+ entry({ name: "Copy of B" }),
+ );
+
+ expect(afterOpeningB.byOwner["duplicate:agent-A"]?.draft.name).toBe(
+ "Half-finished copy of A",
+ );
+ expect(Object.keys(afterOpeningB.byOwner).sort()).toEqual([
+ MANUAL_DRAFT_BLANK_OWNER,
+ "duplicate:agent-A",
+ "duplicate:agent-B",
+ ]);
+ });
+
+ // The runtime is seeded automatically on every visit. Counting it as content
+ // would store a slot for a form nobody touched — and would grow a dead key
+ // for every agent ever opened for duplication.
+ it("stores nothing for a form the user has not touched", () => {
+ const drafts = setManualDraftEntry({ byOwner: {} }, "blank", entry());
+ expect(drafts.byOwner).toEqual({});
+ expect(manualDraftEntryHasContent(entry())).toBe(false);
+ });
+
+ // Emptying the form removes its slot rather than parking a blank one.
+ it("drops a slot once its content is gone", () => {
+ const withContent = setManualDraftEntry(
+ { byOwner: {} },
+ "blank",
+ entry({ name: "Typed" }),
+ );
+ expect(withContent.byOwner.blank).toBeDefined();
+
+ const emptied = setManualDraftEntry({ ...withContent }, "blank", entry());
+ expect(emptied.byOwner.blank).toBeUndefined();
+
+ const discarded = setManualDraftEntry({ ...withContent }, "blank", null);
+ expect(discarded.byOwner.blank).toBeUndefined();
+ });
+
+ // Every field the form can change, one at a time. An earlier version listed
+ // six of them by hand and silently dropped the rest: picking a model before
+ // typing a name, or setting access first, deleted the slot on the next save.
+ it.each([
+ ["name", { name: "Release" }],
+ ["description", { description: "Ships carefully" }],
+ ["instructions", { instructions: "Be careful" }],
+ ["avatar", { avatarUrl: "🚀" }],
+ ["model", { model: "gpt-5.6-sol" }],
+ ["thinking level", { thinkingLevel: "high" }],
+ ["service tier", { serviceTier: "priority" }],
+ ["access scope", { permissionScope: "workspace" as const }],
+ ["skills", { skillIds: new Set(["skill-1"]) }],
+ ["members", { memberIds: new Set(["member-1"]) }],
+ ["teams", { teamIds: new Set(["team-1"]) }],
+ ])("keeps a draft whose only edit is the %s", (_label, overrides) => {
+ expect(manualDraftEntryHasContent(entry(overrides))).toBe(true);
+ expect(
+ setManualDraftEntry({ byOwner: {} }, "blank", entry(overrides)).byOwner
+ .blank,
+ ).toBeDefined();
+ });
+
+ // The runtime is the one field that must not count: the form seeds it on
+ // every visit, so counting it would store a draft for a form nobody touched.
+ it("does not count the auto-seeded runtime", () => {
+ expect(
+ manualDraftEntryHasContent({ ...entry(), runtimeId: "runtime-9" }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/core/agents/manual-draft-store.ts b/packages/core/agents/manual-draft-store.ts
new file mode 100644
index 0000000000..be85ce9065
--- /dev/null
+++ b/packages/core/agents/manual-draft-store.ts
@@ -0,0 +1,91 @@
+"use client";
+
+import { createDraftStore } from "../drafts/create-draft-store";
+import type { StoredAgentDraft } from "../types";
+import { EMPTY_AGENT_DRAFT } from "./draft";
+import { storedAgentDraftsEqual, toStoredAgentDraft } from "./stored-draft";
+
+/**
+ * The manual creation form, kept across navigation.
+ *
+ * The AI route stores its configuration server-side, keyed by the conversation
+ * it belongs to. The manual route has no conversation and nothing on the server
+ * to hang a draft off, so it persists locally — which is enough for what it has
+ * to survive: a tab switch, a route change, a reload (#6287).
+ *
+ * Drafts are keyed by what is being created, not stored one at a time. A blank
+ * agent and a copy of agent X are different pieces of work, and a copy of X is
+ * not a copy of Y; a single slot destroys one the moment the user opens
+ * another, before they have typed anything. Same shape the chat composer uses
+ * for its per-session drafts.
+ */
+export interface ManualDraftEntry {
+ /** Runtime included here, unlike the AI route's draft: there is no carrier
+ * agent to be authoritative about it. */
+ runtimeId: string;
+ draft: StoredAgentDraft;
+}
+
+export interface ManualAgentDrafts {
+ /** Keyed by {@link manualDraftOwner}. */
+ byOwner: Record<string, ManualDraftEntry>;
+}
+
+export const EMPTY_MANUAL_DRAFT_ENTRY: ManualDraftEntry = {
+ runtimeId: "",
+ draft: toStoredAgentDraft(EMPTY_AGENT_DRAFT, null),
+};
+
+export const MANUAL_DRAFT_BLANK_OWNER = "blank";
+
+export function manualDraftOwner(duplicateId: string | null): string {
+ return duplicateId ? `duplicate:${duplicateId}` : MANUAL_DRAFT_BLANK_OWNER;
+}
+
+/**
+ * Whether an entry is worth keeping: anything at all differs from a fresh form.
+ *
+ * Compared whole rather than field by field on purpose. An enumerated predicate
+ * silently stops covering each field added to the draft after it was written —
+ * and the failure is invisible, because the field saves fine as long as some
+ * *other* field is also set. The first version of this listed six fields and
+ * dropped a model-only or access-only edit on the floor.
+ *
+ * The runtime is the one thing that must not count, and it is already outside
+ * this comparison: the form seeds it on every visit, so counting it would store
+ * a draft for a form nobody touched and grow a dead slot for every agent ever
+ * opened for duplication. It lives on the entry, not in the draft, for exactly
+ * that reason.
+ */
+export function manualDraftEntryHasContent(entry: ManualDraftEntry): boolean {
+ return !storedAgentDraftsEqual(entry.draft, EMPTY_MANUAL_DRAFT_ENTRY.draft);
+}
+
+/**
+ * Writes one owner's entry without touching the others, and drops it entirely
+ * when it holds nothing. Emptying the form therefore removes its slot rather
+ * than parking a blank one, which is also what keeps the map from growing a
+ * dead key per agent ever opened for duplication.
+ */
+export function setManualDraftEntry(
+ drafts: ManualAgentDrafts,
+ owner: string,
+ entry: ManualDraftEntry | null,
+): ManualAgentDrafts {
+ const byOwner = { ...drafts.byOwner };
+ if (entry && manualDraftEntryHasContent(entry)) {
+ byOwner[owner] = entry;
+ } else {
+ delete byOwner[owner];
+ }
+ return { byOwner };
+}
+
+const EMPTY_MANUAL_AGENT_DRAFTS: ManualAgentDrafts = { byOwner: {} };
+
+export const useManualAgentDraftStore = createDraftStore<ManualAgentDrafts>({
+ storageKey: "multica:agents:manual-draft",
+ emptyData: EMPTY_MANUAL_AGENT_DRAFTS,
+ hasMeaningful: (drafts) =>
+ Object.values(drafts.byOwner).some(manualDraftEntryHasContent),
+});
diff --git a/packages/core/agents/queries.ts b/packages/core/agents/queries.ts
index e17eae1a74..db80d3761d 100644
--- a/packages/core/agents/queries.ts
+++ b/packages/core/agents/queries.ts
@@ -163,3 +163,23 @@ export function agentTemplateDetailOptions(slug: string) {
gcTime: 30 * 60 * 1000,
});
}
+
+/** Unfinished agent-creation conversations, scoped to the caller. */
+export const agentBuilderSessionKeys = {
+ all: (wsId: string) => ["workspace", wsId, "agent-builder-sessions"] as const,
+ list: (wsId: string) => [...agentBuilderSessionKeys.all(wsId), "list"] as const,
+};
+
+export function agentBuilderSessionListOptions(wsId: string) {
+ return queryOptions({
+ queryKey: agentBuilderSessionKeys.list(wsId),
+ queryFn: () => api.listAgentBuilderSessions(),
+ enabled: wsId.length > 0,
+ // Overrides the client-wide `staleTime: Infinity`. This list changes
+ // through work done on another screen — starting a conversation, sending a
+ // turn, an agent finally being created — and the surfaces that render it
+ // mount on demand. Cached forever it would show the state of the first
+ // visit: a user who just held a conversation comes back to "no drafts".
+ staleTime: 0,
+ });
+}
diff --git a/packages/core/agents/stored-draft.test.ts b/packages/core/agents/stored-draft.test.ts
new file mode 100644
index 0000000000..6d0f6131f9
--- /dev/null
+++ b/packages/core/agents/stored-draft.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from "vitest";
+import type { AgentDraft } from "./draft";
+import {
+ fromStoredAgentDraft,
+ storedAgentDraftsEqual,
+ toStoredAgentDraft,
+} from "./stored-draft";
+
+const draft = (): AgentDraft => ({
+ name: "Release manager",
+ description: "Ships carefully",
+ instructions: "# Role\nShip.",
+ avatarUrl: "🚀",
+ runtimeId: "runtime-1",
+ model: "gpt-5.6-sol",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ skillIds: new Set(["skill-1", "skill-2"]),
+ permissionScope: "members",
+ memberIds: new Set(["member-1"]),
+ teamIds: new Set(["team-1"]),
+});
+
+describe("stored agent draft", () => {
+ it("round-trips every editable field", () => {
+ const original = draft();
+ const restored = fromStoredAgentDraft(
+ toStoredAgentDraft(original, "msg-1"),
+ original.runtimeId,
+ );
+ expect(restored).toEqual(original);
+ });
+
+ // The runtime a conversation executes on is owned by its carrier agent. A
+ // copy inside the draft could only go stale and put the picker on a runtime
+ // that runs nothing (MUL-5163), so the restore takes it from the caller.
+ it("takes the runtime from the caller, not the stored copy", () => {
+ const stored = toStoredAgentDraft(draft(), null);
+ expect(stored).not.toHaveProperty("runtimeId");
+ expect(fromStoredAgentDraft(stored, "runtime-2").runtimeId).toBe(
+ "runtime-2",
+ );
+ });
+
+ // The marker is what stops a restore from re-applying the last reply over
+ // edits made after it, so it has to survive the round trip.
+ it("carries the applied message marker", () => {
+ expect(toStoredAgentDraft(draft(), "msg-9").applied_message_id).toBe(
+ "msg-9",
+ );
+ expect(toStoredAgentDraft(draft(), null).applied_message_id).toBeNull();
+ });
+
+ // Autosave compares on the stored form: a Set rebuilt with the same members
+ // is a new reference every render and would otherwise write on every keystroke
+ // elsewhere in the form.
+ it("treats rebuilt sets with the same members as unchanged", () => {
+ expect(
+ storedAgentDraftsEqual(
+ toStoredAgentDraft(draft(), "msg-1"),
+ toStoredAgentDraft(draft(), "msg-1"),
+ ),
+ ).toBe(true);
+ expect(
+ storedAgentDraftsEqual(
+ toStoredAgentDraft(draft(), "msg-1"),
+ toStoredAgentDraft({ ...draft(), name: "Other" }, "msg-1"),
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/packages/core/agents/stored-draft.ts b/packages/core/agents/stored-draft.ts
new file mode 100644
index 0000000000..e5a26c5b23
--- /dev/null
+++ b/packages/core/agents/stored-draft.ts
@@ -0,0 +1,61 @@
+import type { StoredAgentDraft } from "../types";
+import { EMPTY_AGENT_DRAFT, type AgentDraft } from "./draft";
+
+export type { StoredAgentDraft };
+
+export function toStoredAgentDraft(
+ draft: AgentDraft,
+ appliedMessageId: string | null,
+): StoredAgentDraft {
+ return {
+ name: draft.name,
+ description: draft.description,
+ instructions: draft.instructions,
+ avatar_url: draft.avatarUrl,
+ model: draft.model,
+ thinking_level: draft.thinkingLevel,
+ service_tier: draft.serviceTier,
+ skill_ids: [...draft.skillIds],
+ permission_scope: draft.permissionScope,
+ member_ids: [...draft.memberIds],
+ team_ids: [...draft.teamIds],
+ applied_message_id: appliedMessageId,
+ };
+}
+
+/**
+ * Rebuilds the editable draft. `runtimeId` comes from the caller because the
+ * server owns it — see the note on {@link StoredAgentDraft}.
+ */
+export function fromStoredAgentDraft(
+ stored: StoredAgentDraft,
+ runtimeId: string,
+): AgentDraft {
+ return {
+ ...EMPTY_AGENT_DRAFT,
+ name: stored.name,
+ description: stored.description,
+ instructions: stored.instructions,
+ avatarUrl: stored.avatar_url,
+ runtimeId,
+ model: stored.model,
+ thinkingLevel: stored.thinking_level,
+ serviceTier: stored.service_tier,
+ skillIds: new Set(stored.skill_ids),
+ permissionScope: stored.permission_scope,
+ memberIds: new Set(stored.member_ids),
+ teamIds: new Set(stored.team_ids),
+ };
+}
+
+/**
+ * Whether two drafts would serialize identically — the autosave's "has anything
+ * actually changed" test. Compared on the stored form so a `Set` rebuilt with
+ * the same members does not read as an edit and cause a pointless write.
+ */
+export function storedAgentDraftsEqual(
+ a: StoredAgentDraft,
+ b: StoredAgentDraft,
+): boolean {
+ return JSON.stringify(a) === JSON.stringify(b);
+}
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 43bb7eedea..44c418ecb2 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -27,6 +27,8 @@ import type {
CreateAgentFromTemplateResponse,
AgentBuilderRuntimeSwitch,
AgentBuilderSession,
+ AgentBuilderSessionSummary,
+ StoredAgentDraft,
UpdateAgentRequest,
AgentEnvResponse,
UpdateAgentEnvRequest,
@@ -198,6 +200,8 @@ import {
CreateAgentFromTemplateResponseSchema,
AgentBuilderRuntimeSwitchSchema,
AgentBuilderSessionSchema,
+ AgentBuilderSessionListSchema,
+ EMPTY_AGENT_BUILDER_SESSION_LIST,
agentBuilderRuntimeSwitchFallback,
DashboardAgentRunTimeListSchema,
DashboardRunTimeDailyListSchema,
@@ -1143,6 +1147,46 @@ export class ApiClient {
);
}
+ /**
+ * The caller's unfinished agent-creation conversations.
+ *
+ * Builder sessions are hidden from every chat list (their carrier agent is
+ * `kind = 'system'`), so this is the only route back to one. A 404 means the
+ * backend predates the endpoint: degrade to "no drafts" instead of erroring
+ * the Agents page, exactly as listChatDraftRestores does.
+ */
+ async listAgentBuilderSessions(): Promise<AgentBuilderSessionSummary[]> {
+ let raw: unknown;
+ try {
+ raw = await this.fetch<unknown>("/api/agent-builder/sessions");
+ } catch (err) {
+ if (err instanceof ApiError && err.status === 404) return [];
+ throw err;
+ }
+ return parseWithFallback(
+ raw,
+ AgentBuilderSessionListSchema,
+ EMPTY_AGENT_BUILDER_SESSION_LIST,
+ { endpoint: "GET /api/agent-builder/sessions" },
+ ).sessions;
+ }
+
+ /**
+ * Stores the configuration a creation conversation has arrived at, including
+ * edits the user typed but has not sent. Whole-object last-write-wins: one
+ * conversation has one editor, so a field-level merge could only reconstruct
+ * a state nobody saw. Read back through `listAgentBuilderSessions`.
+ */
+ async saveAgentBuilderDraft(
+ sessionId: string,
+ draft: StoredAgentDraft,
+ ): Promise<void> {
+ await this.fetch(`/api/agent-builder/sessions/${sessionId}/draft`, {
+ method: "PUT",
+ body: JSON.stringify({ draft }),
+ });
+ }
+
/** 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.
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 59c8ea122a..f475aafe90 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -493,6 +493,35 @@ describe("ApiClient schema fallback", () => {
});
});
+ describe("listAgentBuilderSessions", () => {
+ it("falls back to no drafts when the response is malformed", async () => {
+ stubFetchJson({ unexpected: "shape" });
+ const client = new ApiClient("https://api.example.test");
+ expect(await client.listAgentBuilderSessions()).toEqual([]);
+ });
+
+ // Losing the whole row would lose the conversation. A draft missing its
+ // runtime degrades to "let the user pick one" instead.
+ it("keeps a draft whose runtime the server omitted", async () => {
+ stubFetchJson({
+ sessions: [{ session_id: "s-1", title: "Create an agent" }],
+ });
+ const client = new ApiClient("https://api.example.test");
+ const sessions = await client.listAgentBuilderSessions();
+ expect(sessions).toHaveLength(1);
+ expect(sessions[0]?.session_id).toBe("s-1");
+ expect(sessions[0]?.runtime_id).toBe("");
+ });
+
+ // An installed desktop build can outrun a self-hosted backend. Without this
+ // the Agents page would error instead of simply offering no drafts.
+ it("treats a 404 from an older backend as no drafts", async () => {
+ stubFetchJson({ error: "not found" }, 404);
+ const client = new ApiClient("https://api.example.test");
+ expect(await client.listAgentBuilderSessions()).toEqual([]);
+ });
+ });
+
describe("createAgentFromTemplate", () => {
it("falls back to an empty agent when the response is malformed", async () => {
// The agent was created server-side even though the client can't
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 61d344bbdf..9231d4396a 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -5,6 +5,7 @@ import type {
AgentTemplateSummary,
AgentBuilderRuntimeSwitch,
AgentBuilderSession,
+ AgentBuilderSessionSummary,
Attachment,
AutopilotRun,
BillingBalance,
@@ -1380,6 +1381,56 @@ export const EMPTY_AGENT_BUILDER_SESSION: AgentBuilderSession = {
runtime_id: "",
};
+/**
+ * The stored configuration of a creation conversation. Every field falls back
+ * to empty on its own: a draft written by a newer build (or truncated in
+ * transit) must still restore the fields it does understand rather than
+ * discarding the user's work wholesale.
+ */
+export const StoredAgentDraftSchema = z.object({
+ name: z.string().catch(""),
+ description: z.string().catch(""),
+ instructions: z.string().catch(""),
+ avatar_url: z.string().nullable().catch(null),
+ model: z.string().catch(""),
+ thinking_level: z.string().catch(""),
+ service_tier: z.string().catch(""),
+ skill_ids: z.array(z.string()).catch([]),
+ permission_scope: z
+ .enum(["private", "workspace", "members"])
+ .catch("private"),
+ member_ids: z.array(z.string()).catch([]),
+ team_ids: z.array(z.string()).catch([]),
+ applied_message_id: z.string().nullable().catch(null),
+}).loose();
+
+/**
+ * One unfinished creation draft. Every field except the id has a safe empty
+ * default: an older server that omits `runtime_id` must degrade to "let the
+ * user pick" rather than dropping the whole row and losing the conversation.
+ */
+export const AgentBuilderSessionSummarySchema = z.object({
+ session_id: z.string(),
+ title: z.string().catch(""),
+ runtime_id: z.string().catch(""),
+ created_at: z.string().catch(""),
+ updated_at: z.string().catch(""),
+ last_message_content: z.string().catch(""),
+ last_message_role: z.string().catch(""),
+ last_message_at: z.string().catch(""),
+ // Absent for a conversation the user has never hand-edited; the client then
+ // replays the last <agent_draft> block instead of restoring a stored copy.
+ draft: StoredAgentDraftSchema.nullish().catch(null),
+}).loose();
+
+export const AgentBuilderSessionListSchema = z.object({
+ sessions: z.array(AgentBuilderSessionSummarySchema).catch([]),
+}).loose();
+
+export const EMPTY_AGENT_BUILDER_SESSION_LIST: {
+ sessions: AgentBuilderSessionSummary[];
+} = { sessions: [] };
+
export const AgentBuilderRuntimeSwitchSchema = z.object({
runtime_id: z.string(),
}).loose();
diff --git a/packages/core/diagnostics/diagnostic-context.ts b/packages/core/diagnostics/diagnostic-context.ts
index 42fb016513..0711c892c1 100644
--- a/packages/core/diagnostics/diagnostic-context.ts
+++ b/packages/core/diagnostics/diagnostic-context.ts
@@ -61,6 +61,8 @@ const WORKSPACE_ROUTES: readonly RoutePattern[] = [
["autopilots", ":id"],
["agents"],
["agents", "new"],
+ ["agents", "new", "manual"],
+ ["agents", "new", "ai"],
["agents", ":id"],
["members", ":id"],
["squads"],
diff --git a/packages/core/drafts/register-all-drafts.ts b/packages/core/drafts/register-all-drafts.ts
index 6762d731a7..41a0f4be33 100644
--- a/packages/core/drafts/register-all-drafts.ts
+++ b/packages/core/drafts/register-all-drafts.ts
@@ -19,3 +19,4 @@ import "../issues/stores/quick-create-store";
import "../issues/stores/comment-draft-store";
import "../projects/draft-store";
import "../feedback/draft-store";
+import "../agents/manual-draft-store";
diff --git a/packages/core/paths/consistency.test.ts b/packages/core/paths/consistency.test.ts
index d3a8fe282f..6723b2e726 100644
--- a/packages/core/paths/consistency.test.ts
+++ b/packages/core/paths/consistency.test.ts
@@ -23,6 +23,8 @@ describe("paths.workspace() shape", () => {
"autopilots",
"agents",
"newAgent",
+ "newAgentManual",
+ "newAgentAi",
"chat",
"squads",
"inbox",
@@ -46,6 +48,8 @@ describe("paths.workspace() shape", () => {
["autopilots", "autopilots"],
["agents", "agents"],
["newAgent", "agents/new"],
+ ["newAgentManual", "agents/new/manual"],
+ ["newAgentAi", "agents/new/ai"],
["chat", "chat"],
["squads", "squads"],
["inbox", "inbox"],
diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.ts
index 1c141daf06..3bdec60d11 100644
--- a/packages/core/paths/paths.ts
+++ b/packages/core/paths/paths.ts
@@ -27,6 +27,10 @@ function workspaceScoped(slug: string) {
autopilotDetail: (id: string) => `${ws}/autopilots/${encode(id)}`,
agents: () => `${ws}/agents`,
newAgent: () => `${ws}/agents/new`,
+ // The two creation methods behind the chooser. Each is a real route so a
+ // half-filled form survives a refresh and can be linked to directly.
+ newAgentManual: () => `${ws}/agents/new/manual`,
+ newAgentAi: () => `${ws}/agents/new/ai`,
agentDetail: (id: string) => `${ws}/agents/${encode(id)}`,
memberDetail: (id: string) => `${ws}/members/${encode(id)}`,
squads: () => `${ws}/squads`,
diff --git a/packages/core/runtimes/access.ts b/packages/core/runtimes/access.ts
new file mode 100644
index 0000000000..f8fdd7cdbe
--- /dev/null
+++ b/packages/core/runtimes/access.ts
@@ -0,0 +1,18 @@
+import type { RuntimeDevice } from "../types";
+
+/**
+ * Whether this member may run an agent on `runtime`.
+ *
+ * A private runtime is usable only by its owner; a public one by anyone in the
+ * workspace. An unknown viewer (no session yet) is treated as allowed so a
+ * still-loading auth state never hides a runtime the user does own — every
+ * write path re-checks server-side, where admin overrides also apply.
+ */
+export function isRuntimeUsableForUser(
+ runtime: RuntimeDevice,
+ currentUserId: string | null,
+): boolean {
+ if (!currentUserId) return true;
+ if (runtime.owner_id === currentUserId) return true;
+ return runtime.visibility === "public";
+}
diff --git a/packages/core/runtimes/index.ts b/packages/core/runtimes/index.ts
index 09f8a0d47f..69661e26b4 100644
--- a/packages/core/runtimes/index.ts
+++ b/packages/core/runtimes/index.ts
@@ -1,3 +1,4 @@
+export * from "./access";
export * from "./queries";
export * from "./profiles";
export * from "./mutations";
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 115acceb49..50b6379c1f 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -562,6 +562,54 @@ export interface AgentBuilderSession {
runtime_id: string;
}
+/** Who may invoke the agent being created, as the creation form models it. */
+export type AgentPermissionScope = "private" | "workspace" | "members";
+
+/**
+ * The wire form of an in-progress agent configuration.
+ *
+ * Differs from the editable draft in two deliberate ways: `Set` becomes an
+ * array (JSON has no sets), and there is no runtime — which runtime a
+ * conversation executes on is owned by its carrier agent server-side, and a
+ * copy here could only go stale. `applied_message_id` travels along because it
+ * is what stops a restore from re-applying the last reply's `<agent_draft>`
+ * over edits the user made after it.
+ */
+export interface StoredAgentDraft {
+ name: string;
+ description: string;
+ instructions: string;
+ avatar_url: string | null;
+ model: string;
+ thinking_level: string;
+ service_tier: string;
+ skill_ids: string[];
+ permission_scope: AgentPermissionScope;
+ member_ids: string[];
+ team_ids: string[];
+ applied_message_id: string | null;
+}
+
+/** One unfinished agent-creation conversation, as listed by the studio. */
+export interface AgentBuilderSessionSummary {
+ session_id: string;
+ title: string;
+ /** The carrier's runtime — where this conversation actually executes. The
+ * picker seeds from it so it can never disagree with what answers the next
+ * message (MUL-5163). */
+ runtime_id: string;
+ created_at: string;
+ updated_at: string;
+ /** Still in the builder wire format; decode with the builder protocol helpers
+ * before showing it to a human. */
+ last_message_content: string;
+ last_message_role: string;
+ last_message_at: string;
+ /** The stored configuration, or null when the conversation has never been
+ * hand-edited — the client then replays the last `<agent_draft>` block. */
+ draft?: StoredAgentDraft | null;
+}
+
/** 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. */
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 5a8940f4a6..241367788e 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -27,6 +27,9 @@ export type {
CreateAgentRequest,
AgentBuilderRuntimeSwitch,
AgentBuilderSession,
+ AgentBuilderSessionSummary,
+ AgentPermissionScope,
+ StoredAgentDraft,
AgentTemplate,
AgentTemplateSummary,
AgentTemplateSkillRef,
diff --git a/packages/ui/components/ui/resizable.tsx b/packages/ui/components/ui/resizable.tsx
index 305e07e6be..f57365c1f2 100644
--- a/packages/ui/components/ui/resizable.tsx
+++ b/packages/ui/components/ui/resizable.tsx
@@ -11,8 +11,22 @@ function ResizablePanelGroup({
return (
<ResizablePrimitive.Group
data-slot="resizable-panel-group"
+ // The library otherwise injects `*, *:hover { cursor: … !important }`
+ // while dragging, and narrows it to a one-way arrow the moment a panel
+ // hits a bound — so the cursor flips between two icons mid-drag. It is
+ // truthful, but it reads as a glitch. The handle carries `cursor-col-resize`
+ // instead, which stays put.
+ disableCursor
className={cn(
"flex h-full w-full aria-[orientation=vertical]:flex-col",
+ // A drag captures the pointer, which then travels across the panels —
+ // away from the handle that carries the cursor. `:has` puts the same
+ // cursor on the whole group for as long as a separator is active, which
+ // is what the library's global rule was doing before `disableCursor`
+ // turned it off. Without this the cursor reverts to a text caret the
+ // moment the pointer leaves the 8px handle.
+ "[&:has([data-separator=active])_*]:cursor-col-resize [&:has([data-separator=active])]:cursor-col-resize",
+ "aria-[orientation=vertical]:[&:has([data-separator=active])_*]:cursor-row-resize aria-[orientation=vertical]:[&:has([data-separator=active])]:cursor-row-resize",
className
)}
{...props}
@@ -35,6 +49,9 @@ function ResizableHandle({
<ResizablePrimitive.Separator
data-slot="resizable-handle"
className={cn(
+ // The only cursor source: the group opts out of the library's own
+ // (see ResizablePanelGroup). One icon for hover and for the whole drag.
+ "cursor-col-resize aria-[orientation=horizontal]:cursor-row-resize",
"relative flex w-0 items-center justify-center before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors hover:before:bg-foreground/15 data-[separator=active]:before:bg-foreground/15 after:absolute after:inset-y-0 after:left-1/2 after:w-2 after:-translate-x-1/2 focus-visible:outline-hidden aria-[orientation=horizontal]:h-0 aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:before:inset-x-0 aria-[orientation=horizontal]:before:inset-y-auto aria-[orientation=horizontal]:before:h-px aria-[orientation=horizontal]:before:w-full aria-[orientation=horizontal]:before:translate-x-0 aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:h-2 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2",
className
)}
diff --git a/packages/views/agents/components/agent-creation-studio.test.ts b/packages/views/agents/components/agent-creation-studio.test.ts
deleted file mode 100644
index f30566b78d..0000000000
--- a/packages/views/agents/components/agent-creation-studio.test.ts
+++ /dev/null
@@ -1,687 +0,0 @@
-import { createElement } from "react";
-import { fireEvent, render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
-import { ApiError } from "@multica/core/api";
-import type { Agent, RuntimeDevice } from "@multica/core/types";
-import {
- AgentNameField,
- ModeChooser,
- StudioFooter,
- applyDraftModelChange,
- applyDraftRuntimeChange,
- buildCreateAgentRequest,
- buildDuplicateDraft,
- buildInvocationTargets,
- classifyAgentCreateError,
- decodeBuilderInput,
- deriveDuplicateAccess,
- encodeBuilderInput,
- getAgentCreationScreenKey,
- isDraftDescriptionWithinLimit,
- mergeBuilderDraft,
- parseBuilderDraft,
- pickBuilderRestore,
- stripBuilderDraft,
- type AgentDraft,
-} from "./agent-creation-studio";
-
-vi.mock("../../i18n", () => ({
- useT: () => ({
- t: (
- selector: (translations: {
- creation_studio: {
- eyebrow: string;
- choose_title: string;
- choose_description: string;
- recommended: string;
- continue: string;
- modes: {
- blank: { title: string; description: string };
- ai: { title: string; description: string };
- };
- create_and_open: string;
- create_and_add: string;
- creating: string;
- name_conflict: string;
- };
- create_dialog: {
- name_label: string;
- name_placeholder: string;
- };
- }) => string,
- ) =>
- selector({
- creation_studio: {
- eyebrow: "Agent creation",
- choose_title: "How would you like to start?",
- choose_description: "Choose a creation mode.",
- recommended: "Recommended",
- continue: "Continue",
- modes: {
- blank: {
- title: "Start blank",
- description: "Configure every field yourself.",
- },
- ai: {
- title: "Build with AI",
- description: "Describe the outcome you want.",
- },
- },
- create_and_open: "Create and open",
- create_and_add: "Create and add",
- creating: "Creating…",
- name_conflict: "An agent with this name already exists.",
- },
- create_dialog: {
- name_label: "Name",
- name_placeholder: "Agent name",
- },
- }),
- }),
-}));
-
-describe("Agent creation studio screen keys", () => {
- it("groups configuration modes and separates the AI setup and builder", () => {
- expect(getAgentCreationScreenKey("blank", "")).toBe("configure");
- expect(getAgentCreationScreenKey("template", "")).toBe("configure");
- expect(getAgentCreationScreenKey("ai", "")).toBe("ai-setup");
- expect(getAgentCreationScreenKey("ai", "session-1")).toBe("ai-builder");
- });
-});
-
-describe("Agent creation errors", () => {
- it("classifies a conflict as a name error", () => {
- expect(
- classifyAgentCreateError(
- new ApiError("An agent with this name already exists", 409, "Conflict"),
- "Could not create the agent.",
- "This localized name is already in use.",
- ),
- ).toEqual({
- nameError: "This localized name is already in use.",
- formError: null,
- });
- });
-
- it("classifies a network error as a form error", () => {
- expect(
- classifyAgentCreateError(
- new Error("Network request failed"),
- "Could not create the agent.",
- "An agent with this name already exists.",
- ),
- ).toEqual({
- nameError: null,
- formError: "Network request failed",
- });
- });
-
- it("renders a name error directly below the name input", () => {
- const onChange = vi.fn();
- render(
- createElement(AgentNameField, {
- name: "Existing agent",
- error: "An agent with this name already exists",
- onChange,
- }),
- );
-
- const input = screen.getByRole("textbox", { name: "Name" });
- const error = screen.getByText("An agent with this name already exists");
- expect(input).toHaveAttribute("aria-invalid", "true");
- expect(input).toHaveAttribute("aria-describedby", error.id);
- expect(error).not.toHaveAttribute("role");
- expect(
- input.compareDocumentPosition(error) & Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
-
- fireEvent.change(input, { target: { value: "New agent" } });
- expect(onChange).toHaveBeenCalledWith("New agent");
- });
-
- it("focuses and selects the name input when a name error appears", () => {
- const onChange = vi.fn();
- const view = render(
- createElement(AgentNameField, {
- name: "Existing agent",
- error: null,
- onChange,
- }),
- );
-
- const input = screen.getByRole("textbox", { name: "Name" });
- expect(input).not.toHaveFocus();
-
- view.rerender(
- createElement(AgentNameField, {
- name: "Existing agent",
- error: "An agent with this name already exists",
- onChange,
- }),
- );
-
- expect(input).toHaveFocus();
- expect(input).toHaveValue("Existing agent");
- expect(input).toHaveProperty("selectionStart", 0);
- expect(input).toHaveProperty("selectionEnd", "Existing agent".length);
- });
-
- it("renders a generic error on the left side of the sticky footer", () => {
- render(
- createElement(StudioFooter, {
- canCreate: true,
- creating: false,
- squad: false,
- error: "Network request failed",
- onCreate: vi.fn(),
- }),
- );
-
- const error = screen.getByRole("alert");
- const button = screen.getByRole("button", { name: "Create and open" });
- expect(error.parentElement).toBe(button.parentElement);
- expect(
- error.compareDocumentPosition(button) & Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- });
-});
-
-const draft = (): AgentDraft => ({
- name: "Old name",
- description: "Old description",
- instructions: "Old instructions",
- avatarUrl: null,
- runtimeId: "runtime-1",
- model: "model-1",
- thinkingLevel: "",
- serviceTier: "",
- skillIds: new Set(["skill-1"]),
- permissionScope: "private",
- memberIds: new Set(),
- teamIds: new Set(),
-});
-
-describe("Agent creation studio mode chooser", () => {
- it("always offers AI-assisted creation", () => {
- render(
- createElement(ModeChooser, {
- onBlank: vi.fn(),
- onAI: vi.fn(),
- }),
- );
-
- expect(screen.getByText("Start blank")).toBeInTheDocument();
- expect(screen.getByText("Build with AI")).toBeInTheDocument();
- });
-});
-
-describe("Agent creation studio builder protocol", () => {
- it("parses and hides the structured draft block", () => {
- const content =
- 'Here is a first draft.\n<agent_draft>{"name":"Researcher","permission_scope":"workspace"}</agent_draft>';
-
- expect(parseBuilderDraft(content)).toEqual({
- name: "Researcher",
- permission_scope: "workspace",
- });
- expect(stripBuilderDraft(content)).toBe("Here is a first draft.");
- expect(parseBuilderDraft("<agent_draft>not json</agent_draft>")).toBeNull();
- });
-
- it("repairs literal line breaks emitted inside the instructions string", () => {
- const content = `<agent_draft>{"name":"Reviewer","instructions":"# Role
-Review every change.
-
-# Output
-Return findings."}</agent_draft>`;
-
- expect(parseBuilderDraft(content)).toEqual({
- name: "Reviewer",
- instructions: "# Role\nReview every change.\n\n# Output\nReturn findings.",
- });
- });
-
- it("round-trips only the user's natural-language request for chat display", () => {
- const content = encodeBuilderInput(
- "Create a release manager",
- draft(),
- [],
- [],
- { id: "runtime-1", name: "Codex", provider: "codex" },
- [{ id: "gpt-5.5", label: "GPT-5.5", provider: "openai" }],
- );
-
- expect(decodeBuilderInput(content)).toBe("Create a release manager");
- expect(JSON.parse(content.slice(content.indexOf("\n") + 1))).toMatchObject({
- selected_runtime: {
- id: "runtime-1",
- name: "Codex",
- provider: "codex",
- },
- available_runtime_models: [
- { id: "gpt-5.5", label: "GPT-5.5", provider: "openai" },
- ],
- });
- expect(decodeBuilderInput("ordinary chat message")).toBe(
- "ordinary chat message",
- );
- });
-
- // The builder chat is a real chat_session, so cancelling a started-but-empty
- // run defers the empty/non-empty judgment (#5219): the cancel response carries
- // no restore_to_input and the prompt arrives later as a durable draft-restore
- // row holding the ENCODED message. Handing that to the composer raw would show
- // the user a wall of JSON instead of the sentence they typed.
- it("decodes a durable draft restore before the builder composer adopts it", () => {
- const encoded = encodeBuilderInput(
- "Create a release manager",
- draft(),
- [],
- [],
- { id: "runtime-1", name: "Codex", provider: "codex" },
- [],
- );
-
- expect(pickBuilderRestore(null, { id: "msg-1", content: encoded })).toEqual({
- id: "msg-1",
- content: "Create a release manager",
- });
- expect(pickBuilderRestore(null, null)).toBeNull();
- });
-
- // The synchronous answer (task never started) is already decoded and already
- // in hand; it must not be displaced by a durable row for the same cancel.
- it("prefers the synchronous cancel answer over a durable restore", () => {
- expect(
- pickBuilderRestore(
- { id: "msg-1", content: "Create a release manager" },
- { id: "msg-1", content: "should not win" },
- ),
- ).toEqual({ id: "msg-1", content: "Create a release manager" });
- });
-
- it("merges safe fields and rejects unknown workspace references", () => {
- const result = mergeBuilderDraft(
- draft(),
- {
- name: "Release manager",
- model: 123,
- skill_ids: ["skill-2", "unknown-skill"],
- permission_scope: "members",
- member_ids: ["member-1", "unknown-member"],
- },
- new Set(["skill-1", "skill-2"]),
- new Set(["member-1"]),
- new Set(["model-1"]),
- );
-
- expect(result.name).toBe("Release manager");
- expect(result.model).toBe("model-1");
- expect([...result.skillIds]).toEqual(["skill-2"]);
- expect(result.permissionScope).toBe("members");
- expect([...result.memberIds]).toEqual(["member-1"]);
- });
-
- it("accepts catalog models and rejects invented or cross-runtime models", () => {
- const validModelIds = new Set(["gpt-5.5", "gpt-5.3-codex"]);
-
- expect(
- mergeBuilderDraft(
- draft(),
- { model: "gpt-5.5" },
- new Set(),
- new Set(),
- validModelIds,
- ).model,
- ).toBe("gpt-5.5");
- expect(
- mergeBuilderDraft(
- draft(),
- { model: "claude-3-5-sonnet" },
- new Set(),
- new Set(),
- validModelIds,
- ).model,
- ).toBe("model-1");
- expect(
- mergeBuilderDraft(
- draft(),
- { model: "invented-model" },
- new Set(),
- new Set(),
- validModelIds,
- ).model,
- ).toBe("model-1");
- expect(
- mergeBuilderDraft(
- draft(),
- { model: "" },
- new Set(),
- new Set(),
- validModelIds,
- ).model,
- ).toBe("");
- });
-
- it("preserves a user-selected custom model when the catalog is unavailable", () => {
- expect(
- mergeBuilderDraft(
- draft(),
- { model: "invented-model" },
- new Set(),
- new Set(),
- null,
- ).model,
- ).toBe("model-1");
- expect(
- mergeBuilderDraft(
- draft(),
- { model: "model-1" },
- new Set(),
- new Set(),
- null,
- ).model,
- ).toBe("model-1");
- expect(
- mergeBuilderDraft(
- draft(),
- { model: "invented-model" },
- new Set(),
- new Set(),
- new Set(),
- ).model,
- ).toBe("model-1");
- expect(
- mergeBuilderDraft(
- draft(),
- { model: "" },
- new Set(),
- new Set(),
- new Set(),
- ).model,
- ).toBe("model-1");
- });
-
- it("preserves scoped member and team grants when duplicating an agent", () => {
- const access = deriveDuplicateAccess({
- permission_mode: "public_to",
- invocation_targets: [
- { target_type: "member", target_id: "member-1" },
- { target_type: "team", target_id: "team-1" },
- ],
- });
- const duplicateDraft = {
- ...draft(),
- ...access,
- };
-
- expect(access.permissionScope).toBe("members");
- expect(buildInvocationTargets(duplicateDraft)).toEqual([
- { target_type: "member", target_id: "member-1" },
- { target_type: "team", target_id: "team-1" },
- ]);
- });
-
- it("keeps workspace-wide duplicate access workspace-wide", () => {
- expect(
- deriveDuplicateAccess({
- permission_mode: "public_to",
- invocation_targets: [{ target_type: "workspace", target_id: null }],
- }).permissionScope,
- ).toBe("workspace");
- });
-});
-
-const CODEX_RUNTIME: RuntimeDevice = {
- id: "runtime-1",
- workspace_id: "ws-1",
- name: "Codex laptop",
- provider: "codex",
- status: "online",
- owner_id: "user-1",
- visibility: "private",
-} as RuntimeDevice;
-
-const OTHER_RUNTIME: RuntimeDevice = {
- ...CODEX_RUNTIME,
- id: "runtime-2",
- name: "Spare laptop",
-} as RuntimeDevice;
-
-const sourceAgent = (overrides: Partial<Agent> = {}): Agent =>
- ({
- id: "agent-1",
- workspace_id: "ws-1",
- runtime_id: "runtime-1",
- name: "Fast Codex",
- description: "Ships quickly",
- instructions: "Be quick",
- avatar_url: null,
- runtime_mode: "managed",
- runtime_config: {},
- custom_args: ["--verbose"],
- visibility: "private",
- permission_mode: "private",
- invocation_targets: [],
- status: "idle",
- max_concurrent_tasks: 9,
- model: "gpt-5.6-sol",
- thinking_level: "high",
- service_tier: "priority",
- owner_id: "user-1",
- skills: [{ id: "skill-1", name: "Review", description: "" }],
- created_at: "2026-07-28T00:00:00Z",
- updated_at: "2026-07-28T00:00:00Z",
- archived_at: null,
- archived_by: null,
- ...overrides,
- }) as Agent;
-
-// MUL-5390: thinking_level / service_tier are runtime + model scoped. The create
-// flow never exposed them, so a Fast Codex agent could only be configured after
-// the fact and a Duplicate silently dropped the setting.
-describe("Agent creation studio execution overrides", () => {
- it("sends the selected thinking level and service tier", () => {
- const request = buildCreateAgentRequest({
- draft: {
- ...draft(),
- model: "gpt-5.6-sol",
- thinkingLevel: "high",
- serviceTier: "priority",
- },
- runtimeId: "runtime-1",
- });
-
- expect(request).toMatchObject({
- runtime_id: "runtime-1",
- model: "gpt-5.6-sol",
- thinking_level: "high",
- service_tier: "priority",
- });
- });
-
- it("omits empty overrides instead of sending an empty string", () => {
- const request = buildCreateAgentRequest({
- draft: { ...draft(), model: "" },
- runtimeId: "runtime-1",
- });
-
- expect(request.model).toBeUndefined();
- expect(request.thinking_level).toBeUndefined();
- expect(request.service_tier).toBeUndefined();
- expect("thinking_level" in request).toBe(true);
- expect(JSON.parse(JSON.stringify(request))).not.toHaveProperty(
- "thinking_level",
- );
- });
-
- it("carries the runtime-independent duplicate config", () => {
- const request = buildCreateAgentRequest({
- draft: { ...draft(), thinkingLevel: "high", serviceTier: "priority" },
- runtimeId: "runtime-1",
- duplicateSource: sourceAgent(),
- });
-
- expect(request.custom_args).toEqual(["--verbose"]);
- expect(request.max_concurrent_tasks).toBe(9);
- expect(request.thinking_level).toBe("high");
- });
-
- it.each([0, -1, 51])(
- "omits an invalid historical duplicate concurrency of %i",
- (maxConcurrentTasks) => {
- const request = buildCreateAgentRequest({
- draft: draft(),
- runtimeId: "runtime-1",
- duplicateSource: sourceAgent({
- max_concurrent_tasks: maxConcurrentTasks,
- }),
- });
-
- expect(request.max_concurrent_tasks).toBeUndefined();
- expect(request).not.toHaveProperty("max_concurrent_tasks");
- },
- );
-
- it("clears model, thinking level and service tier on a runtime change", () => {
- const current = {
- ...draft(),
- thinkingLevel: "high",
- serviceTier: "priority",
- };
-
- expect(applyDraftRuntimeChange(current, "runtime-2")).toMatchObject({
- runtimeId: "runtime-2",
- model: "",
- thinkingLevel: "",
- serviceTier: "",
- });
- });
-
- it("clears only the per-model overrides on a model change", () => {
- const current = {
- ...draft(),
- thinkingLevel: "high",
- serviceTier: "priority",
- };
- const next = applyDraftModelChange(current, "gpt-5.4-mini");
-
- expect(next).toMatchObject({
- runtimeId: "runtime-1",
- model: "gpt-5.4-mini",
- thinkingLevel: "",
- serviceTier: "",
- });
- // Re-selecting the same model must not wipe a choice the user just made.
- expect(applyDraftModelChange(current, "model-1")).toBe(current);
- });
-
- it("copies the execution config when the duplicate stays on its runtime", () => {
- const duplicate = buildDuplicateDraft(sourceAgent(), {
- runtimes: [CODEX_RUNTIME],
- currentUserId: "user-1",
- fallbackRuntimeId: "runtime-1",
- nameSuffix: " copy",
- });
-
- expect(duplicate).toMatchObject({
- name: "Fast Codex copy",
- runtimeId: "runtime-1",
- model: "gpt-5.6-sol",
- thinkingLevel: "high",
- serviceTier: "priority",
- });
- expect([...duplicate.skillIds]).toEqual(["skill-1"]);
- });
-
- it("drops the execution config when the duplicate falls back to another runtime", () => {
- // Source runtime is gone from the list (deleted, or private to someone
- // else), so the draft lands on the fallback. Keeping the source model here
- // is what persisted a cross-provider model before MUL-5390.
- const duplicate = buildDuplicateDraft(sourceAgent(), {
- runtimes: [OTHER_RUNTIME],
- currentUserId: "user-1",
- fallbackRuntimeId: "runtime-2",
- nameSuffix: " copy",
- });
-
- expect(duplicate).toMatchObject({
- runtimeId: "runtime-2",
- model: "",
- thinkingLevel: "",
- serviceTier: "",
- });
- });
-
- it("drops the execution config when the source runtime is private to someone else", () => {
- const duplicate = buildDuplicateDraft(sourceAgent(), {
- runtimes: [
- { ...CODEX_RUNTIME, owner_id: "user-2" } as RuntimeDevice,
- { ...OTHER_RUNTIME, owner_id: "user-1" } as RuntimeDevice,
- ],
- currentUserId: "user-1",
- fallbackRuntimeId: "runtime-2",
- nameSuffix: " copy",
- });
-
- expect(duplicate).toMatchObject({
- runtimeId: "runtime-2",
- model: "",
- thinkingLevel: "",
- serviceTier: "",
- });
- });
-
- it("keeps the overrides while the AI builder leaves the model alone", () => {
- const current = {
- ...draft(),
- thinkingLevel: "high",
- serviceTier: "priority",
- };
-
- expect(
- mergeBuilderDraft(
- current,
- { name: "Renamed" },
- new Set(),
- new Set(),
- new Set(["model-1"]),
- ),
- ).toMatchObject({
- name: "Renamed",
- model: "model-1",
- thinkingLevel: "high",
- serviceTier: "priority",
- });
- });
-
- it("drops the overrides when the AI builder moves the model", () => {
- const current = {
- ...draft(),
- thinkingLevel: "high",
- serviceTier: "priority",
- };
-
- expect(
- mergeBuilderDraft(
- current,
- { model: "gpt-5.4-mini" },
- new Set(),
- new Set(),
- new Set(["model-1", "gpt-5.4-mini"]),
- ),
- ).toMatchObject({
- model: "gpt-5.4-mini",
- thinkingLevel: "",
- serviceTier: "",
- });
- });
-
- it("enforces the 255-rune description limit the create API applies", () => {
- expect(isDraftDescriptionWithinLimit("a".repeat(255))).toBe(true);
- expect(isDraftDescriptionWithinLimit("a".repeat(256))).toBe(false);
- // Runes, not UTF-16 units: 255 CJK characters are exactly at the limit.
- expect(isDraftDescriptionWithinLimit("汉".repeat(255))).toBe(true);
- expect(isDraftDescriptionWithinLimit("汉".repeat(256))).toBe(false);
- });
-});
diff --git a/packages/views/agents/components/agent-creation-studio.tsx b/packages/views/agents/components/agent-creation-studio.tsx
deleted file mode 100644
index 3c6d6b6a1c..0000000000
--- a/packages/views/agents/components/agent-creation-studio.tsx
+++ /dev/null
@@ -1,2185 +0,0 @@
-"use client";
-
-import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
-import { AnimatePresence, motion, useReducedMotion } from "motion/react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
-import {
- ArrowLeft,
- Bot,
- Check,
- ChevronRight,
- FileText,
- Loader2,
- MessageSquare,
- Search,
-} from "lucide-react";
-import { toast } from "sonner";
-import { api, ApiError } from "@multica/core/api";
-import { useAuthStore } from "@multica/core/auth";
-import {
- AGENT_DESCRIPTION_MAX_LENGTH,
- AGENT_MAX_CONCURRENT_TASKS_MAX,
- AGENT_MAX_CONCURRENT_TASKS_MIN,
- agentTemplateDetailOptions,
- agentTemplateListOptions,
-} from "@multica/core/agents";
-import {
- chatKeys,
- chatMessagesOptions,
- pendingChatTaskOptions,
-} from "@multica/core/chat/queries";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { useWorkspacePaths } from "@multica/core/paths";
-import {
- runtimeDisplayLabel,
- runtimeListOptions,
- runtimeModelsOptions,
-} from "@multica/core/runtimes";
-import type {
- Agent,
- AgentInvocationTargetInput,
- AgentTemplateSummary,
- ChatMessage,
- CreateAgentRequest,
- MemberWithUser,
- RuntimeDevice,
- RuntimeModel,
-} from "@multica/core/types";
-import {
- agentListOptions,
- memberListOptions,
- skillListOptions,
- workspaceKeys,
-} from "@multica/core/workspace/queries";
-import { Button } from "@multica/ui/components/ui/button";
-import { Checkbox } from "@multica/ui/components/ui/checkbox";
-import { Input } from "@multica/ui/components/ui/input";
-import { Textarea } from "@multica/ui/components/ui/textarea";
-import {
- UI_EASE_OUT,
- UI_MOTION_DURATION,
-} from "@multica/ui/lib/motion";
-import { cn } from "@multica/ui/lib/utils";
-import { AvatarUploadControl } from "../../common/avatar-upload-control";
-import { useAppForeground } from "../../common/use-app-foreground";
-import { ChatInput } from "../../chat/components/chat-input";
-import { useChatDraftRestore } from "../../chat/components/use-chat-draft-restore";
-import {
- ChatMessageList,
- ChatMessageSkeleton,
-} from "../../chat/components/chat-message-list";
-import { useNavigation } from "../../navigation";
-import { useT } from "../../i18n";
-import { ActorAvatar } from "../../common/actor-avatar";
-import {
- SettingsCard,
- SettingsSection,
-} from "../../settings/components/settings-layout";
-import { ModelDropdown } from "./model-dropdown";
-import { CharCounter } from "./char-counter";
-import { ServiceTierSettingField } from "./inspector/service-tier-setting-field";
-import { ThinkingSettingField } from "./inspector/thinking-prop-row";
-import { RuntimePicker, isRuntimeUsableForUser } from "./runtime-picker";
-import { SkillMultiSelect } from "./skill-multi-select";
-
-type StudioMode = "choose" | "templates" | "blank" | "template" | "ai";
-type StudioScreenKey =
- | "choose"
- | "templates"
- | "configure"
- | "ai-setup"
- | "ai-builder";
-type TransitionDirection = 1 | -1;
-type PermissionScope = "private" | "workspace" | "members";
-
-export function getAgentCreationScreenKey(
- mode: StudioMode,
- builderSessionId: string,
-): StudioScreenKey {
- if (mode === "blank" || mode === "template") return "configure";
- if (mode === "ai") return builderSessionId ? "ai-builder" : "ai-setup";
- return mode;
-}
-
-export interface AgentDraft {
- name: string;
- description: string;
- instructions: string;
- avatarUrl: string | null;
- runtimeId: string;
- model: string;
- /** Runtime-native reasoning/effort token, scoped to `model`. */
- thinkingLevel: string;
- /** Runtime-native execution tier (Codex Speed), scoped to `model`. */
- serviceTier: string;
- skillIds: Set<string>;
- permissionScope: PermissionScope;
- memberIds: Set<string>;
- /** Team grants are not editable in this form yet, but duplicates must preserve them. */
- teamIds: Set<string>;
-}
-
-/**
- * Draft fields whose only meaning comes from the currently selected
- * runtime + model pair. A runtime change invalidates all three; a model
- * change invalidates the two that hang off the exact model catalog. Keeping
- * them together is what stops an orphan `thinking_level` / `service_tier`
- * from being persisted for a model that never advertised it — the daemon
- * would silently fall back at execution time and the settings page would
- * disagree with what actually ran (MUL-5390).
- */
-export function applyDraftRuntimeChange(
- draft: AgentDraft,
- runtimeId: string,
-): AgentDraft {
- return {
- ...draft,
- runtimeId,
- model: "",
- thinkingLevel: "",
- serviceTier: "",
- };
-}
-
-/** Model change: drop the per-model capability overrides, keep the runtime. */
-export function applyDraftModelChange(
- draft: AgentDraft,
- model: string,
-): AgentDraft {
- if (model === draft.model) return draft;
- return { ...draft, model, thinkingLevel: "", serviceTier: "" };
-}
-
-/**
- * Mirrors the server's `utf8.RuneCountInString` check (agent.go:1013). The
- * textarea's `maxLength` covers typing and pasting, but a duplicated agent or
- * an AI-builder draft can seed a longer value programmatically — without this
- * the create button would submit into a guaranteed 400.
- */
-export function isDraftDescriptionWithinLimit(description: string): boolean {
- return [...description].length <= AGENT_DESCRIPTION_MAX_LENGTH;
-}
-
-export interface BuilderDraftPayload {
- name?: unknown;
- description?: unknown;
- instructions?: unknown;
- model?: unknown;
- skill_ids?: unknown;
- permission_scope?: unknown;
- member_ids?: unknown;
-}
-
-export interface AgentCreateErrors {
- nameError: string | null;
- formError: string | null;
-}
-
-export function classifyAgentCreateError(
- error: unknown,
- fallbackMessage: string,
- conflictMessage: string,
-): AgentCreateErrors {
- const message =
- error instanceof Error && error.message ? error.message : fallbackMessage;
- return error instanceof ApiError && error.status === 409
- ? { nameError: conflictMessage, formError: null }
- : { nameError: null, formError: message };
-}
-
-const BUILDER_INPUT_PREFIX = "MULTICA_AGENT_BUILDER_INPUT\n";
-const EMPTY_CHAT_MESSAGES: ChatMessage[] = [];
-const EMPTY_DRAFT: AgentDraft = {
- name: "",
- description: "",
- instructions: "",
- avatarUrl: null,
- runtimeId: "",
- model: "",
- thinkingLevel: "",
- serviceTier: "",
- skillIds: new Set(),
- permissionScope: "private",
- memberIds: new Set(),
- teamIds: new Set(),
-};
-
-export function AgentCreationStudio() {
- const { t } = useT("agents");
- const wsId = useWorkspaceId();
- const paths = useWorkspacePaths();
- const navigation = useNavigation();
- const qc = useQueryClient();
- const currentUser = useAuthStore((state) => state.user);
- const duplicateId = navigation.searchParams.get("duplicate");
- const squadId = navigation.searchParams.get("squad");
- const shouldReduceMotion = useReducedMotion() ?? false;
-
- const { data: agents = [] } = useQuery(agentListOptions(wsId));
- const {
- data: runtimes = [],
- isLoading: runtimesLoading,
- isSuccess: runtimesLoaded,
- isError: runtimesFailed,
- } = useQuery(runtimeListOptions(wsId));
- const { data: members = [] } = useQuery(memberListOptions(wsId));
- const { data: workspaceSkills = [] } = useQuery(skillListOptions(wsId));
- const { data: templates = [], isLoading: templatesLoading } = useQuery(
- agentTemplateListOptions(),
- );
-
- const duplicateAgent = duplicateId
- ? agents.find((agent) => agent.id === duplicateId) ?? null
- : null;
- const [mode, setMode] = useState<StudioMode>(duplicateId ? "blank" : "choose");
- const [transitionDirection, setTransitionDirection] =
- useState<TransitionDirection>(1);
- const [draft, setDraft] = useState<AgentDraft>(EMPTY_DRAFT);
- // True when a duplicate had to fall back to another runtime, which drops the
- // source's model / thinking / speed. The notice explains the empty fields.
- const [duplicateRuntimeReset, setDuplicateRuntimeReset] = useState(false);
- const [sourceTemplate, setSourceTemplate] = useState<AgentTemplateSummary | null>(null);
- const [selectedTemplate, setSelectedTemplate] = useState<AgentTemplateSummary | null>(null);
- const [templateSearch, setTemplateSearch] = useState("");
- const [creating, setCreating] = useState(false);
- const [nameError, setNameError] = useState<string | null>(null);
- const [formError, setFormError] = useState<string | null>(null);
- 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;
- content: string;
- } | null>(null);
- const appliedAssistantMessageRef = useRef<string | null>(null);
- const builderSessionIdRef = useRef("");
-
- // The builder chat is a real chat_session, so cancelling a started-but-empty
- // run defers the empty/non-empty judgment exactly as it does in the main chat
- // (#5219): stopBuilder's response carries no restore_to_input, and the prompt
- // arrives later as a durable chat_draft_restore row. Without this hook the
- // studio composer would simply never see it. The two sources are exclusive —
- // the synchronous cancel answers immediately, the durable one lands after the
- // daemon acks — so whichever exists is handed to the composer.
- //
- // Gated on app foreground: this studio is a dedicated route, so being mounted
- // means the surface is on screen, but a backgrounded tab must not fetch/apply/
- // consume a restore the user is waiting on elsewhere. It recovers on its next
- // fetch once the tab is refocused.
- const appForeground = useAppForeground();
- const {
- restoreDraftRequest: durableRestoreRequest,
- handleRestoreDraftApplied: handleDurableRestoreApplied,
- } = useChatDraftRestore(builderSessionId || null, appForeground);
- const builderRestoreRequest = useMemo(
- () => pickBuilderRestore(builderRestoreDraft, durableRestoreRequest),
- [builderRestoreDraft, durableRestoreRequest],
- );
-
- useEffect(() => {
- builderSessionIdRef.current = builderSessionId;
- }, [builderSessionId]);
-
- useEffect(
- () => () => {
- const sessionId = builderSessionIdRef.current;
- if (sessionId) {
- // Covers route/sidebar navigation that bypasses the Studio back button.
- // The endpoint atomically cancels any running task before deletion.
- void api.deleteChatSession(sessionId).catch(() => {
- // A hard page unload may interrupt cleanup; runtime teardown remains
- // the final safety net for an orphaned hidden Builder Agent.
- });
- }
- },
- [],
- );
-
- const hasUnsavedDraft =
- mode !== "choose" &&
- mode !== "templates" &&
- (builderSessionId.length > 0 ||
- draft.name.trim().length > 0 ||
- draft.description.trim().length > 0 ||
- draft.instructions.trim().length > 0 ||
- draft.skillIds.size > 0);
-
- useEffect(() => {
- if (!hasUnsavedDraft || creating) return;
- const warnBeforeUnload = (event: BeforeUnloadEvent) => {
- event.preventDefault();
- event.returnValue = "";
- };
- window.addEventListener("beforeunload", warnBeforeUnload);
- return () => window.removeEventListener("beforeunload", warnBeforeUnload);
- }, [creating, hasUnsavedDraft]);
-
- const templateSlug = selectedTemplate?.slug ?? "";
- const templateDetailQuery = useQuery({
- ...agentTemplateDetailOptions(templateSlug),
- enabled: templateSlug.length > 0,
- });
-
- const builderMessagesQuery = useQuery({
- ...chatMessagesOptions(builderSessionId),
- refetchInterval: builderSessionId ? 1500 : false,
- });
- const builderPendingQuery = useQuery({
- ...pendingChatTaskOptions(builderSessionId),
- refetchInterval: builderSessionId ? 1500 : false,
- });
- const builderMessages = builderMessagesQuery.data ?? EMPTY_CHAT_MESSAGES;
- const builderPending = !!builderPendingQuery.data?.task_id;
- const builderDisplayMessages = useMemo(
- () =>
- builderMessages.map((message) => ({
- ...message,
- content:
- message.role === "user"
- ? decodeBuilderInput(message.content)
- : stripBuilderDraft(message.content),
- })),
- [builderMessages],
- );
-
- const usableRuntimes = useMemo(
- () =>
- runtimes.filter(
- (runtime) =>
- runtime.status === "online" &&
- isRuntimeUsableForUser(runtime, currentUser?.id ?? null),
- ),
- [currentUser?.id, runtimes],
- );
- const selectedRuntime =
- runtimes.find((runtime) => runtime.id === draft.runtimeId) ?? null;
- const builderModelsQuery = useQuery(
- runtimeModelsOptions(
- mode === "ai" && selectedRuntime?.status === "online"
- ? selectedRuntime.id
- : null,
- ),
- );
- // `null` means discovery is not available yet (or failed), while `[]` is
- // an authoritative catalog with no selectable models. In both cases the
- // builder may preserve the user's current value but cannot invent one.
- const builderModelCatalog = useMemo(
- () =>
- builderModelsQuery.isSuccess
- ? builderModelsQuery.data.supported
- ? builderModelsQuery.data.models
- : []
- : null,
- [builderModelsQuery.data, builderModelsQuery.isSuccess],
- );
- const validBuilderModelIds = useMemo(
- () =>
- builderModelCatalog === null
- ? null
- : new Set(builderModelCatalog.map((model) => model.id)),
- [builderModelCatalog],
- );
-
- useEffect(() => {
- if (draft.runtimeId || usableRuntimes.length === 0) return;
- setDraft((current) => ({ ...current, runtimeId: usableRuntimes[0]?.id ?? "" }));
- }, [draft.runtimeId, usableRuntimes]);
-
- useDuplicateDraftSeed({
- source: duplicateAgent,
- // `buildDuplicateDraft` decides whether the copy can stay on the source
- // runtime by looking it up in this list. An error is a decidable answer
- // (the runtime cannot be confirmed, so the fallback is right); a pending
- // query is not.
- runtimesSettled: runtimesLoaded || runtimesFailed,
- runtimes,
- currentUserId: currentUser?.id ?? null,
- fallbackRuntimeId: usableRuntimes[0]?.id ?? "",
- nameSuffix: t(($) => $.create_dialog.duplicate_copy_suffix),
- onSeed: (duplicated, runtimeReset) => {
- // Only the forced fallback gets the notice; a later manual runtime switch
- // is the user's own doing and needs no explanation.
- setDuplicateRuntimeReset(runtimeReset);
- setDraft(duplicated);
- },
- });
-
- const skillIdSet = useMemo(
- () => new Set(workspaceSkills.map((skill) => skill.id)),
- [workspaceSkills],
- );
- const memberIdSet = useMemo(
- () => new Set(members.map((member) => member.user_id)),
- [members],
- );
- // Realtime chat updates can mutate the cached messages array in place. Use
- // the latest structured message's scalar identity/content as effect inputs
- // so a draft is still applied when the array reference itself is unchanged.
- const latestBuilderDraftMessage = [...builderMessages]
- .reverse()
- .find(
- (message) =>
- message.role === "assistant" && parseBuilderDraft(message.content),
- );
- const latestBuilderDraftMessageId = latestBuilderDraftMessage?.id;
- const latestBuilderDraftMessageContent = latestBuilderDraftMessage?.content;
-
- useEffect(() => {
- if (
- !latestBuilderDraftMessageId ||
- !latestBuilderDraftMessageContent ||
- latestBuilderDraftMessageId === appliedAssistantMessageRef.current
- ) {
- return;
- }
- const payload = parseBuilderDraft(latestBuilderDraftMessageContent);
- if (!payload) return;
- appliedAssistantMessageRef.current = latestBuilderDraftMessageId;
- setDraft((current) =>
- mergeBuilderDraft(
- current,
- payload,
- skillIdSet,
- memberIdSet,
- validBuilderModelIds,
- ),
- );
- }, [
- latestBuilderDraftMessageContent,
- latestBuilderDraftMessageId,
- memberIdSet,
- skillIdSet,
- validBuilderModelIds,
- ]);
-
- const filteredTemplates = useMemo(() => {
- const query = templateSearch.trim().toLowerCase();
- if (!query) return templates;
- return templates.filter(
- (template) =>
- template.name.toLowerCase().includes(query) ||
- template.description.toLowerCase().includes(query) ||
- template.category?.toLowerCase().includes(query),
- );
- }, [templateSearch, templates]);
-
- const accessInvalid =
- draft.permissionScope === "members" &&
- draft.memberIds.size === 0 &&
- draft.teamIds.size === 0;
- const canCreate =
- draft.name.trim().length > 0 &&
- selectedRuntime != null &&
- isRuntimeUsableForUser(selectedRuntime, currentUser?.id ?? null) &&
- isDraftDescriptionWithinLimit(draft.description) &&
- !accessInvalid &&
- !creating;
- // Duplicating onto a different runtime than the source: the runtime-specific
- // execution config was dropped, so say it instead of letting the user notice
- // an empty model later.
- const currentModeLabel =
- mode === "choose"
- ? t(($) => $.creation_studio.step_choose)
- : mode === "templates"
- ? t(($) => $.creation_studio.step_template)
- : mode === "ai"
- ? t(($) => $.creation_studio.step_ai)
- : t(($) => $.creation_studio.step_configure);
-
- const resetCreationMode = () => {
- setTransitionDirection(-1);
- setMode("choose");
- setSelectedTemplate(null);
- setSourceTemplate(null);
- setBuilderSessionId("");
- setNameError(null);
- setFormError(null);
- };
-
- const deleteBuilderSession = async () => {
- if (!builderSessionId) return true;
- setBuilderClosing(true);
- setBuilderError(null);
- try {
- await api.deleteChatSession(builderSessionId);
- qc.removeQueries({ queryKey: chatKeys.messages(builderSessionId) });
- qc.removeQueries({ queryKey: chatKeys.pendingTask(builderSessionId) });
- builderSessionIdRef.current = "";
- return true;
- } catch (error) {
- setBuilderError(
- error instanceof Error
- ? error.message
- : t(($) => $.creation_studio.builder.stop_failed),
- );
- return false;
- } finally {
- setBuilderClosing(false);
- }
- };
-
- const goBack = async () => {
- if (mode === "choose") {
- navigation.push(paths.agents());
- return;
- }
- setTransitionDirection(-1);
- if (mode === "templates" && selectedTemplate) {
- setSelectedTemplate(null);
- return;
- }
- if (duplicateId) {
- if (!(await deleteBuilderSession())) return;
- navigation.push(paths.agents());
- return;
- }
- if (!(await deleteBuilderSession())) return;
- resetCreationMode();
- };
-
- const chooseBlank = () => {
- setSourceTemplate(null);
- setDraft((current) => ({
- ...EMPTY_DRAFT,
- runtimeId: current.runtimeId || usableRuntimes[0]?.id || "",
- }));
- setTransitionDirection(1);
- setMode("blank");
- };
-
- const chooseAI = () => {
- setTransitionDirection(1);
- setMode("ai");
- };
-
- const applyTemplate = () => {
- const detail = templateDetailQuery.data;
- if (!selectedTemplate || !detail) return;
- setSourceTemplate(selectedTemplate);
- setDraft((current) => ({
- ...EMPTY_DRAFT,
- name: detail.name,
- description: detail.description,
- instructions: detail.instructions,
- runtimeId: current.runtimeId || usableRuntimes[0]?.id || "",
- }));
- setTransitionDirection(1);
- setMode("template");
- };
-
- const startBuilder = async () => {
- if (!selectedRuntime || selectedRuntime.status !== "online") return;
- setBuilderStarting(true);
- setBuilderError(null);
- try {
- const session = await api.createAgentBuilderSession({
- runtime_id: selectedRuntime.id,
- model: draft.model.trim() || undefined,
- });
- if (!session.session_id) throw new Error(t(($) => $.creation_studio.builder.start_failed));
- setTransitionDirection(1);
- setBuilderSessionId(session.session_id);
- } catch (error) {
- setBuilderError(
- error instanceof Error ? error.message : t(($) => $.creation_studio.builder.start_failed),
- );
- } finally {
- setBuilderStarting(false);
- }
- };
-
- // 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) => applyDraftRuntimeChange(current, runtimeId));
- 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 — with the per-model thinking /
- // speed overrides — so the new runtime resolves its own defaults instead
- // of keeping values it may not serve.
- setDraft((current) => applyDraftRuntimeChange(current, boundRuntimeId));
- 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();
- // 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(
- text,
- draft,
- workspaceSkills,
- members,
- selectedRuntime,
- builderModelCatalog,
- );
- const result = await api.sendChatMessage(
- builderSessionId,
- encodedContent,
- );
- const createdAt = new Date().toISOString();
- qc.setQueryData<ChatMessage[]>(
- chatKeys.messages(builderSessionId),
- (current = []) =>
- current.some((message) => message.id === result.message_id)
- ? current
- : [
- ...current,
- {
- id: result.message_id,
- chat_session_id: builderSessionId,
- role: "user",
- content: encodedContent,
- task_id: result.task_id,
- created_at: createdAt,
- },
- ],
- );
- qc.setQueryData(chatKeys.pendingTask(builderSessionId), {
- task_id: result.task_id,
- status: "queued",
- created_at: createdAt,
- });
- await Promise.all([
- qc.invalidateQueries({ queryKey: chatKeys.messages(builderSessionId) }),
- qc.invalidateQueries({ queryKey: chatKeys.pendingTask(builderSessionId) }),
- ]);
- return true;
- } catch (error) {
- setBuilderError(
- error instanceof Error ? error.message : t(($) => $.creation_studio.builder.send_failed),
- );
- return false;
- }
- };
-
- const stopBuilder = async () => {
- const taskId = builderPendingQuery.data?.task_id;
- if (!taskId || !builderSessionId) return;
- qc.setQueryData(chatKeys.pendingTask(builderSessionId), {});
- try {
- const result = await api.cancelTaskById(taskId);
- const restored = result.cancelled_chat_message;
- if (restored?.restore_to_input) {
- setBuilderRestoreDraft({
- id: restored.message_id,
- content: decodeBuilderInput(restored.content),
- });
- }
- await Promise.all([
- qc.invalidateQueries({ queryKey: chatKeys.messages(builderSessionId) }),
- qc.invalidateQueries({ queryKey: chatKeys.pendingTask(builderSessionId) }),
- ]);
- } catch (error) {
- setBuilderError(
- error instanceof Error
- ? error.message
- : t(($) => $.creation_studio.builder.stop_failed),
- );
- qc.invalidateQueries({ queryKey: chatKeys.pendingTask(builderSessionId) });
- }
- };
-
- const createAgent = async () => {
- if (!canCreate || !selectedRuntime) return;
- setCreating(true);
- setNameError(null);
- setFormError(null);
- try {
- const invocationTargets = buildInvocationTargets(draft);
- let agent: Agent;
- if (sourceTemplate) {
- const response = await api.createAgentFromTemplate({
- template_slug: sourceTemplate.slug,
- name: draft.name.trim(),
- description: draft.description.trim(),
- instructions: draft.instructions.trim(),
- avatar_url: draft.avatarUrl ?? undefined,
- runtime_id: selectedRuntime.id,
- model: draft.model.trim() || undefined,
- permission_mode:
- draft.permissionScope === "private" ? "private" : "public_to",
- invocation_targets: invocationTargets,
- extra_skill_ids: [...draft.skillIds],
- });
- agent = response.agent;
- } else {
- const request = buildCreateAgentRequest({
- draft,
- runtimeId: selectedRuntime.id,
- template: mode === "ai" ? "agent_builder" : undefined,
- duplicateSource: duplicateAgent,
- });
- agent = await api.createAgent(request);
- }
-
- if (!agent.id) throw new Error(t(($) => $.creation_studio.create_failed));
- if (squadId) {
- try {
- await api.addSquadMember(squadId, {
- member_type: "agent",
- member_id: agent.id,
- });
- await Promise.all([
- qc.invalidateQueries({
- queryKey: [...workspaceKeys.squads(wsId), squadId, "members"],
- }),
- qc.invalidateQueries({
- queryKey: [...workspaceKeys.squads(wsId), squadId],
- }),
- ]);
- } catch (error) {
- toast.warning(
- t(($) => $.create_dialog.squad_join_failed_toast, {
- name: agent.name || draft.name.trim(),
- error: error instanceof Error ? error.message : "unknown error",
- }),
- );
- }
- }
- if (builderSessionId) {
- // The Agent is already committed. Builder cleanup is best-effort and
- // must never turn a successful create into a retryable create error.
- try {
- await api.deleteChatSession(builderSessionId);
- builderSessionIdRef.current = "";
- } catch {
- // Runtime teardown also removes orphaned system builders.
- }
- }
- await qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
- toast.success(t(($) => $.creation_studio.created, { name: agent.name || draft.name.trim() }));
- navigation.push(squadId ? paths.squadDetail(squadId) : paths.agentDetail(agent.id));
- } catch (error) {
- const nextErrors = classifyAgentCreateError(
- error,
- t(($) => $.creation_studio.create_failed),
- t(($) => $.creation_studio.name_conflict),
- );
- setNameError(nextErrors.nameError);
- setFormError(nextErrors.formError);
- setCreating(false);
- }
- };
-
- const screenKey = getAgentCreationScreenKey(mode, builderSessionId);
- const screenVariants = {
- initial: (direction: TransitionDirection) => ({
- opacity: 0,
- transform: shouldReduceMotion
- ? "translateX(0)"
- : direction === 1
- ? "translateX(8px)"
- : "translateX(-8px)",
- }),
- animate: {
- opacity: 1,
- transform: "translateX(0)",
- transition: {
- duration: shouldReduceMotion
- ? UI_MOTION_DURATION.fast
- : UI_MOTION_DURATION.standard,
- ease: UI_EASE_OUT,
- },
- },
- exit: (direction: TransitionDirection) => ({
- opacity: 0,
- transform: shouldReduceMotion
- ? "translateX(0)"
- : direction === 1
- ? "translateX(-8px)"
- : "translateX(8px)",
- transition: {
- duration: UI_MOTION_DURATION.fast,
- ease: UI_EASE_OUT,
- },
- }),
- };
-
- const updateAgentName = (name: string) => {
- setNameError(null);
- setDraft((current) => ({ ...current, name }));
- };
-
- return (
- <div className="flex min-h-0 flex-1 flex-col bg-background">
- <header className="flex h-14 shrink-0 items-center gap-3 border-b px-5">
- <Button type="button" variant="ghost" size="icon" onClick={() => void goBack()} disabled={builderClosing} aria-label={t(($) => $.creation_studio.back)}>
- <ArrowLeft className="size-4" aria-hidden="true" />
- </Button>
- <div className="min-w-0">
- <h1 className="truncate text-body font-semibold">
- {duplicateAgent
- ? t(($) => $.creation_studio.duplicate_title, { name: duplicateAgent.name })
- : squadId
- ? t(($) => $.creation_studio.squad_title)
- : t(($) => $.creation_studio.title)}
- </h1>
- <p className="truncate text-caption text-muted-foreground">
- {currentModeLabel}
- </p>
- </div>
- {mode !== "choose" && mode !== "templates" && (
- <div className="ml-auto hidden items-center gap-2 text-caption text-muted-foreground sm:flex">
- <span className="rounded-full bg-muted px-2 py-1">
- {sourceTemplate?.name ?? (mode === "ai" ? t(($) => $.creation_studio.modes.ai.title) : t(($) => $.creation_studio.modes.blank.title))}
- </span>
- {selectedRuntime && (
- <span className="rounded-full bg-muted px-2 py-1">
- {runtimeDisplayLabel(selectedRuntime)}
- </span>
- )}
- </div>
- )}
- </header>
-
- <AnimatePresence
- mode="wait"
- initial={false}
- custom={transitionDirection}
- >
- <motion.div
- key={screenKey}
- custom={transitionDirection}
- variants={screenVariants}
- initial="initial"
- animate="animate"
- exit="exit"
- className="flex min-h-0 flex-1 flex-col"
- >
- {mode === "choose" && (
- <ModeChooser
- onBlank={chooseBlank}
- onAI={chooseAI}
- />
- )}
-
- {mode === "templates" && (
- <TemplateChooser
- templates={filteredTemplates}
- loading={templatesLoading}
- search={templateSearch}
- onSearch={setTemplateSearch}
- selected={selectedTemplate}
- onSelect={setSelectedTemplate}
- detail={templateDetailQuery.data}
- detailLoading={templateDetailQuery.isLoading}
- onUse={applyTemplate}
- />
- )}
-
- {(mode === "blank" || mode === "template") && (
- <div className="min-h-0 flex-1 overflow-y-auto">
- <div className="mx-auto w-full max-w-4xl px-5 py-8 sm:px-8">
- {duplicateAgent && (
- <div className="mb-5 rounded-lg border border-warning/30 bg-warning/5 px-4 py-3 text-body">
- {t(($) => $.creation_studio.duplicate_env_notice)}
- </div>
- )}
- {duplicateRuntimeReset && (
- <div className="mb-5 rounded-lg border border-warning/30 bg-warning/5 px-4 py-3 text-body">
- {t(($) => $.creation_studio.duplicate_runtime_reset_notice)}
- </div>
- )}
- <ConfigurationPanel
- draft={draft}
- onChange={setDraft}
- runtimes={runtimes}
- runtimesLoading={runtimesLoading}
- members={members}
- currentUserId={currentUser?.id ?? null}
- nameError={nameError}
- onNameChange={updateAgentName}
- />
- </div>
- <StudioFooter
- canCreate={canCreate}
- creating={creating}
- squad={!!squadId}
- error={formError}
- onCreate={createAgent}
- />
- </div>
- )}
-
- {mode === "ai" && !builderSessionId && (
- <BuilderSetup
- draft={draft}
- onChange={setDraft}
- runtimes={runtimes}
- runtimesLoading={runtimesLoading}
- members={members}
- currentUserId={currentUser?.id ?? null}
- selectedRuntime={selectedRuntime}
- starting={builderStarting}
- error={builderError}
- onStart={startBuilder}
- onConnectRuntime={() => navigation.push(paths.runtimes())}
- />
- )}
-
- {mode === "ai" && builderSessionId && (
- <div className="grid min-h-0 flex-1 grid-cols-1 lg:grid-cols-[minmax(0,1.1fr)_minmax(420px,0.9fr)]">
- <BuilderConversation
- sessionId={builderSessionId}
- messages={builderDisplayMessages}
- loading={builderMessagesQuery.isLoading}
- pendingTask={builderPendingQuery.data}
- runtimeOnline={selectedRuntime?.status === "online"}
- onSend={sendBuilderMessage}
- onStop={() => void stopBuilder()}
- restoreDraftRequest={builderRestoreRequest}
- onRestoreDraftApplied={() => {
- if (builderRestoreDraft) {
- setBuilderRestoreDraft(null);
- return;
- }
- handleDurableRestoreApplied();
- }}
- error={builderError}
- />
- <div className="min-h-0 overflow-y-auto border-l bg-muted/10">
- <div className="mx-auto max-w-2xl px-5 py-6">
- <div className="mb-6">
- <h2 className="text-title-sm font-semibold tracking-tight">
- {t(($) => $.creation_studio.live_draft)}
- </h2>
- <p className="mt-1 text-caption text-muted-foreground">
- {t(($) => $.creation_studio.live_draft_hint)}
- </p>
- </div>
- <ConfigurationPanel
- compact
- draft={draft}
- onChange={setDraft}
- runtimes={runtimes}
- runtimesLoading={runtimesLoading}
- members={members}
- currentUserId={currentUser?.id ?? null}
- nameError={nameError}
- onNameChange={updateAgentName}
- onRuntimeSelect={(runtimeId) => {
- void switchBuilderRuntime(runtimeId);
- }}
- runtimeSwitchPending={builderPending}
- runtimeSwitchInFlight={builderSwitchingRuntime}
- />
- </div>
- <StudioFooter
- canCreate={canCreate && !builderPending}
- creating={creating}
- squad={!!squadId}
- error={formError}
- onCreate={createAgent}
- />
- </div>
- </div>
- )}
- </motion.div>
- </AnimatePresence>
- </div>
- );
-}
-
-export function ModeChooser({
- onBlank,
- onAI,
-}: {
- onBlank: () => void;
- onAI: () => void;
-}) {
- const { t } = useT("agents");
- const modes = [
- {
- icon: FileText,
- title: t(($) => $.creation_studio.modes.blank.title),
- description: t(($) => $.creation_studio.modes.blank.description),
- action: onBlank,
- },
- {
- icon: MessageSquare,
- title: t(($) => $.creation_studio.modes.ai.title),
- description: t(($) => $.creation_studio.modes.ai.description),
- action: onAI,
- recommended: true,
- },
- ];
- return (
- <main className="flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-5 py-10">
- <div className="w-full max-w-5xl">
- <div className="mx-auto max-w-2xl text-center">
- <div className="text-caption font-medium uppercase tracking-wider text-muted-foreground">
- {t(($) => $.creation_studio.eyebrow)}
- </div>
- <h2 className="mt-2 text-balance text-display-sm font-semibold tracking-tight sm:text-display">
- {t(($) => $.creation_studio.choose_title)}
- </h2>
- <p className="mt-3 text-pretty text-body text-muted-foreground">
- {t(($) => $.creation_studio.choose_description)}
- </p>
- </div>
- <div className="mx-auto mt-9 grid max-w-3xl gap-4 md:grid-cols-2">
- {modes.map(({ icon: Icon, title, description, action, recommended }) => (
- <button
- key={title}
- type="button"
- onClick={action}
- className={cn(
- "group relative flex min-h-56 flex-col items-start rounded-xl border bg-card p-5 text-left",
- "transition-[border-color,background-color,transform] hover:-translate-y-0.5 hover:border-primary/40 hover:bg-accent/30",
- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- recommended && "border-primary/30 bg-primary/[0.025]",
- )}
- >
- {recommended && (
- <span className="absolute right-4 top-4 rounded-full bg-primary/10 px-2 py-1 text-micro font-medium text-primary">
- {t(($) => $.creation_studio.recommended)}
- </span>
- )}
- <span className="flex size-11 items-center justify-center rounded-lg bg-muted text-muted-foreground group-hover:text-foreground">
- <Icon className="size-5" aria-hidden="true" />
- </span>
- <span className="mt-7 text-title-sm font-semibold">{title}</span>
- <span className="mt-2 text-body leading-6 text-muted-foreground">{description}</span>
- <span className="mt-auto flex items-center gap-1 pt-5 text-caption font-medium text-foreground">
- {t(($) => $.creation_studio.continue)}
- <ChevronRight className="size-3.5 transition-transform group-hover:translate-x-0.5" aria-hidden="true" />
- </span>
- </button>
- ))}
- </div>
- </div>
- </main>
- );
-}
-
-function TemplateChooser({
- templates,
- loading,
- search,
- onSearch,
- selected,
- onSelect,
- detail,
- detailLoading,
- onUse,
-}: {
- templates: AgentTemplateSummary[];
- loading: boolean;
- search: string;
- onSearch: (value: string) => void;
- selected: AgentTemplateSummary | null;
- onSelect: (template: AgentTemplateSummary) => void;
- detail: { instructions: string } | undefined;
- detailLoading: boolean;
- onUse: () => void;
-}) {
- const { t } = useT("agents");
- return (
- <main className="grid min-h-0 flex-1 grid-cols-1 lg:grid-cols-[minmax(360px,0.9fr)_minmax(0,1.1fr)]">
- <section className="flex min-h-0 flex-col border-r">
- <div className="border-b p-4">
- <div className="relative">
- <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" aria-hidden="true" />
- <Input
- name="template-search"
- autoComplete="off"
- value={search}
- onChange={(event) => onSearch(event.target.value)}
- placeholder={t(($) => $.creation_studio.templates.search)}
- className="pl-9"
- aria-label={t(($) => $.creation_studio.templates.search_label)}
- />
- </div>
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto p-3">
- {loading ? (
- <div className="flex justify-center py-16"><Loader2 className="size-5 animate-spin text-muted-foreground" /></div>
- ) : templates.length === 0 ? (
- <div className="py-16 text-center text-body text-muted-foreground">{t(($) => $.creation_studio.templates.empty)}</div>
- ) : (
- <div className="space-y-2">
- {templates.map((template) => (
- <button
- key={template.slug}
- type="button"
- onClick={() => onSelect(template)}
- className={cn(
- "flex w-full items-start gap-3 rounded-lg border p-3 text-left transition-colors",
- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- selected?.slug === template.slug ? "border-primary bg-primary/5" : "border-transparent hover:bg-muted",
- )}
- >
- <span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted"><Bot className="size-4" /></span>
- <span className="min-w-0 flex-1">
- <span className="flex items-center gap-2">
- <span className="truncate text-body font-medium">{template.name}</span>
- {template.category && <span className="ml-auto shrink-0 text-micro text-muted-foreground">{template.category}</span>}
- </span>
- <span className="mt-1 line-clamp-2 block text-caption leading-5 text-muted-foreground">{template.description}</span>
- </span>
- </button>
- ))}
- </div>
- )}
- </div>
- </section>
- <section className="min-h-0 overflow-y-auto">
- {!selected ? (
- <div className="flex h-full min-h-80 flex-col items-center justify-center px-8 text-center text-muted-foreground">
- <Bot className="size-8" />
- <p className="mt-3 text-body">{t(($) => $.creation_studio.templates.select_hint)}</p>
- </div>
- ) : (
- <div className="mx-auto max-w-3xl p-6 sm:p-8">
- <div className="flex items-start gap-4">
- <span className="flex size-12 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary"><Bot className="size-6" /></span>
- <div><h2 className="text-title-lg font-semibold">{selected.name}</h2><p className="mt-1 text-body leading-6 text-muted-foreground">{selected.description}</p></div>
- </div>
- {selected.skills.length > 0 && (
- <div className="mt-7"><h3 className="text-caption font-semibold uppercase tracking-wider text-muted-foreground">{t(($) => $.creation_studio.templates.skills)}</h3><div className="mt-3 space-y-2">{selected.skills.map((skill) => <div key={skill.source_url} className="flex items-start gap-2 rounded-lg border bg-card p-3"><Check className="mt-0.5 size-4 shrink-0 text-success" /><div><div className="text-body font-medium">{skill.cached_name}</div><div className="mt-0.5 text-caption text-muted-foreground">{skill.cached_description}</div></div></div>)}</div></div>
- )}
- <div className="mt-7"><h3 className="text-caption font-semibold uppercase tracking-wider text-muted-foreground">{t(($) => $.creation_studio.templates.instructions)}</h3><div className="mt-3 max-h-80 overflow-y-auto whitespace-pre-wrap rounded-lg border bg-muted/30 p-4 text-body leading-6">{detailLoading ? <Loader2 className="size-4 animate-spin" /> : detail?.instructions}</div></div>
- <div className="mt-7 flex justify-end"><Button onClick={onUse} disabled={detailLoading || !detail}>{t(($) => $.creation_studio.templates.use)}<ChevronRight className="size-4" /></Button></div>
- </div>
- )}
- </section>
- </main>
- );
-}
-
-function ConfigurationPanel({
- draft,
- onChange,
- runtimes,
- runtimesLoading,
- members,
- currentUserId,
- nameError,
- onNameChange,
- compact = false,
- onRuntimeSelect,
- runtimeSwitchPending = false,
- runtimeSwitchInFlight = false,
-}: {
- draft: AgentDraft;
- onChange: (draft: AgentDraft) => void;
- runtimes: RuntimeDevice[];
- runtimesLoading: boolean;
- members: MemberWithUser[];
- currentUserId: string | null;
- nameError: string | null;
- onNameChange: (name: string) => void;
- 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 — and the per-model thinking / speed
- // overrides — on runtime change so the new runtime resolves its own
- // defaults instead of stale values.
- onChange(applyDraftRuntimeChange(draft, id));
- };
-
- return (
- <div className={cn("space-y-8", compact && "space-y-6")}>
- <SettingsSection
- title={t(($) => $.creation_studio.sections.identity)}
- description={t(($) => $.creation_studio.sections.identity_hint)}
- >
- <SettingsCard>
- <DraftFieldRow
- compact={compact}
- label={t(($) => $.create_dialog.avatar.change_aria)}
- >
- <div className={cn(!compact && "sm:flex sm:justify-end")}>
- <AvatarUploadControl
- variant="agent"
- value={draft.avatarUrl}
- name={draft.name}
- size={compact ? 52 : 56}
- onUploaded={(url) => set("avatarUrl", url)}
- onEmojiSelected={(value) => set("avatarUrl", value)}
- onClear={() => set("avatarUrl", null)}
- />
- </div>
- </DraftFieldRow>
- <AgentNameField
- compact={compact}
- name={draft.name}
- error={nameError}
- onChange={onNameChange}
- />
- <DraftFieldRow
- compact={compact}
- align="start"
- label={t(($) => $.create_dialog.description_label)}
- htmlFor="agent-create-description"
- >
- <div>
- <Textarea
- id="agent-create-description"
- name="agent-description"
- autoComplete="off"
- aria-label={t(($) => $.create_dialog.description_label)}
- value={draft.description}
- onChange={(event) => set("description", event.target.value)}
- placeholder={t(($) => $.create_dialog.description_placeholder)}
- rows={compact ? 3 : 4}
- // The create API rejects >255 characters with a 400. Cap the
- // input and show the counter so the limit is visible before
- // submitting, matching the settings page.
- maxLength={AGENT_DESCRIPTION_MAX_LENGTH}
- className="resize-y"
- />
- <CharCounter
- length={[...draft.description].length}
- max={AGENT_DESCRIPTION_MAX_LENGTH}
- />
- </div>
- </DraftFieldRow>
- </SettingsCard>
- </SettingsSection>
-
- <SettingsSection
- title={t(($) => $.creation_studio.sections.behavior)}
- description={t(($) => $.creation_studio.sections.behavior_hint)}
- >
- <SettingsCard>
- <DraftFieldRow
- compact
- label={t(($) => $.create_dialog.instructions.label)}
- htmlFor="agent-create-instructions"
- >
- <Textarea
- id="agent-create-instructions"
- name="agent-instructions"
- autoComplete="off"
- aria-label={t(($) => $.create_dialog.instructions.label)}
- value={draft.instructions}
- onChange={(event) => set("instructions", event.target.value)}
- placeholder={t(($) => $.create_dialog.instructions.editor_placeholder)}
- rows={compact ? 9 : 12}
- className="min-h-44 resize-y font-mono text-label leading-6"
- />
- </DraftFieldRow>
- <div className="px-4 py-4">
- <SkillMultiSelect
- selectedIds={draft.skillIds}
- onChange={(ids) => set("skillIds", ids)}
- />
- </div>
- </SettingsCard>
- </SettingsSection>
-
- <SettingsSection
- title={t(($) => $.creation_studio.sections.execution)}
- description={t(($) => $.creation_studio.sections.execution_hint)}
- >
- <SettingsCard>
- <div className={cn("grid gap-4 px-4 py-4", !compact && "sm:grid-cols-2")}>
- <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-caption 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) => onChange(applyDraftModelChange(draft, value))}
- // A successful switch clears the model, so an edit made while the
- // rebind is in flight would be silently discarded.
- disabled={!selectedRuntime || runtimeSwitchInFlight}
- />
- </div>
- {/* Both fields fail closed: they render only when the exact selected
- model's live catalog advertises the capability (or a value is
- already set and needs clearing), so an offline runtime, a failed
- discovery or an empty model shows nothing instead of an input
- that cannot be honoured. */}
- <AgentExecutionOverrides
- draft={draft}
- runtime={selectedRuntime}
- disabled={runtimeLocked}
- onChange={onChange}
- />
- </SettingsCard>
- </SettingsSection>
-
- <SettingsSection
- title={t(($) => $.creation_studio.sections.access)}
- description={t(($) => $.creation_studio.sections.access_hint)}
- >
- <SettingsCard>
- <div
- className="space-y-1 p-2"
- role="radiogroup"
- aria-label={t(($) => $.creation_studio.sections.access)}
- >
- {(["private", "workspace", "members"] as PermissionScope[]).map(
- (scope) => (
- <button
- key={scope}
- type="button"
- role="radio"
- aria-checked={draft.permissionScope === scope}
- onClick={() => set("permissionScope", scope)}
- className={cn(
- "flex w-full items-start gap-3 rounded-md px-3 py-2.5 text-left transition-colors",
- "hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- draft.permissionScope === scope && "bg-muted",
- )}
- >
- <span
- className={cn(
- "mt-1 flex size-3.5 shrink-0 items-center justify-center rounded-full border",
- draft.permissionScope === scope && "border-primary",
- )}
- aria-hidden="true"
- >
- {draft.permissionScope === scope ? (
- <span className="size-1.5 rounded-full bg-primary" />
- ) : null}
- </span>
- <span className="min-w-0">
- <span className="block text-body font-medium">
- {t(($) => $.creation_studio.access[scope].title)}
- </span>
- <span className="mt-0.5 block text-caption leading-5 text-muted-foreground">
- {t(($) => $.creation_studio.access[scope].description)}
- </span>
- </span>
- </button>
- ),
- )}
- </div>
- {draft.permissionScope === "members" ? (
- <div className="max-h-48 overflow-y-auto p-2">
- {otherMembers.map((member) => {
- const checked = draft.memberIds.has(member.user_id);
- return (
- <label
- key={member.user_id}
- className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-2 hover:bg-muted"
- >
- <Checkbox
- checked={checked}
- onCheckedChange={(value) => {
- const next = new Set(draft.memberIds);
- if (value === true) next.add(member.user_id);
- else next.delete(member.user_id);
- set("memberIds", next);
- }}
- />
- <ActorAvatar
- actorType="member"
- actorId={member.user_id}
- size="sm"
- />
- <span className="min-w-0 flex-1 truncate text-body">
- {member.name}
- </span>
- </label>
- );
- })}
- {draft.memberIds.size === 0 ? (
- <p className="px-2 py-1 text-caption text-destructive">
- {t(($) => $.creation_studio.access.members.required)}
- </p>
- ) : null}
- </div>
- ) : null}
- </SettingsCard>
- </SettingsSection>
- </div>
- );
-}
-
-export function AgentNameField({
- name,
- error,
- onChange,
- compact = false,
-}: {
- name: string;
- error: string | null;
- onChange: (name: string) => void;
- compact?: boolean;
-}) {
- const { t } = useT("agents");
- const errorId = "agent-create-name-error";
- const inputRef = useRef<HTMLInputElement>(null);
-
- useEffect(() => {
- if (!error) return;
- inputRef.current?.focus();
- inputRef.current?.select();
- }, [error]);
-
- return (
- <DraftFieldRow
- compact={compact}
- label={t(($) => $.create_dialog.name_label)}
- htmlFor="agent-create-name"
- >
- <div className="space-y-1.5">
- <Input
- ref={inputRef}
- id="agent-create-name"
- name="agent-name"
- autoComplete="off"
- aria-label={t(($) => $.create_dialog.name_label)}
- aria-invalid={!!error}
- aria-describedby={error ? errorId : undefined}
- value={name}
- onChange={(event) => onChange(event.target.value)}
- placeholder={t(($) => $.create_dialog.name_placeholder)}
- />
- {error ? (
- <p id={errorId} className="text-caption text-destructive">
- {error}
- </p>
- ) : null}
- </div>
- </DraftFieldRow>
- );
-}
-
-/**
- * Per-model execution overrides (thinking level + Codex speed) for the create
- * flow. Capability comes from the exact selected model's live catalog on the
- * selected runtime, so nothing renders while that cannot be resolved — an
- * offline runtime, failed discovery, or an empty "use the runtime default"
- * model. That is the same fail-closed rule the settings page follows, and it is
- * why no value can be sent that the daemon would refuse to honour.
- */
-export function AgentExecutionOverrides({
- draft,
- runtime,
- disabled = false,
- onChange,
-}: {
- draft: AgentDraft;
- runtime: RuntimeDevice | null;
- disabled?: boolean;
- onChange: (draft: AgentDraft) => void;
-}) {
- const { t } = useT("agents");
- const runtimeOnline = runtime?.status === "online";
- return (
- <>
- <ThinkingSettingField
- label={t(($) => $.creation_studio.thinking_label)}
- runtimeId={runtime?.id ?? null}
- runtimeOnline={runtimeOnline}
- provider={runtime?.provider ?? ""}
- model={draft.model}
- value={draft.thinkingLevel}
- canEdit={!disabled}
- onChange={(thinkingLevel) => onChange({ ...draft, thinkingLevel })}
- />
- <ServiceTierSettingField
- label={t(($) => $.creation_studio.speed_label)}
- runtimeId={runtime?.id ?? null}
- runtimeOnline={runtimeOnline}
- model={draft.model}
- value={draft.serviceTier}
- canEdit={!disabled}
- onChange={(serviceTier) => onChange({ ...draft, serviceTier })}
- />
- </>
- );
-}
-
-function DraftFieldRow({
- label,
- children,
- compact = false,
- align = "center",
- htmlFor,
-}: {
- label: string;
- children: ReactNode;
- compact?: boolean;
- align?: "center" | "start";
- htmlFor?: string;
-}) {
- return (
- <div
- className={cn(
- "gap-3 px-4 py-4",
- compact
- ? "flex flex-col"
- : "grid sm:grid-cols-[minmax(0,1fr)_minmax(280px,1.2fr)] sm:gap-8",
- !compact && (align === "center" ? "sm:items-center" : "sm:items-start"),
- )}
- >
- {htmlFor ? (
- <label htmlFor={htmlFor} className="text-body font-medium">
- {label}
- </label>
- ) : (
- <div className="text-body font-medium">{label}</div>
- )}
- <div className="min-w-0">{children}</div>
- </div>
- );
-}
-
-function BuilderSetup({ draft, onChange, runtimes, runtimesLoading, members, currentUserId, selectedRuntime, starting, error, onStart, onConnectRuntime }: { draft: AgentDraft; onChange: (draft: AgentDraft) => void; runtimes: RuntimeDevice[]; runtimesLoading: boolean; members: MemberWithUser[]; currentUserId: string | null; selectedRuntime: RuntimeDevice | null; starting: boolean; error: string | null; onStart: () => void; onConnectRuntime: () => void; }) {
- const { t } = useT("agents");
- const hasOnline = runtimes.some((runtime) => runtime.status === "online" && isRuntimeUsableForUser(runtime, currentUserId));
- return <main className="flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-5 py-10"><div className="w-full max-w-xl rounded-xl border bg-card p-6 shadow-sm"><span className="flex size-11 items-center justify-center rounded-lg bg-primary/10 text-primary"><MessageSquare className="size-5" /></span><h2 className="mt-5 text-title-lg font-semibold">{t(($) => $.creation_studio.builder.setup_title)}</h2><p className="mt-2 text-body leading-6 text-muted-foreground">{t(($) => $.creation_studio.builder.setup_description)}</p><div className="mt-6 space-y-4"><RuntimePicker runtimes={runtimes} runtimesLoading={runtimesLoading} members={members} currentUserId={currentUserId} selectedRuntimeId={draft.runtimeId} onSelect={(runtimeId) => { if (runtimeId !== draft.runtimeId) onChange(applyDraftRuntimeChange(draft, runtimeId)); }} /><ModelDropdown runtimeId={selectedRuntime?.id ?? null} runtimeOnline={selectedRuntime?.status === "online"} value={draft.model} onChange={(model) => onChange(applyDraftModelChange(draft, model))} disabled={!selectedRuntime} /></div>{error && <div role="alert" className="mt-4 text-body text-destructive">{error}</div>}<div className="mt-6 flex justify-end">{hasOnline ? <Button onClick={onStart} disabled={starting || selectedRuntime?.status !== "online"}>{starting && <Loader2 className="size-4 animate-spin" />}{t(($) => $.creation_studio.builder.start)}</Button> : <Button onClick={onConnectRuntime}>{t(($) => $.creation_studio.builder.connect_runtime)}</Button>}</div></div></main>;
-}
-
-function BuilderConversation({
- sessionId,
- messages,
- loading,
- pendingTask,
- runtimeOnline,
- onSend,
- onStop,
- restoreDraftRequest,
- onRestoreDraftApplied,
- error,
-}: {
- sessionId: string;
- messages: ChatMessage[];
- loading: boolean;
- pendingTask: { task_id?: string; status?: string; created_at?: string } | undefined;
- runtimeOnline: boolean;
- onSend: (content: string) => Promise<boolean>;
- onStop: () => void;
- restoreDraftRequest: { id: string; content: string } | null;
- onRestoreDraftApplied: () => void;
- error: string | null;
-}) {
- const { t } = useT("agents");
- const pending = !!pendingTask?.task_id;
- const draftKey = `agent-builder:${sessionId}`;
- const prompts = [
- t(($) => $.creation_studio.builder.prompt_review),
- t(($) => $.creation_studio.builder.prompt_research),
- t(($) => $.creation_studio.builder.prompt_assistant),
- ];
-
- return (
- // `@container`: this is one column of the studio's split layout, so the
- // shared chat gutter must size against the column, not the viewport.
- <section className="flex min-h-0 flex-col bg-background @container">
- <header className="flex min-h-14 shrink-0 items-center justify-between gap-4 border-b px-5 py-2.5">
- <div className="min-w-0">
- <h2 className="truncate text-body font-semibold">
- {t(($) => $.creation_studio.builder.chat_title)}
- </h2>
- <p className="truncate text-caption text-muted-foreground">
- {t(($) => $.creation_studio.builder.chat_hint)}
- </p>
- </div>
- <div className="flex shrink-0 items-center gap-1.5 text-caption text-muted-foreground">
- <span
- className={cn(
- "size-2 rounded-full",
- runtimeOnline ? "bg-success" : "bg-muted-foreground/40",
- )}
- aria-hidden="true"
- />
- {runtimeOnline
- ? t(($) => $.creation_studio.builder.runtime_online)
- : t(($) => $.creation_studio.builder.runtime_offline)}
- </div>
- </header>
-
- {loading ? (
- <ChatMessageSkeleton />
- ) : messages.length > 0 || pending ? (
- <ChatMessageList
- messages={messages}
- pendingTask={pendingTask}
- availability={runtimeOnline ? "online" : "offline"}
- transformContent={stripBuilderDraft}
- />
- ) : (
- <div className="flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-5 py-8">
- <div className="w-full max-w-xl text-center">
- <h3 className="text-balance text-title font-semibold">
- {t(($) => $.creation_studio.builder.empty_title)}
- </h3>
- <p className="mx-auto mt-2 max-w-md text-pretty text-body leading-6 text-muted-foreground">
- {t(($) => $.creation_studio.builder.empty_description)}
- </p>
- <div className="mt-5 flex flex-wrap justify-center gap-2">
- {prompts.map((prompt) => (
- <button
- key={prompt}
- type="button"
- onClick={() => void onSend(prompt)}
- className="rounded-full border bg-background px-3 py-1.5 text-caption transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- {prompt}
- </button>
- ))}
- </div>
- </div>
- </div>
- )}
-
- {error ? (
- <div
- role="alert"
- aria-live="polite"
- className="mx-5 mb-3 rounded-md bg-destructive/5 px-3 py-2 text-body text-destructive"
- >
- {error}
- </div>
- ) : null}
-
- <ChatInput
- onSend={(content) => onSend(content)}
- onStop={onStop}
- isRunning={pending}
- disabled={!runtimeOnline}
- agentName={t(($) => $.creation_studio.builder.chat_title)}
- draftKeyOverride={draftKey}
- editorKeyOverride={draftKey}
- restoreDraftRequest={restoreDraftRequest}
- onRestoreDraftApplied={onRestoreDraftApplied}
- />
- </section>
- );
-}
-
-export function StudioFooter({
- canCreate,
- creating,
- squad,
- error,
- onCreate,
-}: {
- canCreate: boolean;
- creating: boolean;
- squad: boolean;
- error: string | null;
- onCreate: () => void;
-}) {
- const { t } = useT("agents");
- return (
- <div className="pe-chat-launcher sticky bottom-0 mt-8 flex items-center justify-between gap-3 border-t bg-background/95 py-3 pl-5 backdrop-blur">
- {error ? (
- <p
- role="alert"
- className="min-w-0 flex-1 break-words text-body text-destructive"
- >
- {error}
- </p>
- ) : null}
- <Button
- type="button"
- className="ml-auto shrink-0"
- onClick={onCreate}
- disabled={!canCreate}
- >
- {creating && <Loader2 className="size-4 animate-spin" />}
- {creating
- ? t(($) => $.creation_studio.creating)
- : squad
- ? t(($) => $.creation_studio.create_and_add)
- : t(($) => $.creation_studio.create_and_open)}
- </Button>
- </div>
- );
-}
-export function buildInvocationTargets(
- draft: AgentDraft,
-): AgentInvocationTargetInput[] {
- if (draft.permissionScope === "private") return [];
- if (draft.permissionScope === "workspace") {
- return [{ target_type: "workspace" }];
- }
- return [
- ...[...draft.memberIds].map((targetId) => ({
- target_type: "member" as const,
- target_id: targetId,
- })),
- ...[...draft.teamIds].map((targetId) => ({
- target_type: "team" as const,
- target_id: targetId,
- })),
- ];
-}
-
-export function deriveDuplicateAccess(
- agent: Pick<Agent, "permission_mode" | "invocation_targets">,
-): Pick<AgentDraft, "permissionScope" | "memberIds" | "teamIds"> {
- if (agent.permission_mode !== "public_to") {
- return {
- permissionScope: "private",
- memberIds: new Set(),
- teamIds: new Set(),
- };
- }
-
- const targets = agent.invocation_targets ?? [];
- if (targets.some((target) => target.target_type === "workspace")) {
- return {
- permissionScope: "workspace",
- memberIds: new Set(),
- teamIds: new Set(),
- };
- }
-
- const memberIds = targets
- .filter((target) => target.target_type === "member" && target.target_id)
- .map((target) => target.target_id as string);
- const teamIds = targets
- .filter((target) => target.target_type === "team" && target.target_id)
- .map((target) => target.target_id as string);
- if (memberIds.length === 0 && teamIds.length === 0) {
- return {
- permissionScope: "private",
- memberIds: new Set(),
- teamIds: new Set(),
- };
- }
- return {
- permissionScope: "members",
- memberIds: new Set(memberIds),
- teamIds: new Set(teamIds),
- };
-}
-
-/**
- * Seeds the studio draft from the agent being duplicated.
- *
- * `model` / `thinkingLevel` / `serviceTier` only mean something on the runtime
- * they were chosen for, so they ride along only when the copy stays on that
- * exact runtime. When the source runtime is gone, private to somebody else or
- * offline, the draft falls back to another runtime and the three are cleared
- * for the user to pick again — the same rule `multica agent copy` already
- * enforces server-side (cmd_agent_copy.go). Before MUL-5390 the fallback kept
- * the source `model` and silently persisted a cross-provider value.
- */
-export function buildDuplicateDraft(
- source: Agent,
- options: {
- runtimes: RuntimeDevice[];
- currentUserId: string | null;
- fallbackRuntimeId: string;
- nameSuffix: string;
- },
-): AgentDraft {
- const keepsRuntime =
- !!source.runtime_id &&
- options.runtimes.some(
- (runtime) =>
- runtime.id === source.runtime_id &&
- isRuntimeUsableForUser(runtime, options.currentUserId),
- );
- return {
- ...EMPTY_DRAFT,
- name: `${source.name}${options.nameSuffix}`,
- description: source.description ?? "",
- instructions: source.instructions ?? "",
- avatarUrl: source.avatar_url ?? null,
- runtimeId: keepsRuntime
- ? (source.runtime_id as string)
- : options.fallbackRuntimeId,
- model: keepsRuntime ? source.model ?? "" : "",
- thinkingLevel: keepsRuntime ? source.thinking_level ?? "" : "",
- serviceTier: keepsRuntime ? source.service_tier ?? "" : "",
- skillIds: new Set(source.skills.map((skill) => skill.id)),
- ...deriveDuplicateAccess(source),
- };
-}
-
-/**
- * Seeds the duplicate draft exactly once, and only from a runtime list that has
- * actually answered.
- *
- * The ordering matters: the agent list and the runtime list are independent
- * queries, so on a cold start (a direct `?duplicate=<id>` link, or a refresh)
- * the agent can arrive while runtimes are still pending. Seeding then would run
- * `buildDuplicateDraft` against `[]`, read the source runtime as unavailable,
- * and clear the model / thinking / speed that a same-runtime copy must keep —
- * permanently, because seeding happens once. Re-running on every runtime change
- * instead would overwrite edits the user already made, so the gate is on the
- * query being decidable rather than on the data changing.
- */
-export function useDuplicateDraftSeed({
- source,
- runtimesSettled,
- runtimes,
- currentUserId,
- fallbackRuntimeId,
- nameSuffix,
- onSeed,
-}: {
- source: Agent | null;
- /** The runtime query resolved or failed — `false` while it is pending. */
- runtimesSettled: boolean;
- runtimes: RuntimeDevice[];
- currentUserId: string | null;
- fallbackRuntimeId: string;
- nameSuffix: string;
- onSeed: (draft: AgentDraft, runtimeReset: boolean) => void;
-}): void {
- const seededRef = useRef(false);
- // The callback is recreated every render by design (it closes over setState),
- // so keep it out of the effect's dependency list.
- const onSeedRef = useRef(onSeed);
- onSeedRef.current = onSeed;
-
- useEffect(() => {
- if (seededRef.current || !source || !runtimesSettled) return;
- seededRef.current = true;
- const draft = buildDuplicateDraft(source, {
- runtimes,
- currentUserId,
- fallbackRuntimeId,
- nameSuffix,
- });
- onSeedRef.current(draft, draft.runtimeId !== source.runtime_id);
- }, [
- currentUserId,
- fallbackRuntimeId,
- nameSuffix,
- runtimes,
- runtimesSettled,
- source,
- ]);
-}
-
-/**
- * Assembles the `POST /api/agents` body. Empty execution overrides are omitted
- * rather than sent as `""` so the runtime resolves its own default, and the
- * duplicate-only fields are the runtime-independent ones (`custom_args`,
- * concurrency) — mirroring `multica agent copy`.
- */
-export function buildCreateAgentRequest(options: {
- draft: AgentDraft;
- runtimeId: string;
- /** Template attribution for the `agent_created` event, not a template create. */
- template?: string;
- duplicateSource?: Agent | null;
-}): CreateAgentRequest {
- const { draft, runtimeId, template, duplicateSource } = options;
- const request: CreateAgentRequest = {
- name: draft.name.trim(),
- description: draft.description.trim(),
- instructions: draft.instructions.trim() || undefined,
- avatar_url: draft.avatarUrl ?? undefined,
- runtime_id: runtimeId,
- model: draft.model.trim() || undefined,
- thinking_level: draft.thinkingLevel.trim() || undefined,
- service_tier: draft.serviceTier.trim() || undefined,
- permission_mode:
- draft.permissionScope === "private" ? "private" : "public_to",
- invocation_targets: buildInvocationTargets(draft),
- skill_ids: [...draft.skillIds],
- template,
- };
- if (duplicateSource) {
- if (duplicateSource.custom_args.length > 0) {
- request.custom_args = duplicateSource.custom_args;
- }
- const sourceConcurrency = duplicateSource.max_concurrent_tasks;
- if (
- Number.isInteger(sourceConcurrency) &&
- sourceConcurrency >= AGENT_MAX_CONCURRENT_TASKS_MIN &&
- sourceConcurrency <= AGENT_MAX_CONCURRENT_TASKS_MAX
- ) {
- request.max_concurrent_tasks = sourceConcurrency;
- }
- }
- return request;
-}
-export function parseBuilderDraft(content: string): BuilderDraftPayload | null {
- const match = content.match(/<agent_draft>([\s\S]*?)<\/agent_draft>/);
- if (!match?.[1]) return null;
- try {
- const value = JSON.parse(match[1]);
- return value && typeof value === "object"
- ? (value as BuilderDraftPayload)
- : null;
- } catch {
- // Some CLI-backed models emit literal newlines in the Markdown
- // instructions string even when asked for compact JSON. Repair only JSON
- // control characters that occur inside strings; object structure and all
- // other syntax still have to pass JSON.parse.
- try {
- const value = JSON.parse(escapeJsonStringControlCharacters(match[1]));
- return value && typeof value === "object"
- ? (value as BuilderDraftPayload)
- : null;
- } catch {
- return null;
- }
- }
-}
-
-function escapeJsonStringControlCharacters(value: string): string {
- let result = "";
- let inString = false;
- let escaped = false;
-
- for (const character of value) {
- if (!inString) {
- result += character;
- if (character === '"') inString = true;
- continue;
- }
- if (escaped) {
- result += character;
- escaped = false;
- continue;
- }
- if (character === "\\") {
- result += character;
- escaped = true;
- continue;
- }
- if (character === '"') {
- result += character;
- inString = false;
- continue;
- }
- if (character === "\n") {
- result += "\\n";
- } else if (character === "\r") {
- result += "\\r";
- } else if (character === "\t") {
- result += "\\t";
- } else {
- result += character;
- }
- }
-
- return result;
-}
-
-export function stripBuilderDraft(content: string): string {
- return content.replace(/<agent_draft>[\s\S]*?<\/agent_draft>/g, "").trim();
-}
-
-export function encodeBuilderInput(
- request: string,
- draft: AgentDraft,
- skills: Array<{ id: string; name: string; description: string }>,
- members: Array<{ user_id: string; name: string }>,
- runtime: Pick<RuntimeDevice, "id" | "name" | "provider"> | null,
- models: RuntimeModel[] | null,
-): string {
- return (
- BUILDER_INPUT_PREFIX +
- JSON.stringify(
- {
- user_request: request,
- current_draft: {
- name: draft.name,
- description: draft.description,
- instructions: draft.instructions,
- model: draft.model,
- skill_ids: [...draft.skillIds],
- permission_scope: draft.permissionScope,
- member_ids: [...draft.memberIds],
- },
- selected_runtime: runtime
- ? {
- id: runtime.id,
- name: runtime.name,
- provider: runtime.provider,
- }
- : null,
- available_runtime_models:
- models === null
- ? null
- : models.map((model) => ({
- id: model.id,
- label: model.label,
- provider: model.provider,
- })),
- available_workspace_skills: skills.map((skill) => ({
- id: skill.id,
- name: skill.name,
- description: skill.description,
- })),
- available_workspace_members: members.map((member) => ({
- id: member.user_id,
- name: member.name,
- })),
- },
- null,
- 2,
- )
- );
-}
-
-export function decodeBuilderInput(content: string): string {
- if (!content.startsWith(BUILDER_INPUT_PREFIX)) return content;
- try {
- const parsed = JSON.parse(content.slice(BUILDER_INPUT_PREFIX.length)) as {
- user_request?: unknown;
- };
- return typeof parsed.user_request === "string"
- ? parsed.user_request
- : content;
- } catch {
- return content;
- }
-}
-
-export interface BuilderRestore {
- id: string;
- content: string;
-}
-
-/**
- * Chooses which cancelled prompt the builder composer should adopt (#5219).
- *
- * Two sources, never both: cancelling a task the daemon never started answers
- * synchronously (`cancelled_chat_message.restore_to_input`), while cancelling a
- * started-but-empty one defers the judgment and delivers the prompt later as a
- * durable chat_draft_restore row. The durable copy is the raw chat_message
- * content, i.e. still in the builder's encoded wire form, so it is decoded here
- * exactly as the synchronous path decodes its own.
- *
- * The session id is deliberately not carried over: the builder composer keys its
- * draft by `agent-builder:<id>`, so ChatInput's session guard would never match
- * a raw session id — and it does not need to, since this composer only ever
- * shows the builder session.
- */
-export function pickBuilderRestore(
- synchronous: BuilderRestore | null,
- durable: { id: string; content: string } | null,
-): BuilderRestore | null {
- if (synchronous) return synchronous;
- if (!durable) return null;
- return { id: durable.id, content: decodeBuilderInput(durable.content) };
-}
-
-export function mergeBuilderDraft(
- current: AgentDraft,
- payload: BuilderDraftPayload,
- validSkillIds: Set<string>,
- validMemberIds: Set<string>,
- validModelIds: ReadonlySet<string> | null,
-): AgentDraft {
- const scope =
- payload.permission_scope === "workspace" ||
- payload.permission_scope === "members" ||
- payload.permission_scope === "private"
- ? payload.permission_scope
- : current.permissionScope;
- const skillIds = Array.isArray(payload.skill_ids)
- ? payload.skill_ids.filter(
- (id): id is string =>
- typeof id === "string" && validSkillIds.has(id),
- )
- : [...current.skillIds];
- const memberIds = Array.isArray(payload.member_ids)
- ? payload.member_ids.filter(
- (id): id is string =>
- typeof id === "string" && validMemberIds.has(id),
- )
- : [...current.memberIds];
- // The current value may be a deliberate custom entry from ModelDropdown,
- // so preserving it is always safe. Only catalog IDs may be introduced by
- // the builder; failed discovery therefore cannot turn into fail-open input.
- const model =
- typeof payload.model === "string" &&
- (payload.model === current.model ||
- (validModelIds !== null &&
- validModelIds.size > 0 &&
- (payload.model === "" || validModelIds.has(payload.model))))
- ? payload.model
- : current.model;
-
- return {
- ...current,
- name: typeof payload.name === "string" ? payload.name : current.name,
- description:
- typeof payload.description === "string"
- ? payload.description
- : current.description,
- instructions:
- typeof payload.instructions === "string"
- ? payload.instructions
- : current.instructions,
- model,
- // The builder can move the model, which invalidates whatever thinking /
- // speed the user picked for the previous one. It never sets these two
- // itself, so an unchanged model simply preserves them.
- thinkingLevel: model === current.model ? current.thinkingLevel : "",
- serviceTier: model === current.model ? current.serviceTier : "",
- skillIds: new Set(skillIds),
- permissionScope: scope,
- memberIds: new Set(scope === "members" ? memberIds : []),
- teamIds: current.teamIds,
- };
-}
diff --git a/packages/views/agents/components/agents-page.test.tsx b/packages/views/agents/components/agents-page.test.tsx
index 99d93515c3..1481207f70 100644
--- a/packages/views/agents/components/agents-page.test.tsx
+++ b/packages/views/agents/components/agents-page.test.tsx
@@ -127,6 +127,7 @@ vi.mock("@multica/core/hooks", () => ({
vi.mock("@multica/core/paths", () => ({
useWorkspacePaths: () => ({
newAgent: () => "/test-workspace/agents/new",
+ newAgentManual: () => "/test-workspace/agents/new/manual",
agentDetail: (id: string) => `/test-workspace/agents/${id}`,
}),
}));
diff --git a/packages/views/agents/components/agents-page.tsx b/packages/views/agents/components/agents-page.tsx
index 1cf129509d..d203f5915d 100644
--- a/packages/views/agents/components/agents-page.tsx
+++ b/packages/views/agents/components/agents-page.tsx
@@ -969,8 +969,12 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
overscan: 10,
});
+ // Straight to the manual form: a duplicate already has every field decided,
+ // so the method chooser would be a step with nothing to choose.
const handleDuplicate = useCallback((agent: Agent) => {
- navigation.push(`${paths.newAgent()}?duplicate=${encodeURIComponent(agent.id)}`);
+ navigation.push(
+ `${paths.newAgentManual()}?duplicate=${encodeURIComponent(agent.id)}`,
+ );
}, [navigation, paths]);
const selectedRows = rows.filter((row) => selectedIds.has(row.agent.id));
diff --git a/packages/views/agents/components/create-agent-dialog.tsx b/packages/views/agents/components/create-agent-dialog.tsx
index 160789bedd..a146c99474 100644
--- a/packages/views/agents/components/create-agent-dialog.tsx
+++ b/packages/views/agents/components/create-agent-dialog.tsx
@@ -4,7 +4,8 @@ import { useState } from "react";
import { Globe, Lock, Users } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { ModelDropdown } from "./model-dropdown";
-import { RuntimePicker, isRuntimeUsableForUser } from "./runtime-picker";
+import { RuntimePicker } from "./runtime-picker";
+import { isRuntimeUsableForUser } from "@multica/core/runtimes";
import { InstructionsEditor } from "./instructions-editor";
import { SkillMultiSelect } from "./skill-multi-select";
import { AvatarUploadControl } from "../../common/avatar-upload-control";
diff --git a/packages/views/agents/components/index.ts b/packages/views/agents/components/index.ts
index f0b04c9a55..c459fd7799 100644
--- a/packages/views/agents/components/index.ts
+++ b/packages/views/agents/components/index.ts
@@ -1,3 +1,2 @@
export { AgentsPage } from "./agents-page";
export { AgentDetailPage } from "./agent-detail-page";
-export { AgentCreationStudio } from "./agent-creation-studio";
diff --git a/packages/views/agents/components/runtime-picker.tsx b/packages/views/agents/components/runtime-picker.tsx
index b11df09e0e..352032b0c4 100644
--- a/packages/views/agents/components/runtime-picker.tsx
+++ b/packages/views/agents/components/runtime-picker.tsx
@@ -4,7 +4,10 @@ import { useEffect, useMemo, useState } from "react";
import { ChevronDown, Cloud, Loader2, Lock, Search } from "lucide-react";
import { ProviderLogo } from "../../runtimes/components/provider-logo";
import { ActorAvatar } from "../../common/actor-avatar";
-import { runtimeDisplayName } from "@multica/core/runtimes";
+import {
+ isRuntimeUsableForUser,
+ runtimeDisplayName,
+} from "@multica/core/runtimes";
import type { MemberWithUser, RuntimeDevice } from "@multica/core/types";
import {
Popover,
@@ -320,17 +323,6 @@ export function RuntimePicker({
);
}
-// Visibility gate exposed so the parent can defend Create against a locked
-// selection (e.g. duplicate of an agent whose runtime is now private).
-export function isRuntimeUsableForUser(
- r: RuntimeDevice,
- currentUserId: string | null,
-): boolean {
- if (!currentUserId) return true;
- if (r.owner_id === currentUserId) return true;
- return r.visibility === "public";
-}
-
function computeFilteredRuntimes(
runtimes: RuntimeDevice[],
filter: RuntimeFilter,
diff --git a/packages/views/agents/create/agent-configuration-panel.tsx b/packages/views/agents/create/agent-configuration-panel.tsx
new file mode 100644
index 0000000000..4f41a5f216
--- /dev/null
+++ b/packages/views/agents/create/agent-configuration-panel.tsx
@@ -0,0 +1,449 @@
+"use client";
+
+import { useEffect, useRef, type ReactNode } from "react";
+import {
+ AGENT_DESCRIPTION_MAX_LENGTH,
+ applyDraftModelChange,
+ applyDraftRuntimeChange,
+ type AgentDraft,
+ type AgentPermissionScope,
+} from "@multica/core/agents";
+import type { MemberWithUser, RuntimeDevice } from "@multica/core/types";
+import { Checkbox } from "@multica/ui/components/ui/checkbox";
+import { Input } from "@multica/ui/components/ui/input";
+import { Textarea } from "@multica/ui/components/ui/textarea";
+import { cn } from "@multica/ui/lib/utils";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { AvatarUploadControl } from "../../common/avatar-upload-control";
+import { useT } from "../../i18n";
+import {
+ SettingsCard,
+ SettingsSection,
+} from "../../settings/components/settings-layout";
+import { CharCounter } from "../components/char-counter";
+import { ServiceTierSettingField } from "../components/inspector/service-tier-setting-field";
+import { ThinkingSettingField } from "../components/inspector/thinking-prop-row";
+import { ModelDropdown } from "../components/model-dropdown";
+import { RuntimePicker } from "../components/runtime-picker";
+import { SkillMultiSelect } from "../components/skill-multi-select";
+
+const PERMISSION_SCOPES: AgentPermissionScope[] = [
+ "private",
+ "workspace",
+ "members",
+];
+
+export function AgentConfigurationPanel({
+ draft,
+ onChange,
+ runtimes,
+ runtimesLoading,
+ members,
+ currentUserId,
+ nameError,
+ onNameChange,
+ compact = false,
+ onRuntimeSelect,
+ runtimeSwitchPending = false,
+ runtimeSwitchInFlight = false,
+}: {
+ draft: AgentDraft;
+ onChange: (draft: AgentDraft) => void;
+ runtimes: RuntimeDevice[];
+ runtimesLoading: boolean;
+ members: MemberWithUser[];
+ currentUserId: string | null;
+ nameError: string | null;
+ onNameChange: (name: string) => void;
+ 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 — and the per-model thinking / speed
+ // overrides — on runtime change so the new runtime resolves its own
+ // defaults instead of stale values.
+ onChange(applyDraftRuntimeChange(draft, id));
+ };
+
+ return (
+ <div className={cn("space-y-8", compact && "space-y-6")}>
+ <SettingsSection
+ title={t(($) => $.creation_studio.sections.identity)}
+ description={t(($) => $.creation_studio.sections.identity_hint)}
+ >
+ <SettingsCard>
+ <DraftFieldRow
+ compact={compact}
+ label={t(($) => $.create_dialog.avatar.change_aria)}
+ >
+ <div className={cn(!compact && "sm:flex sm:justify-end")}>
+ <AvatarUploadControl
+ variant="agent"
+ value={draft.avatarUrl}
+ name={draft.name}
+ size={compact ? 52 : 56}
+ onUploaded={(url) => set("avatarUrl", url)}
+ onEmojiSelected={(value) => set("avatarUrl", value)}
+ onClear={() => set("avatarUrl", null)}
+ />
+ </div>
+ </DraftFieldRow>
+ <AgentNameField
+ compact={compact}
+ name={draft.name}
+ error={nameError}
+ onChange={onNameChange}
+ />
+ <DraftFieldRow
+ compact={compact}
+ align="start"
+ label={t(($) => $.create_dialog.description_label)}
+ htmlFor="agent-create-description"
+ >
+ <div>
+ <Textarea
+ id="agent-create-description"
+ name="agent-description"
+ autoComplete="off"
+ aria-label={t(($) => $.create_dialog.description_label)}
+ value={draft.description}
+ onChange={(event) => set("description", event.target.value)}
+ placeholder={t(($) => $.create_dialog.description_placeholder)}
+ rows={compact ? 3 : 4}
+ // The create API rejects >255 characters with a 400. Cap the
+ // input and show the counter so the limit is visible before
+ // submitting, matching the settings page.
+ maxLength={AGENT_DESCRIPTION_MAX_LENGTH}
+ className="resize-y"
+ />
+ <CharCounter
+ length={[...draft.description].length}
+ max={AGENT_DESCRIPTION_MAX_LENGTH}
+ />
+ </div>
+ </DraftFieldRow>
+ </SettingsCard>
+ </SettingsSection>
+
+ <SettingsSection
+ title={t(($) => $.creation_studio.sections.behavior)}
+ description={t(($) => $.creation_studio.sections.behavior_hint)}
+ >
+ <SettingsCard>
+ <DraftFieldRow
+ compact
+ label={t(($) => $.create_dialog.instructions.label)}
+ htmlFor="agent-create-instructions"
+ >
+ <Textarea
+ id="agent-create-instructions"
+ name="agent-instructions"
+ autoComplete="off"
+ aria-label={t(($) => $.create_dialog.instructions.label)}
+ value={draft.instructions}
+ onChange={(event) => set("instructions", event.target.value)}
+ placeholder={t(
+ ($) => $.create_dialog.instructions.editor_placeholder,
+ )}
+ rows={compact ? 9 : 12}
+ className="min-h-44 resize-y font-mono text-label leading-6"
+ />
+ </DraftFieldRow>
+ <div className="px-4 py-4">
+ <SkillMultiSelect
+ selectedIds={draft.skillIds}
+ onChange={(ids) => set("skillIds", ids)}
+ />
+ </div>
+ </SettingsCard>
+ </SettingsSection>
+
+ <SettingsSection
+ title={t(($) => $.creation_studio.sections.execution)}
+ description={t(($) => $.creation_studio.sections.execution_hint)}
+ >
+ <SettingsCard>
+ <div
+ className={cn("grid gap-4 px-4 py-4", !compact && "sm:grid-cols-2")}
+ >
+ <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-caption 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) => onChange(applyDraftModelChange(draft, value))}
+ // A successful switch clears the model, so an edit made while the
+ // rebind is in flight would be silently discarded.
+ disabled={!selectedRuntime || runtimeSwitchInFlight}
+ />
+ </div>
+ {/* Both fields fail closed: they render only when the exact selected
+ model's live catalog advertises the capability (or a value is
+ already set and needs clearing), so an offline runtime, a failed
+ discovery or an empty model shows nothing instead of an input
+ that cannot be honoured. */}
+ <AgentExecutionOverrides
+ draft={draft}
+ runtime={selectedRuntime}
+ disabled={runtimeLocked}
+ onChange={onChange}
+ />
+ </SettingsCard>
+ </SettingsSection>
+
+ <SettingsSection
+ title={t(($) => $.creation_studio.sections.access)}
+ description={t(($) => $.creation_studio.sections.access_hint)}
+ >
+ <SettingsCard>
+ <div
+ className="space-y-1 p-2"
+ role="radiogroup"
+ aria-label={t(($) => $.creation_studio.sections.access)}
+ >
+ {PERMISSION_SCOPES.map((scope) => (
+ <button
+ key={scope}
+ type="button"
+ role="radio"
+ aria-checked={draft.permissionScope === scope}
+ onClick={() => set("permissionScope", scope)}
+ className={cn(
+ "flex w-full items-start gap-3 rounded-md px-3 py-2.5 text-left transition-colors",
+ "hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ draft.permissionScope === scope && "bg-muted",
+ )}
+ >
+ <span
+ className={cn(
+ "mt-1 flex size-3.5 shrink-0 items-center justify-center rounded-full border",
+ draft.permissionScope === scope && "border-primary",
+ )}
+ aria-hidden="true"
+ >
+ {draft.permissionScope === scope ? (
+ <span className="size-1.5 rounded-full bg-primary" />
+ ) : null}
+ </span>
+ <span className="min-w-0">
+ <span className="block text-body font-medium">
+ {t(($) => $.creation_studio.access[scope].title)}
+ </span>
+ <span className="mt-0.5 block text-caption leading-5 text-muted-foreground">
+ {t(($) => $.creation_studio.access[scope].description)}
+ </span>
+ </span>
+ </button>
+ ))}
+ </div>
+ {draft.permissionScope === "members" ? (
+ <div className="max-h-48 overflow-y-auto p-2">
+ {otherMembers.map((member) => {
+ const checked = draft.memberIds.has(member.user_id);
+ return (
+ <label
+ key={member.user_id}
+ className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-2 hover:bg-muted"
+ >
+ <Checkbox
+ checked={checked}
+ onCheckedChange={(value) => {
+ const next = new Set(draft.memberIds);
+ if (value === true) next.add(member.user_id);
+ else next.delete(member.user_id);
+ set("memberIds", next);
+ }}
+ />
+ <ActorAvatar
+ actorType="member"
+ actorId={member.user_id}
+ size="sm"
+ />
+ <span className="min-w-0 flex-1 truncate text-body">
+ {member.name}
+ </span>
+ </label>
+ );
+ })}
+ {draft.memberIds.size === 0 ? (
+ <p className="px-2 py-1 text-caption text-destructive">
+ {t(($) => $.creation_studio.access.members.required)}
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+ </SettingsCard>
+ </SettingsSection>
+ </div>
+ );
+}
+
+export function AgentNameField({
+ name,
+ error,
+ onChange,
+ compact = false,
+}: {
+ name: string;
+ error: string | null;
+ onChange: (name: string) => void;
+ compact?: boolean;
+}) {
+ const { t } = useT("agents");
+ const errorId = "agent-create-name-error";
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ if (!error) return;
+ inputRef.current?.focus();
+ inputRef.current?.select();
+ }, [error]);
+
+ return (
+ <DraftFieldRow
+ compact={compact}
+ label={t(($) => $.create_dialog.name_label)}
+ htmlFor="agent-create-name"
+ >
+ <div className="space-y-1.5">
+ <Input
+ ref={inputRef}
+ id="agent-create-name"
+ name="agent-name"
+ autoComplete="off"
+ aria-label={t(($) => $.create_dialog.name_label)}
+ aria-invalid={!!error}
+ aria-describedby={error ? errorId : undefined}
+ value={name}
+ onChange={(event) => onChange(event.target.value)}
+ placeholder={t(($) => $.create_dialog.name_placeholder)}
+ />
+ {error ? (
+ <p id={errorId} className="text-caption text-destructive">
+ {error}
+ </p>
+ ) : null}
+ </div>
+ </DraftFieldRow>
+ );
+}
+
+/**
+ * Per-model execution overrides (thinking level + Codex speed) for the create
+ * flow. Capability comes from the exact selected model's live catalog on the
+ * selected runtime, so nothing renders while that cannot be resolved — an
+ * offline runtime, failed discovery, or an empty "use the runtime default"
+ * model. That is the same fail-closed rule the settings page follows, and it is
+ * why no value can be sent that the daemon would refuse to honour.
+ */
+export function AgentExecutionOverrides({
+ draft,
+ runtime,
+ disabled = false,
+ onChange,
+}: {
+ draft: AgentDraft;
+ runtime: RuntimeDevice | null;
+ disabled?: boolean;
+ onChange: (draft: AgentDraft) => void;
+}) {
+ const { t } = useT("agents");
+ const runtimeOnline = runtime?.status === "online";
+ return (
+ <>
+ <ThinkingSettingField
+ label={t(($) => $.creation_studio.thinking_label)}
+ runtimeId={runtime?.id ?? null}
+ runtimeOnline={runtimeOnline}
+ provider={runtime?.provider ?? ""}
+ model={draft.model}
+ value={draft.thinkingLevel}
+ canEdit={!disabled}
+ onChange={(thinkingLevel) => onChange({ ...draft, thinkingLevel })}
+ />
+ <ServiceTierSettingField
+ label={t(($) => $.creation_studio.speed_label)}
+ runtimeId={runtime?.id ?? null}
+ runtimeOnline={runtimeOnline}
+ model={draft.model}
+ value={draft.serviceTier}
+ canEdit={!disabled}
+ onChange={(serviceTier) => onChange({ ...draft, serviceTier })}
+ />
+ </>
+ );
+}
+
+function DraftFieldRow({
+ label,
+ children,
+ compact = false,
+ align = "center",
+ htmlFor,
+}: {
+ label: string;
+ children: ReactNode;
+ compact?: boolean;
+ align?: "center" | "start";
+ htmlFor?: string;
+}) {
+ return (
+ <div
+ className={cn(
+ "gap-3 px-4 py-4",
+ compact
+ ? "flex flex-col"
+ : "grid sm:grid-cols-[minmax(0,1fr)_minmax(280px,1.2fr)] sm:gap-8",
+ !compact && (align === "center" ? "sm:items-center" : "sm:items-start"),
+ )}
+ >
+ {htmlFor ? (
+ <label htmlFor={htmlFor} className="text-body font-medium">
+ {label}
+ </label>
+ ) : (
+ <div className="text-body font-medium">{label}</div>
+ )}
+ <div className="min-w-0">{children}</div>
+ </div>
+ );
+}
diff --git a/packages/views/agents/components/agent-creation-studio.execution.test.tsx b/packages/views/agents/create/agent-execution-overrides.test.tsx
similarity index 97%
rename from packages/views/agents/components/agent-creation-studio.execution.test.tsx
rename to packages/views/agents/create/agent-execution-overrides.test.tsx
index 9cd7462915..de4467946a 100644
--- a/packages/views/agents/components/agent-creation-studio.execution.test.tsx
+++ b/packages/views/agents/create/agent-execution-overrides.test.tsx
@@ -31,10 +31,8 @@ vi.mock("@multica/core/api", () => ({
ApiError: class ApiError extends Error {},
}));
-import {
- AgentExecutionOverrides,
- type AgentDraft,
-} from "./agent-creation-studio";
+import type { AgentDraft } from "@multica/core/agents";
+import { AgentExecutionOverrides } from "./agent-configuration-panel";
const FAST_MODEL: RuntimeModel = {
id: "gpt-5.6-sol",
diff --git a/packages/views/agents/create/ai-create-agent-page.tsx b/packages/views/agents/create/ai-create-agent-page.tsx
new file mode 100644
index 0000000000..d21a9e07af
--- /dev/null
+++ b/packages/views/agents/create/ai-create-agent-page.tsx
@@ -0,0 +1,129 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { agentBuilderSessionListOptions } from "@multica/core/agents";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { runtimeDisplayLabel } from "@multica/core/runtimes";
+import type { RuntimeDevice } from "@multica/core/types";
+import { useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+import { BuilderSetupPanel } from "./builder-setup-panel";
+import { BuilderWorkspace } from "./builder-workspace";
+import { AgentCreateChip, AgentCreateShell } from "./create-shell";
+import { createPathWithParams } from "./squad-param";
+
+/**
+ * Conversational agent creation.
+ *
+ * The route holds the conversation list and the identity of the open one; each
+ * conversation's own state lives in {@link BuilderWorkspace}, mounted under a
+ * `key` so switching is a remount rather than a reset every future field would
+ * have to remember to join.
+ *
+ * `?session=` is what makes a conversation addressable — a refresh, a
+ * back/forward, and a reopened tab all land back in the same chat instead of
+ * silently starting a new one.
+ */
+export function AiCreateAgentPage() {
+ const { t } = useT("agents");
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const squadId = navigation.searchParams.get("squad");
+ const sessionId = navigation.searchParams.get("session") ?? "";
+
+ const builderSessions = useQuery(agentBuilderSessionListOptions(wsId));
+ const sessions = builderSessions.data ?? [];
+ const sessionSettled = builderSessions.isSuccess || builderSessions.isError;
+ const openSession = sessions.find(
+ (session) => session.session_id === sessionId,
+ );
+
+ // The chip has to say something before the list answers, and only the open
+ // pane knows which runtime it settled on.
+ const [runtimeLabel, setRuntimeLabel] = useState<string | null>(null);
+ // The runtime a just-started conversation was created with. It cannot be read
+ // back yet — a conversation joins the list only once it has a message — and
+ // without it the first turn would render against the first runtime in the
+ // list instead of the one the user picked.
+ const [startedRuntimeId, setStartedRuntimeId] = useState("");
+
+ const handleSetupRuntimeLabel = useCallback(
+ (runtime: RuntimeDevice | null) =>
+ setRuntimeLabel(runtime ? runtimeDisplayLabel(runtime) : null),
+ [],
+ );
+
+ const open = useCallback(
+ (nextSessionId: string) =>
+ navigation.replace(
+ createPathWithParams(paths.newAgentAi(), {
+ squad: squadId,
+ session: nextSessionId,
+ }),
+ ),
+ [navigation, paths, squadId],
+ );
+
+ const closeSession = useCallback(
+ () =>
+ navigation.replace(
+ createPathWithParams(paths.newAgentAi(), { squad: squadId }),
+ ),
+ [navigation, paths, squadId],
+ );
+
+ return (
+ <AgentCreateShell
+ title={
+ squadId
+ ? t(($) => $.creation_studio.squad_title)
+ : t(($) => $.creation_studio.title)
+ }
+ step={t(($) => $.creation_studio.step_ai)}
+ onBack={() => navigation.push(paths.newAgent())}
+ chips={
+ <>
+ <AgentCreateChip>
+ {t(($) => $.creation_studio.modes.ai.title)}
+ </AgentCreateChip>
+ {runtimeLabel ? (
+ <AgentCreateChip>{runtimeLabel}</AgentCreateChip>
+ ) : null}
+ </>
+ }
+ >
+ {sessionId ? (
+ <BuilderWorkspace
+ // Switching conversations remounts everything below: the draft, the
+ // applied-message marker and the composer all belong to one
+ // conversation, and a remount is the only reset that cannot forget a
+ // field.
+ key={sessionId}
+ sessionId={sessionId}
+ squadId={squadId}
+ session={openSession}
+ sessionSettled={sessionSettled}
+ fallbackRuntimeId={startedRuntimeId}
+ onDiscarded={closeSession}
+ onRuntimeLabel={setRuntimeLabel}
+ />
+ ) : (
+ <BuilderSetupPanel
+ sessions={sessions}
+ onResume={(nextSessionId) => {
+ setStartedRuntimeId("");
+ open(nextSessionId);
+ }}
+ onStarted={(nextSessionId, runtimeId) => {
+ setStartedRuntimeId(runtimeId);
+ open(nextSessionId);
+ }}
+ onRuntimeLabel={handleSetupRuntimeLabel}
+ />
+ )}
+ </AgentCreateShell>
+ );
+}
diff --git a/packages/views/agents/create/builder-conversation.tsx b/packages/views/agents/create/builder-conversation.tsx
new file mode 100644
index 0000000000..49b46921a5
--- /dev/null
+++ b/packages/views/agents/create/builder-conversation.tsx
@@ -0,0 +1,250 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { Loader2, MessageSquare } from "lucide-react";
+import {
+ applyDraftModelChange,
+ applyDraftRuntimeChange,
+ stripBuilderDraft,
+ type AgentDraft,
+ type BuilderRestore,
+} from "@multica/core/agents";
+import { isRuntimeUsableForUser } from "@multica/core/runtimes";
+import type {
+ ChatMessage,
+ MemberWithUser,
+ RuntimeDevice,
+} from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
+import { ChatInput } from "../../chat/components/chat-input";
+import {
+ ChatMessageList,
+ ChatMessageSkeleton,
+} from "../../chat/components/chat-message-list";
+import { useT } from "../../i18n";
+import { ModelDropdown } from "../components/model-dropdown";
+import { RuntimePicker } from "../components/runtime-picker";
+
+/**
+ * Pre-conversation card: the builder runs on a real runtime, so the runtime and
+ * model have to be chosen before the first message — they are frozen onto the
+ * hidden carrier agent when the session is created.
+ */
+export function BuilderSetup({
+ draft,
+ onChange,
+ runtimes,
+ runtimesLoading,
+ members,
+ currentUserId,
+ selectedRuntime,
+ starting,
+ error,
+ onStart,
+ onConnectRuntime,
+ banner,
+}: {
+ draft: AgentDraft;
+ onChange: (draft: AgentDraft) => void;
+ runtimes: RuntimeDevice[];
+ runtimesLoading: boolean;
+ members: MemberWithUser[];
+ currentUserId: string | null;
+ selectedRuntime: RuntimeDevice | null;
+ starting: boolean;
+ error: string | null;
+ onStart: () => void;
+ onConnectRuntime: () => void;
+ /** Rendered above the card: the way back to an unfinished conversation, so
+ * this screen cannot silently start yet another one. */
+ banner?: ReactNode;
+}) {
+ const { t } = useT("agents");
+ const hasOnline = runtimes.some(
+ (runtime) =>
+ runtime.status === "online" &&
+ isRuntimeUsableForUser(runtime, currentUserId),
+ );
+ return (
+ <main className="flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-5 py-10">
+ <div className="w-full max-w-xl">
+ {banner}
+ <div className="rounded-xl border bg-card p-6 shadow-sm">
+ <span className="flex size-11 items-center justify-center rounded-lg bg-primary/10 text-primary">
+ <MessageSquare className="size-5" />
+ </span>
+ <h2 className="mt-5 text-title-lg font-semibold">
+ {t(($) => $.creation_studio.builder.setup_title)}
+ </h2>
+ <p className="mt-2 text-body leading-6 text-muted-foreground">
+ {t(($) => $.creation_studio.builder.setup_description)}
+ </p>
+ <div className="mt-6 space-y-4">
+ <RuntimePicker
+ runtimes={runtimes}
+ runtimesLoading={runtimesLoading}
+ members={members}
+ currentUserId={currentUserId}
+ selectedRuntimeId={draft.runtimeId}
+ onSelect={(runtimeId) => {
+ if (runtimeId !== draft.runtimeId) {
+ onChange(applyDraftRuntimeChange(draft, runtimeId));
+ }
+ }}
+ />
+ <ModelDropdown
+ runtimeId={selectedRuntime?.id ?? null}
+ runtimeOnline={selectedRuntime?.status === "online"}
+ value={draft.model}
+ onChange={(model) => onChange(applyDraftModelChange(draft, model))}
+ disabled={!selectedRuntime}
+ />
+ </div>
+ {error && (
+ <div role="alert" className="mt-4 text-body text-destructive">
+ {error}
+ </div>
+ )}
+ <div className="mt-6 flex justify-end">
+ {hasOnline ? (
+ <Button
+ onClick={onStart}
+ disabled={starting || selectedRuntime?.status !== "online"}
+ >
+ {starting && <Loader2 className="size-4 animate-spin" />}
+ {t(($) => $.creation_studio.builder.start)}
+ </Button>
+ ) : (
+ <Button onClick={onConnectRuntime}>
+ {t(($) => $.creation_studio.builder.connect_runtime)}
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ </main>
+ );
+}
+
+export function BuilderConversation({
+ sessionId,
+ messages,
+ loading,
+ pendingTask,
+ runtimeOnline,
+ onSend,
+ onStop,
+ restoreDraftRequest,
+ onRestoreDraftApplied,
+ error,
+}: {
+ sessionId: string;
+ messages: ChatMessage[];
+ loading: boolean;
+ pendingTask:
+ | { task_id?: string; status?: string; created_at?: string }
+ | undefined;
+ runtimeOnline: boolean;
+ onSend: (content: string) => Promise<boolean>;
+ onStop: () => void;
+ restoreDraftRequest: BuilderRestore | null;
+ onRestoreDraftApplied: () => void;
+ error: string | null;
+}) {
+ const { t } = useT("agents");
+ const pending = !!pendingTask?.task_id;
+ const draftKey = `agent-builder:${sessionId}`;
+ const prompts = [
+ t(($) => $.creation_studio.builder.prompt_review),
+ t(($) => $.creation_studio.builder.prompt_research),
+ t(($) => $.creation_studio.builder.prompt_assistant),
+ ];
+
+ return (
+ // `@container`: this is one column of the studio's split layout, so the
+ // shared chat gutter must size against the column, not the viewport.
+ <section className="flex h-full min-h-0 flex-col bg-background @container">
+ <header className="flex min-h-14 shrink-0 items-center justify-between gap-4 border-b px-5 py-2.5">
+ <div className="min-w-0">
+ <h2 className="truncate text-body font-semibold">
+ {t(($) => $.creation_studio.builder.chat_title)}
+ </h2>
+ <p className="truncate text-caption text-muted-foreground">
+ {t(($) => $.creation_studio.builder.chat_hint)}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-1.5 text-caption text-muted-foreground">
+ <span
+ className={cn(
+ "size-2 rounded-full",
+ runtimeOnline ? "bg-success" : "bg-muted-foreground/40",
+ )}
+ aria-hidden="true"
+ />
+ {runtimeOnline
+ ? t(($) => $.creation_studio.builder.runtime_online)
+ : t(($) => $.creation_studio.builder.runtime_offline)}
+ </div>
+ </header>
+
+ {loading ? (
+ <ChatMessageSkeleton />
+ ) : messages.length > 0 || pending ? (
+ <ChatMessageList
+ messages={messages}
+ pendingTask={pendingTask}
+ availability={runtimeOnline ? "online" : "offline"}
+ // Applies to the live stream as well as history, which is what keeps
+ // the half-written JSON block off the screen mid-reply.
+ transformContent={stripBuilderDraft}
+ />
+ ) : (
+ <div className="flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-5 py-8">
+ <div className="w-full max-w-xl text-center">
+ <h3 className="text-balance text-title font-semibold">
+ {t(($) => $.creation_studio.builder.empty_title)}
+ </h3>
+ <p className="mx-auto mt-2 max-w-md text-pretty text-body leading-6 text-muted-foreground">
+ {t(($) => $.creation_studio.builder.empty_description)}
+ </p>
+ <div className="mt-5 flex flex-wrap justify-center gap-2">
+ {prompts.map((prompt) => (
+ <button
+ key={prompt}
+ type="button"
+ onClick={() => void onSend(prompt)}
+ className="rounded-full border bg-background px-3 py-1.5 text-caption transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {prompt}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {error ? (
+ <div
+ role="alert"
+ aria-live="polite"
+ className="mx-5 mb-3 rounded-md bg-destructive/5 px-3 py-2 text-body text-destructive"
+ >
+ {error}
+ </div>
+ ) : null}
+
+ <ChatInput
+ onSend={(content) => onSend(content)}
+ onStop={onStop}
+ isRunning={pending}
+ disabled={!runtimeOnline}
+ agentName={t(($) => $.creation_studio.builder.chat_title)}
+ draftKeyOverride={draftKey}
+ editorKeyOverride={draftKey}
+ restoreDraftRequest={restoreDraftRequest}
+ onRestoreDraftApplied={onRestoreDraftApplied}
+ />
+ </section>
+ );
+}
diff --git a/packages/views/agents/create/builder-setup-panel.tsx b/packages/views/agents/create/builder-setup-panel.tsx
new file mode 100644
index 0000000000..b7cb70ea77
--- /dev/null
+++ b/packages/views/agents/create/builder-setup-panel.tsx
@@ -0,0 +1,77 @@
+"use client";
+
+import { useEffect } from "react";
+import { useWorkspacePaths } from "@multica/core/paths";
+import type {
+ AgentBuilderSessionSummary,
+ RuntimeDevice,
+} from "@multica/core/types";
+import { useNavigation } from "../../navigation";
+import { BuilderSetup } from "./builder-conversation";
+import { UnfinishedDraftsBanner } from "./unfinished-drafts";
+import { useBuilderSession } from "./use-builder-session";
+import { useCreateAgentForm } from "./use-create-agent-form";
+
+/**
+ * The step before a conversation exists: choose where it will run.
+ *
+ * The runtime cannot be deferred — it is frozen onto the hidden carrier agent
+ * when the session is created, and it becomes the new agent's default runtime.
+ * This pane owns a throwaway form for exactly those two fields; the real draft
+ * belongs to the conversation and is created with it.
+ */
+export function BuilderSetupPanel({
+ sessions,
+ onResume,
+ onStarted,
+ onRuntimeLabel,
+}: {
+ /** Unfinished conversations, so this screen is not a dead end when some
+ * exist: the picker is the only way back to them from here. */
+ sessions: AgentBuilderSessionSummary[];
+ onResume: (sessionId: string) => void;
+ /** Hands the new conversation's id and runtime back so the route can open it. */
+ onStarted: (sessionId: string, runtimeId: string) => void;
+ onRuntimeLabel: (runtime: RuntimeDevice | null) => void;
+}) {
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const form = useCreateAgentForm();
+ const { draft, setDraft, selectedRuntime } = form;
+
+ const builder = useBuilderSession({
+ sessionId: "",
+ // Nothing is sent from this screen; the encoder is only reachable once a
+ // conversation exists.
+ encodeInput: (text) => text,
+ });
+
+ useEffect(() => {
+ onRuntimeLabel(selectedRuntime);
+ }, [onRuntimeLabel, selectedRuntime]);
+
+ const startConversation = async () => {
+ if (selectedRuntime?.status !== "online") return;
+ const startedId = await builder.start(selectedRuntime.id, draft.model);
+ if (startedId) onStarted(startedId, selectedRuntime.id);
+ };
+
+ return (
+ <BuilderSetup
+ banner={
+ <UnfinishedDraftsBanner sessions={sessions} onResume={onResume} />
+ }
+ draft={draft}
+ onChange={setDraft}
+ runtimes={form.runtimes}
+ runtimesLoading={form.runtimesLoading}
+ members={form.members}
+ currentUserId={form.currentUserId}
+ selectedRuntime={selectedRuntime}
+ starting={builder.starting}
+ error={builder.error}
+ onStart={() => void startConversation()}
+ onConnectRuntime={() => navigation.push(paths.runtimes())}
+ />
+ );
+}
diff --git a/packages/views/agents/create/builder-workspace.tsx b/packages/views/agents/create/builder-workspace.tsx
new file mode 100644
index 0000000000..0bf55423bc
--- /dev/null
+++ b/packages/views/agents/create/builder-workspace.tsx
@@ -0,0 +1,409 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useDefaultLayout } from "react-resizable-panels";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import {
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+} from "@multica/ui/components/ui/resizable";
+import {
+ applyDraftRuntimeChange,
+ decodeBuilderInput,
+ encodeBuilderInput,
+ mergeBuilderDraft,
+ parseBuilderDraft,
+ stripBuilderDraft,
+} from "@multica/core/agents";
+import {
+ runtimeDisplayLabel,
+ runtimeModelsOptions,
+} from "@multica/core/runtimes";
+import type { AgentBuilderSessionSummary } from "@multica/core/types";
+import { AgentConfigurationPanel } from "./agent-configuration-panel";
+import { BuilderConversation } from "./builder-conversation";
+import { CreateAgentFooter } from "./create-agent-footer";
+import { useBuilderDraftSync } from "./use-builder-draft-sync";
+import { useBuilderSession } from "./use-builder-session";
+import { useCreateAgentForm } from "./use-create-agent-form";
+import { useCreateAgentSubmit } from "./use-create-agent-submit";
+import { useT } from "../../i18n";
+
+/**
+ * One creation conversation: the chat on the left, its live configuration on
+ * the right.
+ *
+ * Mounted with `key={sessionId}` by the page, so switching conversations tears
+ * this down and builds it again. That is deliberate — every piece of state here
+ * (the draft, which assistant message has been applied, the composer) belongs
+ * to one conversation, and a remount is the only reset that cannot forget a
+ * field.
+ */
+export function BuilderWorkspace({
+ sessionId,
+ squadId,
+ session,
+ sessionSettled,
+ fallbackRuntimeId,
+ onDiscarded,
+ onRuntimeLabel,
+}: {
+ sessionId: string;
+ squadId: string | null;
+ /** This conversation's row from the list, once it has arrived. */
+ session: AgentBuilderSessionSummary | undefined;
+ /** The list query answered — either data or an error. */
+ sessionSettled: boolean;
+ /** Runtime this conversation was just started on. A conversation only joins
+ * the list once it has a message, so for the first turn this is the only
+ * truthful answer to "where does it run". */
+ fallbackRuntimeId: string;
+ /** The conversation no longer exists; the page decides where to go. */
+ onDiscarded: () => void;
+ /** Reports the runtime this conversation settled on, for the shell's chip. */
+ onRuntimeLabel: (label: string | null) => void;
+}) {
+ const { t } = useT("agents");
+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({
+ id: "multica_agent_builder_layout",
+ });
+
+ // Resuming: the conversation already runs somewhere, and only the server
+ // knows where. Until it answers, the form seeds no runtime at all — falling
+ // back to the first usable one would put the picker on a runtime that
+ // executes nothing (MUL-5163).
+ const runtimeSeed = useMemo(
+ () => ({
+ ready: sessionSettled,
+ runtimeId: session?.runtime_id || fallbackRuntimeId,
+ }),
+ [fallbackRuntimeId, session?.runtime_id, sessionSettled],
+ );
+ const form = useCreateAgentForm({ runtimeSeed });
+ const { draft, setDraft, selectedRuntime } = form;
+
+ const draftSync = useBuilderDraftSync({
+ sessionId,
+ stored: session?.draft,
+ storedSettled: sessionSettled,
+ runtimeId: session?.runtime_id ?? "",
+ draft,
+ setDraft,
+ });
+
+ const builderModelsQuery = useQuery(
+ runtimeModelsOptions(
+ selectedRuntime?.status === "online" ? selectedRuntime.id : null,
+ ),
+ );
+ // `null` means discovery is not available yet (or failed), while `[]` is
+ // an authoritative catalog with no selectable models. In both cases the
+ // builder may preserve the user's current value but cannot invent one.
+ const builderModelCatalog = useMemo(
+ () =>
+ builderModelsQuery.isSuccess
+ ? builderModelsQuery.data.supported
+ ? builderModelsQuery.data.models
+ : []
+ : null,
+ [builderModelsQuery.data, builderModelsQuery.isSuccess],
+ );
+ const validBuilderModelIds = useMemo(
+ () =>
+ builderModelCatalog === null
+ ? null
+ : new Set(builderModelCatalog.map((model) => model.id)),
+ [builderModelCatalog],
+ );
+
+ // Read through a ref so the encoder handed to the session hook stays current
+ // without making the hook depend on every catalog query.
+ const encodeContext = useRef({
+ draft,
+ workspaceSkills: form.workspaceSkills,
+ members: form.members,
+ selectedRuntime,
+ builderModelCatalog,
+ });
+ encodeContext.current = {
+ draft,
+ workspaceSkills: form.workspaceSkills,
+ members: form.members,
+ selectedRuntime,
+ builderModelCatalog,
+ };
+
+ const builder = useBuilderSession({
+ sessionId,
+ encodeInput: (text) => {
+ const context = encodeContext.current;
+ return encodeBuilderInput(
+ text,
+ context.draft,
+ context.workspaceSkills,
+ context.members,
+ context.selectedRuntime,
+ context.builderModelCatalog,
+ );
+ },
+ });
+
+ const submit = useCreateAgentSubmit({
+ draft,
+ runtimeId: selectedRuntime?.id ?? null,
+ squadId,
+ template: "agent_builder",
+ // The agent is already committed here, so builder cleanup must never turn
+ // a successful create into a retryable create error.
+ onCreated: () => builder.archiveAfterCreate(),
+ });
+
+ const skillIdSet = useMemo(
+ () => new Set(form.workspaceSkills.map((skill) => skill.id)),
+ [form.workspaceSkills],
+ );
+ const memberIdSet = useMemo(
+ () => new Set(form.members.map((member) => member.user_id)),
+ [form.members],
+ );
+
+ // Realtime chat updates can mutate the cached messages array in place. Use
+ // the latest structured message's scalar identity/content as effect inputs
+ // so a draft is still applied when the array reference itself is unchanged.
+ const latestDraftMessage = [...builder.messages]
+ .reverse()
+ .find(
+ (message) =>
+ message.role === "assistant" && parseBuilderDraft(message.content),
+ );
+ const latestDraftMessageId = latestDraftMessage?.id;
+ const latestDraftMessageContent = latestDraftMessage?.content;
+
+ const { restored, markApplied } = draftSync;
+ const appliedRef = useRef<string | null>(null);
+ appliedRef.current = draftSync.appliedMessageId;
+
+ useEffect(() => {
+ // Gated on the restore: merging a reply into the form before the stored
+ // configuration lands would be overwritten a tick later, and the merge
+ // would have been computed against an empty draft.
+ if (!restored) return;
+ if (
+ !latestDraftMessageId ||
+ !latestDraftMessageContent ||
+ latestDraftMessageId === appliedRef.current
+ ) {
+ return;
+ }
+ const payload = parseBuilderDraft(latestDraftMessageContent);
+ if (!payload) return;
+ markApplied(latestDraftMessageId);
+ setDraft((current) =>
+ mergeBuilderDraft(
+ current,
+ payload,
+ skillIdSet,
+ memberIdSet,
+ validBuilderModelIds,
+ ),
+ );
+ }, [
+ latestDraftMessageContent,
+ latestDraftMessageId,
+ markApplied,
+ memberIdSet,
+ restored,
+ setDraft,
+ skillIdSet,
+ validBuilderModelIds,
+ ]);
+
+ const displayMessages = useMemo(
+ () =>
+ builder.messages.map((message) => ({
+ ...message,
+ content:
+ message.role === "user"
+ ? decodeBuilderInput(message.content)
+ : stripBuilderDraft(message.content),
+ })),
+ [builder.messages],
+ );
+
+ // True once the draft's runtime is known to match the carrier's. Until then
+ // no selection may reach the server: RuntimePicker seeds an empty selection by
+ // calling onSelect itself, and in this pane onSelect rebinds the live
+ // conversation — so honouring that seed would move the conversation to
+ // whatever runtime sorts first, silently when idle and as "stop the current
+ // reply before switching runtime" when not.
+ const runtimeKnown = sessionSettled && draft.runtimeId.length > 0;
+
+ useEffect(() => {
+ onRuntimeLabel(selectedRuntime ? runtimeDisplayLabel(selectedRuntime) : null);
+ }, [onRuntimeLabel, selectedRuntime]);
+
+ const handleRuntimeSelect = async (runtimeId: string) => {
+ if (!runtimeKnown) return;
+ if (!runtimeId || runtimeId === draft.runtimeId) return;
+ const bound = await builder.switchRuntime(runtimeId);
+ if (!bound) return;
+ // Model ids are per-runtime; clear it — with the per-model thinking /
+ // speed overrides — so the new runtime resolves its own defaults instead
+ // of keeping values it may not serve.
+ setDraft((current) => applyDraftRuntimeChange(current, bound));
+ };
+
+ const canCreate =
+ draft.name.trim().length > 0 &&
+ form.draftReady &&
+ !submit.creating &&
+ !builder.pending;
+
+ // No beforeunload guard here on purpose: the conversation lives on the server
+ // and the configuration autosaves, so there is nothing a reload can lose. The
+ // manual route still warns because its form has no server-side home.
+
+ const [confirmingDiscard, setConfirmingDiscard] = useState(false);
+ // A conversation that no longer exists cannot be shown, edited or resumed;
+ // leave rather than render an editable shell over nothing.
+ const { missing } = builder;
+ useEffect(() => {
+ if (missing) onDiscarded();
+ }, [missing, onDiscarded]);
+
+ const discard = async () => {
+ if (!(await builder.destroy())) return;
+ setConfirmingDiscard(false);
+ onDiscarded();
+ };
+
+ return (
+ <>
+ {/* The group lives here, not on the route, so its two panels are its
+ only children — the same shape the chat page uses. A group whose
+ children alternate between one and two panels (setup vs conversation)
+ cannot keep a single persisted layout straight, and a panel arriving
+ through a child component's fragment is not a child it can measure. */}
+ <ResizablePanelGroup
+ orientation="horizontal"
+ className="min-h-0 flex-1"
+ defaultLayout={defaultLayout}
+ onLayoutChanged={onLayoutChanged}
+ >
+ <ResizablePanel id="conversation" minSize="30%">
+ <BuilderConversation
+ sessionId={sessionId}
+ messages={displayMessages}
+ loading={builder.messagesLoading}
+ pendingTask={builder.pendingTask}
+ runtimeOnline={selectedRuntime?.status === "online"}
+ onSend={builder.send}
+ onStop={() => void builder.stop()}
+ restoreDraftRequest={builder.restoreDraftRequest}
+ onRestoreDraftApplied={builder.handleRestoreDraftApplied}
+ error={builder.error}
+ />
+ </ResizablePanel>
+ <ResizableHandle />
+ <ResizablePanel
+ id="config"
+ defaultSize={420}
+ minSize={340}
+ groupResizeBehavior="preserve-pixel-size"
+ >
+ <div className="flex h-full min-h-0 flex-col border-l bg-muted/10">
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="mx-auto max-w-2xl px-5 py-6">
+ <div className="mb-6">
+ <h2 className="text-title-sm font-semibold tracking-tight">
+ {t(($) => $.creation_studio.live_draft)}
+ </h2>
+ <p className="mt-1 text-caption text-muted-foreground">
+ {t(($) => $.creation_studio.live_draft_hint)}
+ </p>
+ </div>
+ <AgentConfigurationPanel
+ compact
+ draft={draft}
+ onChange={setDraft}
+ runtimes={form.runtimes}
+ runtimesLoading={form.runtimesLoading}
+ members={form.members}
+ currentUserId={form.currentUserId}
+ nameError={submit.nameError}
+ onNameChange={(name) => {
+ submit.clearNameError();
+ setDraft((current) => ({ ...current, name }));
+ }}
+ onRuntimeSelect={(runtimeId) => {
+ void handleRuntimeSelect(runtimeId);
+ }}
+ runtimeSwitchPending={builder.pending}
+ // Also locked while the carrier's runtime is unknown, so the
+ // picker cannot offer a switch it would refuse to perform.
+ runtimeSwitchInFlight={
+ builder.switchingRuntime || !runtimeKnown
+ }
+ />
+ </div>
+ </div>
+ <CreateAgentFooter
+ canCreate={canCreate}
+ creating={submit.creating}
+ squad={!!squadId}
+ error={submit.formError}
+ onCreate={() => void submit.create()}
+ onDiscard={() => setConfirmingDiscard(true)}
+ discarding={builder.closing}
+ />
+ </div>
+ </ResizablePanel>
+ </ResizablePanelGroup>
+
+ <AlertDialog
+ open={confirmingDiscard}
+ onOpenChange={(open) => {
+ if (!open && !builder.closing) setConfirmingDiscard(false);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.creation_studio.drafts.discard_title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.creation_studio.drafts.discard_confirm)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={builder.closing}>
+ {t(($) => $.creation_studio.drafts.discard_cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ onClick={(event) => {
+ // Keep the dialog up while the delete is in flight; it closes
+ // from `discard` only once the server has actually accepted.
+ event.preventDefault();
+ void discard();
+ }}
+ disabled={builder.closing}
+ >
+ {t(($) => $.creation_studio.drafts.discard)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
diff --git a/packages/views/agents/create/choose-create-method-page.tsx b/packages/views/agents/create/choose-create-method-page.tsx
new file mode 100644
index 0000000000..1757bb4f1e
--- /dev/null
+++ b/packages/views/agents/create/choose-create-method-page.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+import { ChevronRight, FileText, MessageSquare } from "lucide-react";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { cn } from "@multica/ui/lib/utils";
+import { useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+import { AgentCreateShell } from "./create-shell";
+import { withSquadParam } from "./squad-param";
+
+/**
+ * Entry route of agent creation: pick a method, then hand off to that method's
+ * own route. Holds no draft — nothing typed here survives to the next screen
+ * because nothing is typed here.
+ */
+export function ChooseCreateMethodPage() {
+ const { t } = useT("agents");
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const squadId = navigation.searchParams.get("squad");
+
+ return (
+ <AgentCreateShell
+ title={
+ squadId
+ ? t(($) => $.creation_studio.squad_title)
+ : t(($) => $.creation_studio.title)
+ }
+ step={t(($) => $.creation_studio.step_choose)}
+ onBack={() => navigation.push(paths.agents())}
+ >
+ <main className="flex min-h-0 flex-1 flex-col overflow-y-auto px-5 py-10">
+ <CreateMethodChooser
+ onBlank={() =>
+ navigation.push(withSquadParam(paths.newAgentManual(), squadId))
+ }
+ onAI={() =>
+ navigation.push(withSquadParam(paths.newAgentAi(), squadId))
+ }
+ />
+ </main>
+ </AgentCreateShell>
+ );
+}
+
+export function CreateMethodChooser({
+ onBlank,
+ onAI,
+}: {
+ onBlank: () => void;
+ onAI: () => void;
+}) {
+ const { t } = useT("agents");
+ const modes = [
+ {
+ icon: FileText,
+ title: t(($) => $.creation_studio.modes.blank.title),
+ description: t(($) => $.creation_studio.modes.blank.description),
+ action: onBlank,
+ },
+ {
+ icon: MessageSquare,
+ title: t(($) => $.creation_studio.modes.ai.title),
+ description: t(($) => $.creation_studio.modes.ai.description),
+ action: onAI,
+ recommended: true,
+ },
+ ];
+ return (
+ <div className="m-auto w-full max-w-5xl">
+ <div className="mx-auto max-w-2xl text-center">
+ <div className="text-caption font-medium uppercase tracking-wider text-muted-foreground">
+ {t(($) => $.creation_studio.eyebrow)}
+ </div>
+ <h2 className="mt-2 text-balance text-display-sm font-semibold tracking-tight sm:text-display">
+ {t(($) => $.creation_studio.choose_title)}
+ </h2>
+ <p className="mt-3 text-pretty text-body text-muted-foreground">
+ {t(($) => $.creation_studio.choose_description)}
+ </p>
+ </div>
+ <div className="mx-auto mt-9 grid max-w-3xl gap-4 md:grid-cols-2">
+ {modes.map(
+ ({ icon: Icon, title, description, action, recommended }) => (
+ <button
+ key={title}
+ type="button"
+ onClick={action}
+ className={cn(
+ "group relative flex min-h-56 flex-col items-start rounded-xl border bg-card p-5 text-left",
+ "transition-[border-color,background-color,transform] hover:-translate-y-0.5 hover:border-primary/40 hover:bg-accent/30",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ recommended && "border-primary/30 bg-primary/[0.025]",
+ )}
+ >
+ {recommended && (
+ <span className="absolute right-4 top-4 rounded-full bg-primary/10 px-2 py-1 text-micro font-medium text-primary">
+ {t(($) => $.creation_studio.recommended)}
+ </span>
+ )}
+ <span className="flex size-11 items-center justify-center rounded-lg bg-muted text-muted-foreground group-hover:text-foreground">
+ <Icon className="size-5" aria-hidden="true" />
+ </span>
+ <span className="mt-7 text-title-sm font-semibold">{title}</span>
+ <span className="mt-2 text-body leading-6 text-muted-foreground">
+ {description}
+ </span>
+ <span className="mt-auto flex items-center gap-1 pt-5 text-caption font-medium text-foreground">
+ {t(($) => $.creation_studio.continue)}
+ <ChevronRight
+ className="size-3.5 transition-transform group-hover:translate-x-0.5"
+ aria-hidden="true"
+ />
+ </span>
+ </button>
+ ),
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/agents/create/create-agent-footer.tsx b/packages/views/agents/create/create-agent-footer.tsx
new file mode 100644
index 0000000000..a9e2aceb30
--- /dev/null
+++ b/packages/views/agents/create/create-agent-footer.tsx
@@ -0,0 +1,72 @@
+"use client";
+
+import { Loader2 } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../../i18n";
+
+/**
+ * Where the flow ends. Both exits live here — commit the agent, or abandon the
+ * attempt — because they are the two answers to one question, and reading them
+ * side by side is what makes the destructive one legible. A discard control
+ * parked elsewhere (say, a trash icon over the transcript) reads as "clear this
+ * chat" rather than "throw away what I am building".
+ *
+ * `onDiscard` is optional: the manual route has nothing to abandon, its form is
+ * gone the moment the user navigates away.
+ */
+export function CreateAgentFooter({
+ canCreate,
+ creating,
+ squad,
+ error,
+ onCreate,
+ onDiscard,
+ discarding = false,
+}: {
+ canCreate: boolean;
+ creating: boolean;
+ squad: boolean;
+ error: string | null;
+ onCreate: () => void;
+ onDiscard?: () => void;
+ discarding?: boolean;
+}) {
+ const { t } = useT("agents");
+ return (
+ <div className="pe-chat-launcher sticky bottom-0 mt-8 flex items-center justify-between gap-3 border-t bg-background/95 py-3 pl-5 backdrop-blur">
+ {error ? (
+ <p
+ role="alert"
+ className="min-w-0 flex-1 break-words text-body text-destructive"
+ >
+ {error}
+ </p>
+ ) : null}
+ {onDiscard ? (
+ <Button
+ type="button"
+ variant="ghost"
+ className="ml-auto shrink-0 text-muted-foreground hover:text-foreground"
+ onClick={onDiscard}
+ disabled={creating || discarding}
+ >
+ {t(($) => $.creation_studio.drafts.discard)}
+ </Button>
+ ) : null}
+ <Button
+ type="button"
+ className={cn("shrink-0", !onDiscard && "ml-auto")}
+ onClick={onCreate}
+ disabled={!canCreate}
+ >
+ {creating && <Loader2 className="size-4 animate-spin" />}
+ {creating
+ ? t(($) => $.creation_studio.creating)
+ : squad
+ ? t(($) => $.creation_studio.create_and_add)
+ : t(($) => $.creation_studio.create_and_open)}
+ </Button>
+ </div>
+ );
+}
diff --git a/packages/views/agents/create/create-agent-ui.test.ts b/packages/views/agents/create/create-agent-ui.test.ts
new file mode 100644
index 0000000000..b622d3e4d9
--- /dev/null
+++ b/packages/views/agents/create/create-agent-ui.test.ts
@@ -0,0 +1,206 @@
+import { createElement } from "react";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { ApiError } from "@multica/core/api";
+import { AgentNameField } from "./agent-configuration-panel";
+import { CreateMethodChooser } from "./choose-create-method-page";
+import { CreateAgentFooter } from "./create-agent-footer";
+import { draftPreview } from "./unfinished-drafts";
+import { classifyAgentCreateError } from "./use-create-agent-submit";
+
+vi.mock("../../i18n", () => ({
+ useT: () => ({
+ t: (
+ selector: (translations: {
+ creation_studio: {
+ eyebrow: string;
+ choose_title: string;
+ choose_description: string;
+ recommended: string;
+ continue: string;
+ modes: {
+ blank: { title: string; description: string };
+ ai: { title: string; description: string };
+ };
+ create_and_open: string;
+ create_and_add: string;
+ creating: string;
+ name_conflict: string;
+ };
+ create_dialog: {
+ name_label: string;
+ name_placeholder: string;
+ };
+ }) => string,
+ ) =>
+ selector({
+ creation_studio: {
+ eyebrow: "Agent creation",
+ choose_title: "How would you like to start?",
+ choose_description: "Choose a creation mode.",
+ recommended: "Recommended",
+ continue: "Continue",
+ modes: {
+ blank: {
+ title: "Start blank",
+ description: "Configure every field yourself.",
+ },
+ ai: {
+ title: "Build with AI",
+ description: "Describe the outcome you want.",
+ },
+ },
+ create_and_open: "Create and open",
+ create_and_add: "Create and add",
+ creating: "Creating…",
+ name_conflict: "An agent with this name already exists.",
+ },
+ create_dialog: {
+ name_label: "Name",
+ name_placeholder: "Agent name",
+ },
+ }),
+ }),
+}));
+
+describe("Agent creation errors", () => {
+ it("classifies a conflict as a name error", () => {
+ expect(
+ classifyAgentCreateError(
+ new ApiError("An agent with this name already exists", 409, "Conflict"),
+ "Could not create the agent.",
+ "This localized name is already in use.",
+ ),
+ ).toEqual({
+ nameError: "This localized name is already in use.",
+ formError: null,
+ });
+ });
+
+ it("classifies a network error as a form error", () => {
+ expect(
+ classifyAgentCreateError(
+ new Error("Network request failed"),
+ "Could not create the agent.",
+ "An agent with this name already exists.",
+ ),
+ ).toEqual({
+ nameError: null,
+ formError: "Network request failed",
+ });
+ });
+
+ it("renders a name error directly below the name input", () => {
+ const onChange = vi.fn();
+ render(
+ createElement(AgentNameField, {
+ name: "Existing agent",
+ error: "An agent with this name already exists",
+ onChange,
+ }),
+ );
+
+ const input = screen.getByRole("textbox", { name: "Name" });
+ const error = screen.getByText("An agent with this name already exists");
+ expect(input).toHaveAttribute("aria-invalid", "true");
+ expect(input).toHaveAttribute("aria-describedby", error.id);
+ expect(error).not.toHaveAttribute("role");
+ expect(
+ input.compareDocumentPosition(error) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+
+ fireEvent.change(input, { target: { value: "New agent" } });
+ expect(onChange).toHaveBeenCalledWith("New agent");
+ });
+
+ it("focuses and selects the name input when a name error appears", () => {
+ const onChange = vi.fn();
+ const view = render(
+ createElement(AgentNameField, {
+ name: "Existing agent",
+ error: null,
+ onChange,
+ }),
+ );
+
+ const input = screen.getByRole("textbox", { name: "Name" });
+ expect(input).not.toHaveFocus();
+
+ view.rerender(
+ createElement(AgentNameField, {
+ name: "Existing agent",
+ error: "An agent with this name already exists",
+ onChange,
+ }),
+ );
+
+ expect(input).toHaveFocus();
+ expect(input).toHaveValue("Existing agent");
+ expect(input).toHaveProperty("selectionStart", 0);
+ expect(input).toHaveProperty("selectionEnd", "Existing agent".length);
+ });
+
+ it("renders a generic error on the left side of the sticky footer", () => {
+ render(
+ createElement(CreateAgentFooter, {
+ canCreate: true,
+ creating: false,
+ squad: false,
+ error: "Network request failed",
+ onCreate: vi.fn(),
+ }),
+ );
+
+ const error = screen.getByRole("alert");
+ const button = screen.getByRole("button", { name: "Create and open" });
+ expect(error.parentElement).toBe(button.parentElement);
+ expect(
+ error.compareDocumentPosition(button) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+});
+
+// The list endpoint returns the stored message untouched, still in the builder
+// wire format. Rendered raw it is a wall of JSON, which is what the user would
+// see on the one screen meant to help them recognise their own draft.
+describe("Unfinished draft preview", () => {
+ it("unwraps the encoded envelope on a user message", () => {
+ expect(
+ draftPreview({
+ last_message_role: "user",
+ last_message_content:
+ 'MULTICA_AGENT_BUILDER_INPUT\n{"user_request":"Create a release manager","current_draft":{"name":"X"}}',
+ }),
+ ).toBe("Create a release manager");
+ });
+
+ it("hides the structured block on an assistant message", () => {
+ expect(
+ draftPreview({
+ last_message_role: "assistant",
+ last_message_content:
+ 'Here is a first draft.\n<agent_draft>{"name":"Researcher"}</agent_draft>',
+ }),
+ ).toBe("Here is a first draft.");
+ });
+
+ it("returns an empty preview when the server sent no message", () => {
+ expect(
+ draftPreview({ last_message_role: "", last_message_content: "" }),
+ ).toBe("");
+ });
+});
+
+describe("Agent creation method chooser", () => {
+ it("always offers AI-assisted creation", () => {
+ render(
+ createElement(CreateMethodChooser, {
+ onBlank: vi.fn(),
+ onAI: vi.fn(),
+ }),
+ );
+
+ expect(screen.getByText("Start blank")).toBeInTheDocument();
+ expect(screen.getByText("Build with AI")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/agents/create/create-shell.tsx b/packages/views/agents/create/create-shell.tsx
new file mode 100644
index 0000000000..e01d8745b4
--- /dev/null
+++ b/packages/views/agents/create/create-shell.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { ArrowLeft } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import { useT } from "../../i18n";
+
+/**
+ * Chrome shared by every agent-creation route: the back control, the flow
+ * title, and the current step. Each route owns what "back" means — the chooser
+ * leaves the flow, the two method routes return to the chooser — so the shell
+ * takes a handler rather than deriving it.
+ */
+export function AgentCreateShell({
+ title,
+ step,
+ onBack,
+ backDisabled = false,
+ chips,
+ children,
+}: {
+ title: string;
+ step: string;
+ onBack: () => void;
+ backDisabled?: boolean;
+ /** Right-aligned context badges (method, runtime). Hidden on small screens. */
+ chips?: ReactNode;
+ children: ReactNode;
+}) {
+ const { t } = useT("agents");
+ return (
+ <div className="flex min-h-0 flex-1 flex-col bg-background">
+ <header className="flex h-14 shrink-0 items-center gap-3 border-b px-5">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={onBack}
+ disabled={backDisabled}
+ aria-label={t(($) => $.creation_studio.back)}
+ >
+ <ArrowLeft className="size-4" aria-hidden="true" />
+ </Button>
+ <div className="min-w-0">
+ <h1 className="truncate text-body font-semibold">{title}</h1>
+ <p className="truncate text-caption text-muted-foreground">{step}</p>
+ </div>
+ {chips ? (
+ <div className="ml-auto hidden items-center gap-2 text-caption text-muted-foreground sm:flex">
+ {chips}
+ </div>
+ ) : null}
+ </header>
+ {children}
+ </div>
+ );
+}
+
+export function AgentCreateChip({ children }: { children: ReactNode }) {
+ return <span className="rounded-full bg-muted px-2 py-1">{children}</span>;
+}
diff --git a/packages/views/agents/create/index.ts b/packages/views/agents/create/index.ts
new file mode 100644
index 0000000000..d80c5f1a32
--- /dev/null
+++ b/packages/views/agents/create/index.ts
@@ -0,0 +1,6 @@
+// The three route entry points. Everything else in this folder is internal to
+// the flow and already imported by path — re-exporting it here only created a
+// second name for the same thing and a list to keep in sync.
+export { ChooseCreateMethodPage } from "./choose-create-method-page";
+export { ManualCreateAgentPage } from "./manual-create-agent-page";
+export { AiCreateAgentPage } from "./ai-create-agent-page";
diff --git a/packages/views/agents/create/manual-create-agent-page.tsx b/packages/views/agents/create/manual-create-agent-page.tsx
new file mode 100644
index 0000000000..ced59fa9f6
--- /dev/null
+++ b/packages/views/agents/create/manual-create-agent-page.tsx
@@ -0,0 +1,160 @@
+"use client";
+
+import { useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { runtimeDisplayLabel } from "@multica/core/runtimes";
+import { agentListOptions } from "@multica/core/workspace/queries";
+import { useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+import { AgentConfigurationPanel } from "./agent-configuration-panel";
+import { CreateAgentFooter } from "./create-agent-footer";
+import { AgentCreateChip, AgentCreateShell } from "./create-shell";
+import { useCreateAgentForm } from "./use-create-agent-form";
+import { useCreateAgentSubmit } from "./use-create-agent-submit";
+import { useDuplicateDraftSeed } from "./use-duplicate-draft-seed";
+import {
+ clearManualDraftForOwner,
+ useManualDraftSync,
+} from "./use-manual-draft-sync";
+
+/**
+ * Manual agent creation: every field filled in by hand.
+ *
+ * `?duplicate=<id>` seeds the same form from an existing agent instead of
+ * starting empty — the two share one route because after seeding they are the
+ * same screen with the same submit path.
+ */
+export function ManualCreateAgentPage() {
+ const { t } = useT("agents");
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const duplicateId = navigation.searchParams.get("duplicate");
+ const squadId = navigation.searchParams.get("squad");
+
+ const form = useCreateAgentForm();
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const duplicateAgent = duplicateId
+ ? agents.find((agent) => agent.id === duplicateId) ?? null
+ : null;
+
+ // True when a duplicate had to fall back to another runtime, which drops the
+ // source's model / thinking / speed. The notice explains the empty fields.
+ const [duplicateRuntimeReset, setDuplicateRuntimeReset] = useState(false);
+ // A duplicate seeds asynchronously (it waits for the runtime query). Saving
+ // before that lands would persist the empty form the seed is about to
+ // replace, and restoring before it would be undone a tick later.
+ const [duplicateSeeded, setDuplicateSeeded] = useState(false);
+
+ useDuplicateDraftSeed({
+ source: duplicateAgent,
+ // `buildDuplicateDraft` decides whether the copy can stay on the source
+ // runtime by looking it up in this list. An error is a decidable answer
+ // (the runtime cannot be confirmed, so the fallback is right); a pending
+ // query is not.
+ runtimesSettled: form.runtimesSettled,
+ runtimes: form.runtimes,
+ currentUserId: form.currentUserId,
+ fallbackRuntimeId: form.usableRuntimes[0]?.id ?? "",
+ nameSuffix: t(($) => $.create_dialog.duplicate_copy_suffix),
+ onSeed: (duplicated, runtimeReset) => {
+ // Only the forced fallback gets the notice; a later manual runtime switch
+ // is the user's own doing and needs no explanation.
+ setDuplicateRuntimeReset(runtimeReset);
+ form.setDraft(duplicated);
+ setDuplicateSeeded(true);
+ },
+ });
+
+ // What #6287 reported: the desktop shell mounts only the active tab, so
+ // coming back from another tab is a remount and everything typed was gone.
+ useManualDraftSync({
+ duplicateId,
+ draft: form.draft,
+ setDraft: form.setDraft,
+ ready: !duplicateId || duplicateSeeded,
+ });
+
+ const submit = useCreateAgentSubmit({
+ draft: form.draft,
+ runtimeId: form.selectedRuntime?.id ?? null,
+ squadId,
+ duplicateSource: duplicateAgent,
+ // The work is committed; leaving it stored would hand the finished agent's
+ // fields to whoever opens this form next. Only this flow's slot — another
+ // half-finished copy is still someone's unfinished work.
+ onCreated: () => clearManualDraftForOwner(duplicateId),
+ });
+
+ const canCreate =
+ form.draft.name.trim().length > 0 && form.draftReady && !submit.creating;
+
+ return (
+ <AgentCreateShell
+ title={
+ duplicateAgent
+ ? t(($) => $.creation_studio.duplicate_title, {
+ name: duplicateAgent.name,
+ })
+ : squadId
+ ? t(($) => $.creation_studio.squad_title)
+ : t(($) => $.creation_studio.title)
+ }
+ step={t(($) => $.creation_studio.step_configure)}
+ // A duplicate arrives from the agents list, not from the chooser, so it
+ // returns to where it came from instead of offering a method to pick.
+ onBack={() =>
+ navigation.push(duplicateId ? paths.agents() : paths.newAgent())
+ }
+ chips={
+ <>
+ <AgentCreateChip>
+ {t(($) => $.creation_studio.modes.blank.title)}
+ </AgentCreateChip>
+ {form.selectedRuntime && (
+ <AgentCreateChip>
+ {runtimeDisplayLabel(form.selectedRuntime)}
+ </AgentCreateChip>
+ )}
+ </>
+ }
+ >
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="mx-auto w-full max-w-4xl px-5 py-8 sm:px-8">
+ {duplicateAgent && (
+ <div className="mb-5 rounded-lg border border-warning/30 bg-warning/5 px-4 py-3 text-body">
+ {t(($) => $.creation_studio.duplicate_env_notice)}
+ </div>
+ )}
+ {duplicateRuntimeReset && (
+ <div className="mb-5 rounded-lg border border-warning/30 bg-warning/5 px-4 py-3 text-body">
+ {t(($) => $.creation_studio.duplicate_runtime_reset_notice)}
+ </div>
+ )}
+ <AgentConfigurationPanel
+ draft={form.draft}
+ onChange={form.setDraft}
+ runtimes={form.runtimes}
+ runtimesLoading={form.runtimesLoading}
+ members={form.members}
+ currentUserId={form.currentUserId}
+ nameError={submit.nameError}
+ onNameChange={(name) => {
+ submit.clearNameError();
+ form.setDraft((current) => ({ ...current, name }));
+ }}
+ />
+ </div>
+ <CreateAgentFooter
+ canCreate={canCreate}
+ creating={submit.creating}
+ squad={!!squadId}
+ error={submit.formError}
+ onCreate={() => void submit.create()}
+ />
+ </div>
+ </AgentCreateShell>
+ );
+}
diff --git a/packages/views/agents/create/squad-param.ts b/packages/views/agents/create/squad-param.ts
new file mode 100644
index 0000000000..abbb984b42
--- /dev/null
+++ b/packages/views/agents/create/squad-param.ts
@@ -0,0 +1,23 @@
+/**
+ * Builds a creation-route URL with the params that have to survive a hop
+ * between screens.
+ *
+ * `squad` is the reason the flow was opened at all, so it rides along from the
+ * chooser into whichever method the user picks. `session` addresses one builder
+ * conversation, so a refresh, a back/forward, or a reopened tab lands back in
+ * the same chat instead of starting a new one.
+ */
+export function createPathWithParams(
+ path: string,
+ params: { squad?: string | null; session?: string | null },
+): string {
+ const query = new URLSearchParams();
+ if (params.squad) query.set("squad", params.squad);
+ if (params.session) query.set("session", params.session);
+ const suffix = query.toString();
+ return suffix ? `${path}?${suffix}` : path;
+}
+
+export function withSquadParam(path: string, squadId: string | null): string {
+ return createPathWithParams(path, { squad: squadId });
+}
diff --git a/packages/views/agents/create/unfinished-drafts.tsx b/packages/views/agents/create/unfinished-drafts.tsx
new file mode 100644
index 0000000000..26919234e7
--- /dev/null
+++ b/packages/views/agents/create/unfinished-drafts.tsx
@@ -0,0 +1,157 @@
+"use client";
+
+import { useState } from "react";
+import { ChevronRight, MessageSquare } from "lucide-react";
+import { decodeBuilderInput, stripBuilderDraft } from "@multica/core/agents";
+import type { AgentBuilderSessionSummary } from "@multica/core/types";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { cn } from "@multica/ui/lib/utils";
+import { useT, useTimeAgo } from "../../i18n";
+
+/**
+ * Offers the conversations this user started and left, on the one screen that
+ * would otherwise silently start a third one.
+ *
+ * A single unfinished draft opens directly — a chooser listing one item is a
+ * question with one answer. Several open a dialog, because picking between them
+ * needs to show what each one is about, which does not fit in a banner.
+ */
+export function UnfinishedDraftsBanner({
+ sessions,
+ onResume,
+}: {
+ sessions: AgentBuilderSessionSummary[];
+ onResume: (sessionId: string) => void;
+}) {
+ const { t } = useT("agents");
+ const [picking, setPicking] = useState(false);
+
+ if (sessions.length === 0) return null;
+
+ const openOrPick = () => {
+ const only = sessions[0];
+ if (sessions.length === 1 && only) {
+ onResume(only.session_id);
+ return;
+ }
+ setPicking(true);
+ };
+
+ return (
+ <>
+ <button
+ type="button"
+ onClick={openOrPick}
+ className={cn(
+ "mb-5 flex w-full items-center gap-3 rounded-lg border bg-muted/40 px-4 py-3 text-left transition-colors",
+ "hover:border-primary/40 hover:bg-accent/30",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ )}
+ >
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-background text-muted-foreground">
+ <MessageSquare className="size-4" aria-hidden="true" />
+ </span>
+ <span className="min-w-0 flex-1 text-body">
+ {t(($) => $.creation_studio.drafts.banner, {
+ count: sessions.length,
+ })}
+ </span>
+ <ChevronRight
+ className="size-4 shrink-0 text-muted-foreground"
+ aria-hidden="true"
+ />
+ </button>
+
+ <Dialog open={picking} onOpenChange={setPicking}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.creation_studio.drafts.title)}</DialogTitle>
+ <DialogDescription>
+ {t(($) => $.creation_studio.drafts.pick_hint)}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="max-h-96 space-y-2 overflow-y-auto">
+ {sessions.map((session) => (
+ <button
+ key={session.session_id}
+ type="button"
+ onClick={() => {
+ setPicking(false);
+ onResume(session.session_id);
+ }}
+ className={cn(
+ "flex w-full items-start gap-3 rounded-lg border p-3 text-left transition-colors",
+ "hover:border-primary/40 hover:bg-accent/30",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ )}
+ >
+ <span className="min-w-0 flex-1">
+ <span className="flex items-baseline gap-2">
+ <span className="truncate text-body font-medium">
+ {draftTitle(session) ||
+ t(($) => $.creation_studio.drafts.untitled)}
+ </span>
+ {session.last_message_at ? (
+ <DraftTimestamp at={session.last_message_at} />
+ ) : null}
+ </span>
+ {/* Two lines: enough to recognise which conversation this is,
+ short enough that a long reply cannot push the next row
+ off the dialog. */}
+ <span className="mt-1 line-clamp-2 block text-caption leading-5 text-muted-foreground">
+ {draftPreview(session)}
+ </span>
+ </span>
+ </button>
+ ))}
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
+
+function DraftTimestamp({ at }: { at: string }) {
+ const timeAgo = useTimeAgo();
+ return (
+ <span className="ml-auto shrink-0 text-micro text-muted-foreground">
+ {timeAgo(at)}
+ </span>
+ );
+}
+
+/**
+ * What the user calls this draft. The stored configuration's name is the only
+ * candidate — the server-side title is the same string on every row and would
+ * make the list unreadable.
+ */
+function draftTitle(
+ session: Pick<AgentBuilderSessionSummary, "draft">,
+): string {
+ return session.draft?.name?.trim() ?? "";
+}
+
+/**
+ * The stored message is still in the builder wire format — the user side is a
+ * JSON envelope carrying the whole draft, the assistant side ends in an
+ * `<agent_draft>` block. Shown raw it is a wall of JSON, so both sides are
+ * decoded through the same helpers the conversation itself uses.
+ */
+export function draftPreview(
+ session: Pick<
+ AgentBuilderSessionSummary,
+ "last_message_content" | "last_message_role"
+ >,
+): string {
+ const content = session.last_message_content;
+ if (!content) return "";
+ return session.last_message_role === "user"
+ ? decodeBuilderInput(content)
+ : stripBuilderDraft(content);
+}
diff --git a/packages/views/agents/create/use-builder-draft-sync.ts b/packages/views/agents/create/use-builder-draft-sync.ts
new file mode 100644
index 0000000000..50b73dfbb7
--- /dev/null
+++ b/packages/views/agents/create/use-builder-draft-sync.ts
@@ -0,0 +1,131 @@
+"use client";
+
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type Dispatch,
+ type SetStateAction,
+} from "react";
+import {
+ fromStoredAgentDraft,
+ storedAgentDraftsEqual,
+ toStoredAgentDraft,
+ type AgentDraft,
+ type StoredAgentDraft,
+} from "@multica/core/agents";
+import { api } from "@multica/core/api";
+
+/** How long editing pauses before the configuration is written back. */
+const AUTOSAVE_DELAY_MS = 800;
+
+interface BuilderDraftSync {
+ /**
+ * False until the stored configuration has been applied (or ruled out). The
+ * page must not merge an assistant `<agent_draft>` before this flips, or the
+ * reply would land on an empty draft and then be overwritten by the restore.
+ */
+ restored: boolean;
+ /** The assistant message whose draft is already reflected in the form. */
+ appliedMessageId: string | null;
+ markApplied: (messageId: string) => void;
+}
+
+/**
+ * Keeps one conversation's configuration in sync with the server: restore it on
+ * arrival, then write it back as the user edits.
+ *
+ * The ordering is the whole point. Autosave is armed only after the restore has
+ * run — a save fired while the form still holds its empty initial state would
+ * overwrite the stored configuration with nothing, turning "reopen my draft"
+ * into "lose my draft". `restored` also gates the assistant-draft merge for the
+ * same reason.
+ *
+ * `appliedMessageId` is persisted alongside the configuration because it is
+ * what stops a restore from re-applying the last reply over edits made after
+ * it. Held only in memory it died with the page, which is precisely when the
+ * next restore needs it.
+ */
+export function useBuilderDraftSync(options: {
+ sessionId: string;
+ /** The stored configuration, or null when none was ever saved. */
+ stored: StoredAgentDraft | null | undefined;
+ /** False while the stored configuration is still being fetched. */
+ storedSettled: boolean;
+ /** The carrier's runtime — server-owned, never taken from the stored copy. */
+ runtimeId: string;
+ draft: AgentDraft;
+ setDraft: Dispatch<SetStateAction<AgentDraft>>;
+}): BuilderDraftSync {
+ const { sessionId, stored, storedSettled, runtimeId, draft, setDraft } =
+ options;
+
+ const [restored, setRestored] = useState(false);
+ const appliedMessageIdRef = useRef<string | null>(null);
+ // The last shape known to be on the server, so an unchanged draft never
+ // produces a request. Also seeded by the restore, which must not immediately
+ // save back what it just read.
+ const savedRef = useRef<StoredAgentDraft | null>(null);
+
+ useEffect(() => {
+ if (!sessionId || restored || !storedSettled) return;
+ if (stored) {
+ appliedMessageIdRef.current = stored.applied_message_id;
+ savedRef.current = stored;
+ setDraft(fromStoredAgentDraft(stored, runtimeId));
+ }
+ setRestored(true);
+ }, [restored, runtimeId, sessionId, setDraft, stored, storedSettled]);
+
+ // What the debounce is holding, so the unmount below can send it. Without
+ // this, navigating away inside the debounce window silently dropped the last
+ // edits — the exact keystrokes the user is most likely to have just made.
+ const pendingRef = useRef<StoredAgentDraft | null>(null);
+ const save = useCallback(
+ (next: StoredAgentDraft) => {
+ savedRef.current = next;
+ pendingRef.current = null;
+ void api.saveAgentBuilderDraft(sessionId, next).catch(() => {
+ // Best-effort: the next edit retries, and one lost write costs the user
+ // nothing they can see. An error banner here would interrupt typing for
+ // something that self-heals.
+ savedRef.current = null;
+ });
+ },
+ [sessionId],
+ );
+ // Read through a ref by the unmount effect below, which must not re-run — and
+ // therefore must not depend on anything.
+ const saveRef = useRef(save);
+ saveRef.current = save;
+
+ useEffect(() => {
+ if (!sessionId || !restored) return;
+ const next = toStoredAgentDraft(draft, appliedMessageIdRef.current);
+ if (savedRef.current && storedAgentDraftsEqual(savedRef.current, next)) {
+ return;
+ }
+ pendingRef.current = next;
+ const timer = setTimeout(() => save(next), AUTOSAVE_DELAY_MS);
+ return () => clearTimeout(timer);
+ }, [draft, restored, save, sessionId]);
+
+ // Unmount is the deadline: a tab switch, a route change or a session switch
+ // all tear this down, and the debounce timer dies with it.
+ useEffect(
+ () => () => {
+ const pending = pendingRef.current;
+ if (pending) saveRef.current(pending);
+ },
+ [],
+ );
+
+ return {
+ restored,
+ appliedMessageId: appliedMessageIdRef.current,
+ markApplied: (messageId: string) => {
+ appliedMessageIdRef.current = messageId;
+ },
+ };
+}
diff --git a/packages/views/agents/create/use-builder-session.ts b/packages/views/agents/create/use-builder-session.ts
new file mode 100644
index 0000000000..ea851e95fe
--- /dev/null
+++ b/packages/views/agents/create/use-builder-session.ts
@@ -0,0 +1,313 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import {
+ agentBuilderSessionKeys,
+ decodeBuilderInput,
+ pickBuilderRestore,
+ type BuilderRestore,
+} from "@multica/core/agents";
+import { api, ApiError } from "@multica/core/api";
+import {
+ chatKeys,
+ chatMessagesOptions,
+ pendingChatTaskOptions,
+} from "@multica/core/chat/queries";
+import { useWorkspaceId } from "@multica/core/hooks";
+import type { ChatMessage } from "@multica/core/types";
+import { useAppForeground } from "../../common/use-app-foreground";
+import { useChatDraftRestore } from "../../chat/components/use-chat-draft-restore";
+import { useT } from "../../i18n";
+
+const EMPTY_CHAT_MESSAGES: ChatMessage[] = [];
+
+/**
+ * Lifecycle of one AI-builder conversation: create the hidden carrier session,
+ * exchange messages on it, rebind its runtime, and destroy it on request.
+ *
+ * The conversation is identified by `sessionId`, which the page reads off its
+ * own URL. That is what makes it survive a refresh, a back/forward, and a
+ * reopened tab — the hook holds no session state of its own, so unmounting it
+ * (a sidebar click, a route change) leaves the conversation intact on the
+ * server. Destroying one is now an explicit act, never a side effect of
+ * navigation.
+ *
+ * There is no polling: the global realtime sync already invalidates
+ * `chatKeys.messages` / `chatKeys.pendingTask` per session id on
+ * `chat:message`, `chat:done` and the task lifecycle events, exactly as it does
+ * for the main chat window — which has never polled.
+ */
+export function useBuilderSession(options: {
+ /** The conversation to operate on; empty string before one is started. */
+ sessionId: string;
+ /** Encodes composer text into the builder wire format for the current draft. */
+ encodeInput: (text: string) => string;
+}) {
+ const { t } = useT("agents");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const { sessionId } = options;
+
+ // Anything that changes whether this conversation is listable, or what its
+ // row says, has to reach the drafts list — it is rendered on other screens
+ // that are already mounted or will mount from cache.
+ const invalidateDraftList = () =>
+ qc.invalidateQueries({ queryKey: agentBuilderSessionKeys.list(wsId) });
+
+ const [starting, setStarting] = useState(false);
+ const [closing, setClosing] = useState(false);
+ const [switchingRuntime, setSwitchingRuntime] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [restoreDraft, setRestoreDraft] = useState<BuilderRestore | null>(null);
+
+ // The builder chat is a real chat_session, so cancelling a started-but-empty
+ // run defers the empty/non-empty judgment exactly as it does in the main chat
+ // (#5219): stop's response carries no restore_to_input, and the prompt arrives
+ // later as a durable chat_draft_restore row. Without this hook the studio
+ // composer would simply never see it. The two sources are exclusive — the
+ // synchronous cancel answers immediately, the durable one lands after the
+ // daemon acks — so whichever exists is handed to the composer.
+ //
+ // Gated on app foreground: this is a dedicated route, so being mounted means
+ // the surface is on screen, but a backgrounded tab must not fetch/apply/
+ // consume a restore the user is waiting on elsewhere. It recovers on its next
+ // fetch once the tab is refocused.
+ const appForeground = useAppForeground();
+ const {
+ restoreDraftRequest: durableRestoreRequest,
+ handleRestoreDraftApplied: handleDurableRestoreApplied,
+ } = useChatDraftRestore(sessionId || null, appForeground);
+ const restoreDraftRequest = useMemo(
+ () => pickBuilderRestore(restoreDraft, durableRestoreRequest),
+ [restoreDraft, durableRestoreRequest],
+ );
+
+ const messagesQuery = useQuery(chatMessagesOptions(sessionId));
+ const pendingQuery = useQuery(pendingChatTaskOptions(sessionId));
+ const messages = messagesQuery.data ?? EMPTY_CHAT_MESSAGES;
+ const pending = !!pendingQuery.data?.task_id;
+ // The conversation named by the URL is gone — discarded here, deleted from
+ // another tab, or a link that outlived it. Read off the transcript fetch
+ // rather than "absent from the drafts list", because a conversation is only
+ // listed once it has a message: a session created a second ago is legitimately
+ // missing from the list and must not be mistaken for a dead one.
+ const missing =
+ messagesQuery.error instanceof ApiError &&
+ messagesQuery.error.status === 404;
+
+ /** Creates the conversation. Returns its id so the caller can address it. */
+ const start = async (
+ runtimeId: string,
+ model: string,
+ ): Promise<string | null> => {
+ setStarting(true);
+ setError(null);
+ try {
+ const session = await api.createAgentBuilderSession({
+ runtime_id: runtimeId,
+ model: model.trim() || undefined,
+ });
+ if (!session.session_id) {
+ throw new Error(t(($) => $.creation_studio.builder.start_failed));
+ }
+ return session.session_id;
+ } catch (err) {
+ setError(
+ err instanceof Error
+ ? err.message
+ : t(($) => $.creation_studio.builder.start_failed),
+ );
+ return null;
+ } finally {
+ setStarting(false);
+ }
+ };
+
+ /**
+ * Destroys the conversation. Returns false when the server refused, so the
+ * caller can stay put and show the error instead of navigating away from a
+ * conversation that still exists.
+ */
+ const destroy = async (): Promise<boolean> => {
+ if (!sessionId) return true;
+ setClosing(true);
+ setError(null);
+ try {
+ await api.deleteChatSession(sessionId);
+ qc.removeQueries({ queryKey: chatKeys.messages(sessionId) });
+ qc.removeQueries({ queryKey: chatKeys.pendingTask(sessionId) });
+ void invalidateDraftList();
+ return true;
+ } catch (err) {
+ setError(
+ err instanceof Error
+ ? err.message
+ : t(($) => $.creation_studio.builder.stop_failed),
+ );
+ return false;
+ } finally {
+ setClosing(false);
+ }
+ };
+
+ /**
+ * Retires the conversation once its agent exists.
+ *
+ * Archived, not deleted: the conversation is the record of how this agent was
+ * designed, and an archived session is read-only and drops out of the drafts
+ * list, which is exactly the desired end state. Deleting it destroyed that
+ * record for no gain — the carrier costs nothing while idle, since usage is
+ * booked per task and an archived session can never run one.
+ *
+ * Best-effort by design: the agent is already committed at this point, so a
+ * failure here must never turn a successful create into a retryable error.
+ */
+ const archiveAfterCreate = async () => {
+ if (!sessionId) return;
+ try {
+ await api.setChatSessionArchived(sessionId, true);
+ void invalidateDraftList();
+ } catch {
+ // The draft stays listed; the user can discard it explicitly.
+ }
+ };
+
+ // 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 switchRuntime = async (runtimeId: string): Promise<string | null> => {
+ if (switchingRuntime) return null;
+ setSwitchingRuntime(true);
+ setError(null);
+ try {
+ const result = await api.switchAgentBuilderRuntime(sessionId, {
+ runtime_id: runtimeId,
+ });
+ toast.success(
+ t(($) => $.creation_studio.builder.switch_runtime_success),
+ );
+ // 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 path removes. The client fallback already resolves an
+ // unparseable success body to the requested id.
+ return result.runtime_id || runtimeId;
+ } catch (err) {
+ setError(
+ err instanceof Error
+ ? err.message
+ : t(($) => $.creation_studio.builder.switch_runtime_failed),
+ );
+ return null;
+ } finally {
+ setSwitchingRuntime(false);
+ }
+ };
+
+ const send = async (content: string): Promise<boolean> => {
+ const text = content.trim();
+ // switchingRuntime 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 || !sessionId || pending || switchingRuntime) return false;
+ setError(null);
+ try {
+ const encodedContent = options.encodeInput(text);
+ const result = await api.sendChatMessage(sessionId, encodedContent);
+ const createdAt = new Date().toISOString();
+ qc.setQueryData<ChatMessage[]>(
+ chatKeys.messages(sessionId),
+ (current = []) =>
+ current.some((message) => message.id === result.message_id)
+ ? current
+ : [
+ ...current,
+ {
+ id: result.message_id,
+ chat_session_id: sessionId,
+ role: "user",
+ content: encodedContent,
+ task_id: result.task_id,
+ created_at: createdAt,
+ },
+ ],
+ );
+ qc.setQueryData(chatKeys.pendingTask(sessionId), {
+ task_id: result.task_id,
+ status: "queued",
+ created_at: createdAt,
+ });
+ await Promise.all([
+ qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) }),
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) }),
+ // The first turn is what makes a brand-new conversation listable at
+ // all, and every later one moves it to the top with a new preview.
+ invalidateDraftList(),
+ ]);
+ return true;
+ } catch (err) {
+ setError(
+ err instanceof Error
+ ? err.message
+ : t(($) => $.creation_studio.builder.send_failed),
+ );
+ return false;
+ }
+ };
+
+ const stop = async () => {
+ const taskId = pendingQuery.data?.task_id;
+ if (!taskId || !sessionId) return;
+ qc.setQueryData(chatKeys.pendingTask(sessionId), {});
+ try {
+ const result = await api.cancelTaskById(taskId);
+ const restored = result.cancelled_chat_message;
+ if (restored?.restore_to_input) {
+ setRestoreDraft({
+ id: restored.message_id,
+ content: decodeBuilderInput(restored.content),
+ });
+ }
+ await Promise.all([
+ qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) }),
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) }),
+ ]);
+ } catch (err) {
+ setError(
+ err instanceof Error
+ ? err.message
+ : t(($) => $.creation_studio.builder.stop_failed),
+ );
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
+ }
+ };
+
+ return {
+ messages,
+ missing,
+ messagesLoading: messagesQuery.isLoading,
+ pendingTask: pendingQuery.data,
+ pending,
+ starting,
+ closing,
+ switchingRuntime,
+ error,
+ restoreDraftRequest,
+ handleRestoreDraftApplied: () => {
+ if (restoreDraft) {
+ setRestoreDraft(null);
+ return;
+ }
+ handleDurableRestoreApplied();
+ },
+ start,
+ destroy,
+ archiveAfterCreate,
+ switchRuntime,
+ send,
+ stop,
+ };
+}
diff --git a/packages/views/agents/create/use-create-agent-form.ts b/packages/views/agents/create/use-create-agent-form.ts
new file mode 100644
index 0000000000..bf66a8d597
--- /dev/null
+++ b/packages/views/agents/create/use-create-agent-form.ts
@@ -0,0 +1,144 @@
+"use client";
+
+import {
+ useEffect,
+ useMemo,
+ useState,
+ type Dispatch,
+ type SetStateAction,
+} from "react";
+import { useQuery } from "@tanstack/react-query";
+import {
+ EMPTY_AGENT_DRAFT,
+ isDraftDescriptionWithinLimit,
+ type AgentDraft,
+} from "@multica/core/agents";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { isRuntimeUsableForUser, runtimeListOptions } from "@multica/core/runtimes";
+import type {
+ MemberWithUser,
+ RuntimeDevice,
+ SkillSummary,
+} from "@multica/core/types";
+import {
+ memberListOptions,
+ skillListOptions,
+} from "@multica/core/workspace/queries";
+
+interface CreateAgentForm {
+ draft: AgentDraft;
+ setDraft: Dispatch<SetStateAction<AgentDraft>>;
+ runtimes: RuntimeDevice[];
+ runtimesLoading: boolean;
+ /** The runtime query answered — either data or an error. */
+ runtimesSettled: boolean;
+ /** Online runtimes this member is allowed to execute on. */
+ usableRuntimes: RuntimeDevice[];
+ selectedRuntime: RuntimeDevice | null;
+ members: MemberWithUser[];
+ workspaceSkills: SkillSummary[];
+ currentUserId: string | null;
+ /** Every non-name precondition the create button depends on. */
+ draftReady: boolean;
+}
+
+interface RuntimeSeed {
+ /**
+ * False while the caller is still resolving which runtime this draft belongs
+ * to. The form seeds nothing until it flips, so the list-order fallback can
+ * never win a race against the authoritative answer.
+ */
+ ready: boolean;
+ /** The runtime to adopt; empty falls back to the first usable one. */
+ runtimeId: string;
+}
+
+const IMMEDIATE_RUNTIME_SEED: RuntimeSeed = { ready: true, runtimeId: "" };
+
+/**
+ * The state every agent-creation route shares: one draft plus the workspace
+ * catalogs the form renders from.
+ *
+ * The draft itself is plain component state here. Making it survive navigation
+ * is the caller's job, because the two routes answer it differently: the AI
+ * route's configuration belongs to a conversation and lives on the server, the
+ * manual route's has nothing to hang off and persists locally.
+ */
+export function useCreateAgentForm(options?: {
+ /**
+ * Where the runtime comes from for a draft that already exists somewhere. A
+ * resumed builder conversation runs on the runtime its carrier is bound to,
+ * and the picker must show THAT — showing the first usable one instead is how
+ * MUL-5163 presented runtime A while every message ran on B.
+ */
+ runtimeSeed?: RuntimeSeed;
+}): CreateAgentForm {
+ const wsId = useWorkspaceId();
+ const currentUser = useAuthStore((state) => state.user);
+ const currentUserId = currentUser?.id ?? null;
+
+ const {
+ data: runtimes = [],
+ isLoading: runtimesLoading,
+ isSuccess: runtimesLoaded,
+ isError: runtimesFailed,
+ } = useQuery(runtimeListOptions(wsId));
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const { data: workspaceSkills = [] } = useQuery(skillListOptions(wsId));
+
+ const [draft, setDraft] = useState<AgentDraft>(EMPTY_AGENT_DRAFT);
+
+ const usableRuntimes = useMemo(
+ () =>
+ runtimes.filter(
+ (runtime) =>
+ runtime.status === "online" &&
+ isRuntimeUsableForUser(runtime, currentUserId),
+ ),
+ [currentUserId, runtimes],
+ );
+ const selectedRuntime =
+ runtimes.find((runtime) => runtime.id === draft.runtimeId) ?? null;
+
+ // Seeds the picker so a draft is submittable without a manual selection.
+ // Only fills an empty slot: once the draft names a runtime — chosen by the
+ // user, copied from a duplicate, resumed from the server — nothing may move
+ // it.
+ //
+ // One effect decides, not two: the authoritative seed and the list-order
+ // fallback resolve at different times, and letting them race is how the
+ // picker ends up on a runtime that executes nothing.
+ const seed = options?.runtimeSeed ?? IMMEDIATE_RUNTIME_SEED;
+ const seedReady = seed.ready;
+ const seedRuntimeId = seed.runtimeId;
+ useEffect(() => {
+ if (draft.runtimeId || !seedReady) return;
+ const next = seedRuntimeId || usableRuntimes[0]?.id || "";
+ if (!next) return;
+ setDraft((current) => ({ ...current, runtimeId: next }));
+ }, [draft.runtimeId, seedReady, seedRuntimeId, usableRuntimes]);
+
+ const accessInvalid =
+ draft.permissionScope === "members" &&
+ draft.memberIds.size === 0 &&
+ draft.teamIds.size === 0;
+
+ return {
+ draft,
+ setDraft,
+ runtimes,
+ runtimesLoading,
+ runtimesSettled: runtimesLoaded || runtimesFailed,
+ usableRuntimes,
+ selectedRuntime,
+ members,
+ workspaceSkills,
+ currentUserId,
+ draftReady:
+ selectedRuntime != null &&
+ isRuntimeUsableForUser(selectedRuntime, currentUserId) &&
+ isDraftDescriptionWithinLimit(draft.description) &&
+ !accessInvalid,
+ };
+}
diff --git a/packages/views/agents/create/use-create-agent-submit.ts b/packages/views/agents/create/use-create-agent-submit.ts
new file mode 100644
index 0000000000..fc3d456634
--- /dev/null
+++ b/packages/views/agents/create/use-create-agent-submit.ts
@@ -0,0 +1,132 @@
+"use client";
+
+import { useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { buildCreateAgentRequest, type AgentDraft } from "@multica/core/agents";
+import { api, ApiError } from "@multica/core/api";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import type { Agent } from "@multica/core/types";
+import { workspaceKeys } from "@multica/core/workspace/queries";
+import { useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+
+interface AgentCreateErrors {
+ nameError: string | null;
+ formError: string | null;
+}
+
+export function classifyAgentCreateError(
+ error: unknown,
+ fallbackMessage: string,
+ conflictMessage: string,
+): AgentCreateErrors {
+ const message =
+ error instanceof Error && error.message ? error.message : fallbackMessage;
+ return error instanceof ApiError && error.status === 409
+ ? { nameError: conflictMessage, formError: null }
+ : { nameError: null, formError: message };
+}
+
+/**
+ * Commits the draft and leaves the creation flow.
+ *
+ * Deliberately not optimistic: the flow navigates away on success, so the agent
+ * has to exist before the destination renders. A failed squad join is reported
+ * as a warning instead of failing the create — the agent is already committed
+ * at that point and a retry would duplicate it.
+ */
+export function useCreateAgentSubmit(options: {
+ draft: AgentDraft;
+ runtimeId: string | null;
+ squadId: string | null;
+ /** Attribution for the `agent_created` event, not a template create. */
+ template?: string;
+ duplicateSource?: Agent | null;
+ /** Runs after the agent is committed, before navigation. */
+ onCreated?: (agent: Agent) => Promise<void> | void;
+}) {
+ const { t } = useT("agents");
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const qc = useQueryClient();
+
+ const [creating, setCreating] = useState(false);
+ const [nameError, setNameError] = useState<string | null>(null);
+ const [formError, setFormError] = useState<string | null>(null);
+
+ const { draft, runtimeId, squadId, template, duplicateSource, onCreated } =
+ options;
+
+ const create = async () => {
+ if (!runtimeId || creating) return;
+ setCreating(true);
+ setNameError(null);
+ setFormError(null);
+ try {
+ const agent = await api.createAgent(
+ buildCreateAgentRequest({
+ draft,
+ runtimeId,
+ template,
+ duplicateSource,
+ }),
+ );
+ if (!agent.id) throw new Error(t(($) => $.creation_studio.create_failed));
+
+ if (squadId) {
+ try {
+ await api.addSquadMember(squadId, {
+ member_type: "agent",
+ member_id: agent.id,
+ });
+ await Promise.all([
+ qc.invalidateQueries({
+ queryKey: [...workspaceKeys.squads(wsId), squadId, "members"],
+ }),
+ qc.invalidateQueries({
+ queryKey: [...workspaceKeys.squads(wsId), squadId],
+ }),
+ ]);
+ } catch (error) {
+ toast.warning(
+ t(($) => $.create_dialog.squad_join_failed_toast, {
+ name: agent.name || draft.name.trim(),
+ error: error instanceof Error ? error.message : "unknown error",
+ }),
+ );
+ }
+ }
+
+ await onCreated?.(agent);
+ await qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ toast.success(
+ t(($) => $.creation_studio.created, {
+ name: agent.name || draft.name.trim(),
+ }),
+ );
+ navigation.push(
+ squadId ? paths.squadDetail(squadId) : paths.agentDetail(agent.id),
+ );
+ } catch (error) {
+ const nextErrors = classifyAgentCreateError(
+ error,
+ t(($) => $.creation_studio.create_failed),
+ t(($) => $.creation_studio.name_conflict),
+ );
+ setNameError(nextErrors.nameError);
+ setFormError(nextErrors.formError);
+ setCreating(false);
+ }
+ };
+
+ return {
+ create,
+ creating,
+ nameError,
+ formError,
+ clearNameError: () => setNameError(null),
+ };
+}
diff --git a/packages/views/agents/components/agent-creation-studio.duplicate-seed.test.tsx b/packages/views/agents/create/use-duplicate-draft-seed.test.tsx
similarity index 96%
rename from packages/views/agents/components/agent-creation-studio.duplicate-seed.test.tsx
rename to packages/views/agents/create/use-duplicate-draft-seed.test.tsx
index aecf8942a1..f72d70f7ba 100644
--- a/packages/views/agents/components/agent-creation-studio.duplicate-seed.test.tsx
+++ b/packages/views/agents/create/use-duplicate-draft-seed.test.tsx
@@ -3,10 +3,8 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, renderHook } from "@testing-library/react";
import type { Agent, RuntimeDevice } from "@multica/core/types";
-import {
- useDuplicateDraftSeed,
- type AgentDraft,
-} from "./agent-creation-studio";
+import type { AgentDraft } from "@multica/core/agents";
+import { useDuplicateDraftSeed } from "./use-duplicate-draft-seed";
const SOURCE_RUNTIME = {
id: "runtime-1",
diff --git a/packages/views/agents/create/use-duplicate-draft-seed.ts b/packages/views/agents/create/use-duplicate-draft-seed.ts
new file mode 100644
index 0000000000..ed09680452
--- /dev/null
+++ b/packages/views/agents/create/use-duplicate-draft-seed.ts
@@ -0,0 +1,62 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+import { buildDuplicateDraft, type AgentDraft } from "@multica/core/agents";
+import type { Agent, RuntimeDevice } from "@multica/core/types";
+
+/**
+ * Seeds the duplicate draft exactly once, and only from a runtime list that has
+ * actually answered.
+ *
+ * The ordering matters: the agent list and the runtime list are independent
+ * queries, so on a cold start (a direct `?duplicate=<id>` link, or a refresh)
+ * the agent can arrive while runtimes are still pending. Seeding then would run
+ * `buildDuplicateDraft` against `[]`, read the source runtime as unavailable,
+ * and clear the model / thinking / speed that a same-runtime copy must keep —
+ * permanently, because seeding happens once. Re-running on every runtime change
+ * instead would overwrite edits the user already made, so the gate is on the
+ * query being decidable rather than on the data changing.
+ */
+export function useDuplicateDraftSeed({
+ source,
+ runtimesSettled,
+ runtimes,
+ currentUserId,
+ fallbackRuntimeId,
+ nameSuffix,
+ onSeed,
+}: {
+ source: Agent | null;
+ /** The runtime query resolved or failed — `false` while it is pending. */
+ runtimesSettled: boolean;
+ runtimes: RuntimeDevice[];
+ currentUserId: string | null;
+ fallbackRuntimeId: string;
+ nameSuffix: string;
+ onSeed: (draft: AgentDraft, runtimeReset: boolean) => void;
+}): void {
+ const seededRef = useRef(false);
+ // The callback is recreated every render by design (it closes over setState),
+ // so keep it out of the effect's dependency list.
+ const onSeedRef = useRef(onSeed);
+ onSeedRef.current = onSeed;
+
+ useEffect(() => {
+ if (seededRef.current || !source || !runtimesSettled) return;
+ seededRef.current = true;
+ const draft = buildDuplicateDraft(source, {
+ runtimes,
+ currentUserId,
+ fallbackRuntimeId,
+ nameSuffix,
+ });
+ onSeedRef.current(draft, draft.runtimeId !== source.runtime_id);
+ }, [
+ currentUserId,
+ fallbackRuntimeId,
+ nameSuffix,
+ runtimes,
+ runtimesSettled,
+ source,
+ ]);
+}
diff --git a/packages/views/agents/create/use-manual-draft-sync.test.tsx b/packages/views/agents/create/use-manual-draft-sync.test.tsx
new file mode 100644
index 0000000000..66f023524a
--- /dev/null
+++ b/packages/views/agents/create/use-manual-draft-sync.test.tsx
@@ -0,0 +1,87 @@
+// @vitest-environment jsdom
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, renderHook } from "@testing-library/react";
+import {
+ EMPTY_AGENT_DRAFT,
+ toStoredAgentDraft,
+ useManualAgentDraftStore,
+ type AgentDraft,
+} from "@multica/core/agents";
+import { useManualDraftSync } from "./use-manual-draft-sync";
+
+function seedStoredDraft(owner: string, name: string) {
+ useManualAgentDraftStore.getState().setDraft({
+ byOwner: {
+ [owner]: {
+ runtimeId: "runtime-1",
+ draft: toStoredAgentDraft({ ...EMPTY_AGENT_DRAFT, name }, null),
+ },
+ },
+ });
+}
+
+function mountSync(duplicateId: string | null, draft: AgentDraft) {
+ const setDraft = vi.fn();
+ const view = renderHook(() =>
+ useManualDraftSync({ duplicateId, draft, setDraft, ready: true }),
+ );
+ return { setDraft, view };
+}
+
+afterEach(() => {
+ cleanup();
+ useManualAgentDraftStore.getState().clearDraft();
+});
+
+describe("useManualDraftSync", () => {
+ it("restores the draft belonging to this flow", () => {
+ seedStoredDraft("duplicate:agent-A", "Half-finished copy of A");
+
+ const { setDraft } = mountSync("agent-A", EMPTY_AGENT_DRAFT);
+
+ expect(setDraft).toHaveBeenCalledTimes(1);
+ expect(setDraft.mock.calls[0]?.[0]).toMatchObject({
+ name: "Half-finished copy of A",
+ runtimeId: "runtime-1",
+ });
+ });
+
+ // The regression: opening a second flow used to write its own blank form over
+ // the first one's slot, destroying it before the user typed anything.
+ it("does not touch another flow's draft when it opens", () => {
+ seedStoredDraft("duplicate:agent-A", "Half-finished copy of A");
+
+ const { setDraft } = mountSync(null, EMPTY_AGENT_DRAFT);
+
+ expect(setDraft).not.toHaveBeenCalled();
+ expect(
+ useManualAgentDraftStore.getState().draft.byOwner["duplicate:agent-A"]
+ ?.draft.name,
+ ).toBe("Half-finished copy of A");
+ });
+
+ it("does not adopt another flow's draft either", () => {
+ seedStoredDraft("duplicate:agent-A", "Half-finished copy of A");
+
+ const { setDraft } = mountSync("agent-B", EMPTY_AGENT_DRAFT);
+
+ expect(setDraft).not.toHaveBeenCalled();
+ expect(
+ useManualAgentDraftStore.getState().draft.byOwner["duplicate:agent-A"]
+ ?.draft.name,
+ ).toBe("Half-finished copy of A");
+ });
+
+ it("stores this flow's own edits beside the others", () => {
+ seedStoredDraft("duplicate:agent-A", "Half-finished copy of A");
+
+ mountSync(null, { ...EMPTY_AGENT_DRAFT, name: "A blank one" });
+
+ const byOwner = useManualAgentDraftStore.getState().draft.byOwner;
+ expect(byOwner.blank?.draft.name).toBe("A blank one");
+ expect(byOwner["duplicate:agent-A"]?.draft.name).toBe(
+ "Half-finished copy of A",
+ );
+ });
+});
diff --git a/packages/views/agents/create/use-manual-draft-sync.ts b/packages/views/agents/create/use-manual-draft-sync.ts
new file mode 100644
index 0000000000..55211a1361
--- /dev/null
+++ b/packages/views/agents/create/use-manual-draft-sync.ts
@@ -0,0 +1,78 @@
+"use client";
+
+import {
+ useEffect,
+ useState,
+ type Dispatch,
+ type SetStateAction,
+} from "react";
+import {
+ fromStoredAgentDraft,
+ manualDraftOwner,
+ setManualDraftEntry,
+ toStoredAgentDraft,
+ useManualAgentDraftStore,
+ type AgentDraft,
+} from "@multica/core/agents";
+
+/**
+ * Keeps the manual creation form across navigation (#6287).
+ *
+ * The reported bug is a tab switch: the desktop shell mounts only the active
+ * tab, so coming back is a remount and everything typed was gone. A route
+ * change and a reload lose it the same way, so the fix has to be persistence,
+ * not a guard on one exit.
+ *
+ * Two orderings matter here, and both were bugs before they were rules:
+ *
+ * - Restore runs before save is armed. A write fired while the form still
+ * held its empty initial state would overwrite the stored draft with
+ * nothing — turning "come back to my form" into "lose my form".
+ * - Writes are scoped to this flow's own slot. Opening a blank form must not
+ * erase a half-finished copy of some agent, and vice versa; the store keys
+ * drafts by owner precisely so one flow cannot answer for another.
+ */
+export function useManualDraftSync(options: {
+ duplicateId: string | null;
+ draft: AgentDraft;
+ setDraft: Dispatch<SetStateAction<AgentDraft>>;
+ /** False until a duplicate has finished seeding; saving before then would
+ * persist the empty form the seed is about to replace. */
+ ready: boolean;
+}): void {
+ const { duplicateId, draft, setDraft, ready } = options;
+ const owner = manualDraftOwner(duplicateId);
+
+ const setStored = useManualAgentDraftStore((state) => state.setDraft);
+ const [restored, setRestored] = useState(false);
+
+ useEffect(() => {
+ if (restored || !ready) return;
+ // Read at apply time rather than subscribing: this runs once, and a
+ // subscription would re-fire it on every keystroke's own write.
+ const persisted = useManualAgentDraftStore.getState().draft.byOwner[owner];
+ if (persisted) {
+ setDraft(fromStoredAgentDraft(persisted.draft, persisted.runtimeId));
+ }
+ setRestored(true);
+ }, [owner, ready, restored, setDraft]);
+
+ useEffect(() => {
+ if (!restored) return;
+ const current = useManualAgentDraftStore.getState().draft;
+ setStored(
+ setManualDraftEntry(current, owner, {
+ runtimeId: draft.runtimeId,
+ draft: toStoredAgentDraft(draft, null),
+ }),
+ );
+ }, [draft, owner, restored, setStored]);
+}
+
+/** Drops this flow's slot once its agent exists, leaving other flows alone. */
+export function clearManualDraftForOwner(duplicateId: string | null): void {
+ const store = useManualAgentDraftStore.getState();
+ store.setDraft(
+ setManualDraftEntry(store.draft, manualDraftOwner(duplicateId), null),
+ );
+}
diff --git a/packages/views/agents/index.ts b/packages/views/agents/index.ts
index 1c73d0d314..66fbb70a8a 100644
--- a/packages/views/agents/index.ts
+++ b/packages/views/agents/index.ts
@@ -1 +1,6 @@
-export { AgentsPage, AgentDetailPage, AgentCreationStudio } from "./components";
+export { AgentsPage, AgentDetailPage } from "./components";
+export {
+ ChooseCreateMethodPage,
+ ManualCreateAgentPage,
+ AiCreateAgentPage,
+} from "./create";
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index eb4a7f4e76..30ccad9c95 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -281,11 +281,10 @@
"back": "Go back",
"eyebrow": "Agent creation",
"choose_title": "How would you like to start?",
- "choose_description": "Start with full control, adapt a proven template, or describe what you need and build it through conversation.",
+ "choose_description": "Start with full control, or describe what you need and build it through conversation.",
"recommended": "Recommended",
"continue": "Continue",
"step_choose": "Choose a starting point",
- "step_template": "Choose a template",
"step_configure": "Review and configure",
"step_ai": "Build through conversation",
"modes": {
@@ -302,15 +301,6 @@
"description": "Describe the outcome you want. An Agent Builder will ask focused questions and prepare a live draft."
}
},
- "templates": {
- "search": "Search templates…",
- "search_label": "Search agent templates",
- "empty": "No templates match your search.",
- "select_hint": "Select a template to preview its instructions and skills.",
- "skills": "Included skills",
- "instructions": "Instructions",
- "use": "Use this template"
- },
"sections": {
"identity": "Identity",
"identity_hint": "Give the agent a recognizable name and a concise purpose.",
@@ -371,7 +361,17 @@
"creating": "Creating agent…",
"create_failed": "Could not create the agent.",
"name_conflict": "An agent with this name already exists.",
- "created": "{{name}} was created"
+ "created": "{{name}} was created",
+ "drafts": {
+ "title": "Drafts",
+ "untitled": "Untitled draft",
+ "discard": "Discard",
+ "discard_confirm": "The conversation and its configuration are deleted permanently.",
+ "discard_title": "Discard this draft?",
+ "discard_cancel": "Keep editing",
+ "banner": "You have {{count}} unfinished draft(s)",
+ "pick_hint": "Pick one to continue."
+ }
},
"create_dialog": {
"title_create": "Create Agent",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index a28f0b86b0..e06622d52c 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -740,11 +740,10 @@
"back": "戻る",
"eyebrow": "エージェント作成",
"choose_title": "どの方法で始めますか?",
- "choose_description": "すべて自分で設定するか、実績のあるテンプレートを調整するか、必要なものを説明して会話から作成できます。",
+ "choose_description": "すべて自分で設定するか、必要なものを説明して会話から作成できます。",
"recommended": "おすすめ",
"continue": "続ける",
"step_choose": "開始方法を選択",
- "step_template": "テンプレートを選択",
"step_configure": "確認して設定",
"step_ai": "会話で作成",
"modes": {
@@ -761,15 +760,6 @@
"description": "期待する成果を説明すると、Agent Builder が重要な質問を行い、下書きをリアルタイムで作成します。"
}
},
- "templates": {
- "search": "テンプレートを検索…",
- "search_label": "エージェントテンプレートを検索",
- "empty": "検索に一致するテンプレートはありません。",
- "select_hint": "テンプレートを選択して、指示とスキルをプレビューします。",
- "skills": "含まれるスキル",
- "instructions": "指示",
- "use": "このテンプレートを使用"
- },
"sections": {
"identity": "基本情報",
"identity_hint": "識別しやすい名前と簡潔な目的を設定します。",
@@ -830,7 +820,17 @@
"creating": "エージェントを作成中…",
"create_failed": "エージェントを作成できませんでした。",
"name_conflict": "同じ名前のエージェントがすでに存在します。",
- "created": "{{name}} を作成しました"
+ "created": "{{name}} を作成しました",
+ "drafts": {
+ "title": "下書き",
+ "untitled": "無題の下書き",
+ "discard": "作成を破棄",
+ "discard_confirm": "会話と右側の設定は完全に削除されます。",
+ "discard_title": "この作成を破棄しますか?",
+ "discard_cancel": "編集を続ける",
+ "banner": "未完了の下書きが {{count}} 件あります",
+ "pick_hint": "続きを選んでください。"
+ }
},
"actions": {
"selected_other": "{{count}} 件選択中",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 4af7f3744d..7c1972ac9d 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -740,11 +740,10 @@
"back": "뒤로",
"eyebrow": "에이전트 만들기",
"choose_title": "어떻게 시작하시겠어요?",
- "choose_description": "모든 항목을 직접 설정하거나, 검증된 템플릿을 수정하거나, 필요한 내용을 설명하고 대화로 만들 수 있습니다.",
+ "choose_description": "모든 항목을 직접 설정하거나, 필요한 내용을 설명하고 대화로 만들 수 있습니다.",
"recommended": "추천",
"continue": "계속",
"step_choose": "시작 방법 선택",
- "step_template": "템플릿 선택",
"step_configure": "검토 및 설정",
"step_ai": "대화로 만들기",
"modes": {
@@ -761,15 +760,6 @@
"description": "원하는 결과를 설명하면 Agent Builder가 핵심 질문을 하고 실시간 초안을 준비합니다."
}
},
- "templates": {
- "search": "템플릿 검색…",
- "search_label": "에이전트 템플릿 검색",
- "empty": "검색과 일치하는 템플릿이 없습니다.",
- "select_hint": "템플릿을 선택하여 지침과 스킬을 미리 확인하세요.",
- "skills": "포함된 스킬",
- "instructions": "지침",
- "use": "이 템플릿 사용"
- },
"sections": {
"identity": "기본 정보",
"identity_hint": "알아보기 쉬운 이름과 간결한 목적을 지정하세요.",
@@ -830,7 +820,17 @@
"creating": "에이전트 만드는 중…",
"create_failed": "에이전트를 만들지 못했습니다.",
"name_conflict": "같은 이름의 에이전트가 이미 있습니다.",
- "created": "{{name}}을(를) 만들었습니다"
+ "created": "{{name}}을(를) 만들었습니다",
+ "drafts": {
+ "title": "초안",
+ "untitled": "제목 없는 초안",
+ "discard": "생성 취소",
+ "discard_confirm": "대화와 오른쪽 설정이 영구적으로 삭제됩니다.",
+ "discard_title": "이 생성을 취소할까요?",
+ "discard_cancel": "계속 편집",
+ "banner": "미완료 초안이 {{count}}개 있습니다",
+ "pick_hint": "이어서 진행할 항목을 선택하세요."
+ }
},
"actions": {
"selected_other": "{{count}}개 선택됨",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index db62668304..a2c7b0599d 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -272,11 +272,10 @@
"back": "返回",
"eyebrow": "创建智能体",
"choose_title": "你想从哪里开始?",
- "choose_description": "从空白配置、基于成熟模板修改,或者直接描述需求,通过对话完成创建。",
+ "choose_description": "从空白配置开始,或者直接描述需求,通过对话完成创建。",
"recommended": "推荐",
"continue": "继续",
"step_choose": "选择起点",
- "step_template": "选择模板",
"step_configure": "检查并配置",
"step_ai": "通过对话创建",
"modes": {
@@ -293,15 +292,6 @@
"description": "描述你想要的结果。Agent Builder 会提出关键问题并实时生成草稿。"
}
},
- "templates": {
- "search": "搜索模板…",
- "search_label": "搜索智能体模板",
- "empty": "没有匹配的模板。",
- "select_hint": "选择一个模板,预览它的指令和 skill。",
- "skills": "包含的 skill",
- "instructions": "指令",
- "use": "使用此模板"
- },
"sections": {
"identity": "身份",
"identity_hint": "为智能体设置容易识别的名称和简洁的用途。",
@@ -362,7 +352,17 @@
"creating": "正在创建…",
"create_failed": "无法创建智能体。",
"name_conflict": "工作区中已存在同名智能体。",
- "created": "已创建 {{name}}"
+ "created": "已创建 {{name}}",
+ "drafts": {
+ "title": "创建草稿",
+ "untitled": "未命名草稿",
+ "discard": "放弃创建",
+ "discard_confirm": "对话和右侧配置都会被永久删除。",
+ "discard_title": "放弃这次创建?",
+ "discard_cancel": "继续编辑",
+ "banner": "您有 {{count}} 条未完成的创建",
+ "pick_hint": "选一条继续。"
+ }
},
"create_dialog": {
"title_create": "创建智能体",
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 82e2f328d4..a6de9574cc 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1339,8 +1339,15 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/{slug}", h.GetAgentTemplate)
})
r.Route("/api/agent-builder/sessions", func(r chi.Router) {
+ // The creation studio's unfinished drafts. Builder sessions are
+ // invisible to every chat list (their carrier is kind='system'),
+ // so this is the only route back to one.
+ r.Get("/", h.ListAgentBuilderSessions)
r.Post("/", h.CreateAgentBuilderSession)
r.Patch("/{sessionId}/runtime", h.SwitchAgentBuilderRuntime)
+ // Autosaved configuration, including edits the user has typed
+ // but not sent. Read back through the list above.
+ r.Put("/{sessionId}/draft", h.SaveAgentBuilderDraft)
})
// Skills
diff --git a/server/internal/handler/agent_builder.go b/server/internal/handler/agent_builder.go
index 31aa6a2db5..803108bedd 100644
--- a/server/internal/handler/agent_builder.go
+++ b/server/internal/handler/agent_builder.go
@@ -142,6 +142,156 @@ func (h *Handler) CreateAgentBuilderSession(w http.ResponseWriter, r *http.Reque
})
}
+// AgentBuilderSessionSummary is one unfinished agent-creation conversation.
+type AgentBuilderSessionSummary struct {
+ SessionID string `json:"session_id"`
+ Title string `json:"title"`
+ // RuntimeID is the carrier's runtime — where this conversation actually
+ // executes. The client seeds its runtime picker from it so the picker can
+ // never disagree with what answers the next message (MUL-5163).
+ RuntimeID string `json:"runtime_id"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+ // LastMessageContent is the raw stored message, still in the builder's wire
+ // format (the user side is a JSON envelope, the assistant side carries an
+ // <agent_draft> block). Decoding is the client's job: the protocol is
+ // defined by the studio and its prompt, and duplicating it here would give
+ // it a second, silently divergent implementation.
+ LastMessageContent string `json:"last_message_content"`
+ LastMessageRole string `json:"last_message_role"`
+ LastMessageAt string `json:"last_message_at"`
+ // Draft is the stored configuration, opaque to the server (see migration
+ // 252). It ships with the list rather than behind its own fetch because the
+ // studio renders this list beside the conversation it switches between, so
+ // the picked row's configuration must be in hand at click time. Null when
+ // the conversation has only ever been driven by the AI — the client then
+ // replays the last <agent_draft> block instead.
+ Draft json.RawMessage `json:"draft,omitempty"`
+}
+
+type ListAgentBuilderSessionsResponse struct {
+ Sessions []AgentBuilderSessionSummary `json:"sessions"`
+}
+
+// ListAgentBuilderSessions returns the caller's unfinished agent-creation
+// conversations, newest activity first.
+//
+// This is the only way back to a builder session: they are hidden from every
+// chat surface by the `kind = 'user'` agent filter, so before this endpoint the
+// studio had to delete one on navigation or leak it forever. Creator-scoped
+// like every other chat read — a workspace admin cannot list someone else's
+// drafts, matching loadChatSessionForUser's rule.
+func (h *Handler) ListAgentBuilderSessions(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+
+ rows, err := h.Queries.ListAgentBuilderSessionsByCreator(r.Context(), db.ListAgentBuilderSessionsByCreatorParams{
+ WorkspaceID: workspaceUUID,
+ CreatorID: parseUUID(userID),
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list agent builder sessions")
+ return
+ }
+
+ sessions := make([]AgentBuilderSessionSummary, 0, len(rows))
+ for _, row := range rows {
+ sessions = append(sessions, AgentBuilderSessionSummary{
+ SessionID: uuidToString(row.ID),
+ Title: row.Title,
+ RuntimeID: uuidToString(row.RuntimeID),
+ CreatedAt: timestampToString(row.CreatedAt),
+ UpdatedAt: timestampToString(row.UpdatedAt),
+ LastMessageContent: row.LastMessageContent,
+ LastMessageRole: row.LastMessageRole,
+ LastMessageAt: timestampToString(row.LastMessageAt),
+ Draft: json.RawMessage(row.StoredDraft),
+ })
+ }
+ writeJSON(w, http.StatusOK, ListAgentBuilderSessionsResponse{Sessions: sessions})
+}
+
+// maxAgentBuilderDraftBytes bounds one stored configuration. The largest honest
+// field is the instruction markdown, which the create API itself caps well
+// below this; the limit exists so a client bug cannot grow an unbounded row.
+const maxAgentBuilderDraftBytes = 256 * 1024
+
+type SaveAgentBuilderDraftRequest struct {
+ Draft json.RawMessage `json:"draft"`
+}
+
+// SaveAgentBuilderDraft stores the configuration a creation conversation has
+// arrived at, including the edits the user typed but has not sent.
+//
+// The payload is opaque (see migration 252): its shape is the studio's
+// AgentDraft, validated client-side, and nothing server-side reads a field.
+// Whole-object last-write-wins is correct here because a conversation has one
+// editor on one screen — a field-level merge could only reconstruct a state the
+// user never saw.
+func (h *Handler) SaveAgentBuilderDraft(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ var req SaveAgentBuilderDraftRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if len(req.Draft) == 0 {
+ writeError(w, http.StatusBadRequest, "draft is required")
+ return
+ }
+ if len(req.Draft) > maxAgentBuilderDraftBytes {
+ writeError(w, http.StatusRequestEntityTooLarge, "draft is too large")
+ return
+ }
+ if !json.Valid(req.Draft) {
+ writeError(w, http.StatusBadRequest, "draft must be valid JSON")
+ return
+ }
+
+ // Creator-only, and only for a builder carrier — the same two gates the
+ // runtime switch applies. Without the carrier check this would be a way to
+ // hang arbitrary JSON off any chat session the caller owns.
+ 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
+ }
+ 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
+ }
+
+ if _, err := h.Queries.UpsertAgentBuilderDraft(r.Context(), db.UpsertAgentBuilderDraftParams{
+ ChatSessionID: session.ID,
+ WorkspaceID: session.WorkspaceID,
+ Draft: req.Draft,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to save agent builder draft")
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
// 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,
diff --git a/server/internal/handler/agent_builder_test.go b/server/internal/handler/agent_builder_test.go
index d8d4079848..bef4e5bdfb 100644
--- a/server/internal/handler/agent_builder_test.go
+++ b/server/internal/handler/agent_builder_test.go
@@ -358,6 +358,322 @@ func TestSwitchAgentBuilderRuntimeRejectsNonBuilderSession(t *testing.T) {
}
}
+func listBuilderSessions(t *testing.T) ListAgentBuilderSessionsResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ testHandler.ListAgentBuilderSessions(w, newRequest(http.MethodGet, "/api/agent-builder/sessions", nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("ListAgentBuilderSessions: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var response ListAgentBuilderSessionsResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode list response: %v", err)
+ }
+ return response
+}
+
+func insertChatMessage(t *testing.T, sessionID, role, content string) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO chat_message (chat_session_id, role, content)
+ VALUES ($1, $2, $3)
+ `, sessionID, role, content); err != nil {
+ t.Fatalf("insert chat message: %v", err)
+ }
+}
+
+// The studio stopped deleting builder sessions on navigation, so this list is
+// the only route back to one. It must carry the carrier's runtime: the client
+// seeds its picker from it, and a wrong answer reintroduces MUL-5163 (picker
+// shows A while every message runs on B).
+func TestListAgentBuilderSessionsReturnsCarrierRuntime(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ session := newBuilderSession(t)
+ insertChatMessage(t, session.SessionID, "user", "Create a release manager")
+
+ response := listBuilderSessions(t)
+
+ var found *AgentBuilderSessionSummary
+ for i := range response.Sessions {
+ if response.Sessions[i].SessionID == session.SessionID {
+ found = &response.Sessions[i]
+ break
+ }
+ }
+ if found == nil {
+ t.Fatalf("builder session %s missing from the list", session.SessionID)
+ }
+ if found.RuntimeID != testRuntimeID {
+ t.Fatalf("runtime_id = %q, want the carrier's runtime %q", found.RuntimeID, testRuntimeID)
+ }
+ if found.LastMessageContent != "Create a release manager" {
+ t.Fatalf("last_message_content = %q", found.LastMessageContent)
+ }
+ if found.LastMessageRole != "user" {
+ t.Fatalf("last_message_role = %q, want user", found.LastMessageRole)
+ }
+}
+
+func saveBuilderDraft(t *testing.T, sessionID string, draft any) *httptest.ResponseRecorder {
+ t.Helper()
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(),
+ `DELETE FROM agent_builder_draft WHERE chat_session_id = $1`, sessionID)
+ })
+ w := httptest.NewRecorder()
+ req := withURLParams(
+ newRequest(http.MethodPut, "/api/agent-builder/sessions/"+sessionID+"/draft",
+ map[string]any{"draft": draft}),
+ "sessionId", sessionID,
+ )
+ testHandler.SaveAgentBuilderDraft(w, req)
+ return w
+}
+
+// The half of the configuration the user types by hand had no durable home
+// before this: it lived in React state and died on every reload. The list is
+// where it comes back, so the two have to be tested together.
+func TestSaveAgentBuilderDraftRoundTripsThroughTheList(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ session := newBuilderSession(t)
+ insertChatMessage(t, session.SessionID, "user", "Create a release manager")
+
+ if w := saveBuilderDraft(t, session.SessionID, map[string]any{
+ "name": "Release manager",
+ "instructions": "Ship carefully",
+ }); w.Code != http.StatusNoContent {
+ t.Fatalf("SaveAgentBuilderDraft: expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+
+ for _, summary := range listBuilderSessions(t).Sessions {
+ if summary.SessionID != session.SessionID {
+ continue
+ }
+ var stored map[string]any
+ if err := json.Unmarshal(summary.Draft, &stored); err != nil {
+ t.Fatalf("decode stored draft %q: %v", string(summary.Draft), err)
+ }
+ if stored["name"] != "Release manager" {
+ t.Fatalf("stored draft name = %v", stored["name"])
+ }
+ return
+ }
+ t.Fatalf("builder session %s missing from the list", session.SessionID)
+}
+
+// One conversation has one current configuration. Accumulating rows per save
+// would make "which one is current" a question the read path has to answer.
+func TestSaveAgentBuilderDraftOverwritesInPlace(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ session := newBuilderSession(t)
+
+ saveBuilderDraft(t, session.SessionID, map[string]any{"name": "First"})
+ saveBuilderDraft(t, session.SessionID, map[string]any{"name": "Second"})
+
+ var rows int
+ var name string
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*), max(draft->>'name') FROM agent_builder_draft WHERE chat_session_id = $1
+ `, session.SessionID).Scan(&rows, &name); err != nil {
+ t.Fatalf("read stored drafts: %v", err)
+ }
+ if rows != 1 {
+ t.Fatalf("stored draft rows = %d, want exactly one per conversation", rows)
+ }
+ if name != "Second" {
+ t.Fatalf("stored draft name = %q, want the latest save", name)
+ }
+}
+
+// Without the carrier gate this endpoint would be a way to hang arbitrary JSON
+// off any chat session the caller happens to own.
+func TestSaveAgentBuilderDraftRejectsNonBuilderSession(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ 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 Draft 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, 'Ordinary chat', $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 := saveBuilderDraft(t, userSessionID, map[string]any{"name": "X"}); w.Code != http.StatusNotFound {
+ t.Fatalf("ordinary chat: expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+// agent_builder_draft carries no chat_session FK, so nothing reclaims the row
+// on its own. A draft outliving its conversation is a leak the user can never
+// see, let alone clear.
+func TestDeleteChatSessionPrunesTheBuilderDraft(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ session := newBuilderSession(t)
+ saveBuilderDraft(t, session.SessionID, map[string]any{"name": "Doomed"})
+
+ w := httptest.NewRecorder()
+ req := withURLParams(
+ newRequest(http.MethodDelete, "/api/chat/sessions/"+session.SessionID, nil),
+ "sessionId", session.SessionID,
+ )
+ // DeleteChatSession reads the workspace off the context the middleware
+ // normally fills, not the header.
+ req = withChatTestWorkspaceCtx(t, req)
+ testHandler.DeleteChatSession(w, req)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteChatSession: expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var remaining int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_builder_draft WHERE chat_session_id = $1
+ `, session.SessionID).Scan(&remaining); err != nil {
+ t.Fatalf("count stored drafts: %v", err)
+ }
+ if remaining != 0 {
+ t.Fatalf("stored draft rows after delete = %d, want 0", remaining)
+ }
+}
+
+// A rebind moves the carrier without touching chat_session.runtime_id, which is
+// deliberately left stale as the daemon's resume pointer. Reading the list from
+// that column instead of the carrier would resume the conversation onto a
+// runtime that no longer executes anything.
+func TestListAgentBuilderSessionsFollowsARuntimeSwitch(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ session := newBuilderSession(t)
+ insertChatMessage(t, session.SessionID, "user", "Create a release manager")
+ target := newTestRuntime(t, "Builder List Switch Target", "online")
+
+ if w := switchBuilderRuntime(t, session.SessionID, target); w.Code != http.StatusOK {
+ t.Fatalf("SwitchAgentBuilderRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ for _, summary := range listBuilderSessions(t).Sessions {
+ if summary.SessionID != session.SessionID {
+ continue
+ }
+ if summary.RuntimeID != target {
+ t.Fatalf("runtime_id = %q after switch, want %q", summary.RuntimeID, target)
+ }
+ return
+ }
+ t.Fatalf("builder session %s missing from the list", session.SessionID)
+}
+
+// A session opened and abandoned untouched is not a draft. Listing it would put
+// an empty row in front of the user on every accidental entry into the flow.
+func TestListAgentBuilderSessionsSkipsUntouchedConversations(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ session := newBuilderSession(t)
+
+ for _, summary := range listBuilderSessions(t).Sessions {
+ if summary.SessionID == session.SessionID {
+ t.Fatalf("untouched builder session %s must not be listed", session.SessionID)
+ }
+ }
+}
+
+// The configuration form is editable from the moment the session exists and
+// autosaves, so a user can open the builder, type a name and leave before the
+// first turn. Keying "is this a draft" on messages alone made that work
+// unreachable: the row existed and nothing could reach it.
+func TestListAgentBuilderSessionsIncludesASavedDraftWithNoMessages(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ session := newBuilderSession(t)
+ saveBuilderDraft(t, session.SessionID, map[string]any{"name": "Typed but never sent"})
+
+ for _, summary := range listBuilderSessions(t).Sessions {
+ if summary.SessionID != session.SessionID {
+ continue
+ }
+ if summary.LastMessageContent != "" || summary.LastMessageRole != "" {
+ t.Fatalf("expected an empty last message, got %q/%q",
+ summary.LastMessageRole, summary.LastMessageContent)
+ }
+ if summary.RuntimeID != testRuntimeID {
+ t.Fatalf("runtime_id = %q, want the carrier's runtime %q", summary.RuntimeID, testRuntimeID)
+ }
+ return
+ }
+ t.Fatalf("builder session %s with a saved draft is missing from the list", session.SessionID)
+}
+
+// Ordinary chats must never leak into the creation-draft list: their carrier is
+// a user agent, and the studio would try to resume a conversation it cannot
+// drive.
+func TestListAgentBuilderSessionsExcludesOrdinaryChats(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ 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 List 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, 'Ordinary chat', $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_message WHERE chat_session_id = $1`, userSessionID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, userSessionID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, userAgentID)
+ })
+ insertChatMessage(t, userSessionID, "user", "Hello")
+
+ for _, summary := range listBuilderSessions(t).Sessions {
+ if summary.SessionID == userSessionID {
+ t.Fatalf("ordinary chat %s must not appear as a creation draft", userSessionID)
+ }
+ }
+}
+
// 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
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index f97504c7c4..513cf72271 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -626,6 +626,13 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {
return
}
+ // Same no-FK chore, for the agent configuration a builder conversation was
+ // editing. A no-op for ordinary chats, which never have one.
+ if err := qtx.DeleteAgentBuilderDraft(r.Context(), session.ID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete agent builder draft")
+ return
+ }
+
if err := qtx.DeleteChatSession(r.Context(), db.DeleteChatSessionParams{
ID: session.ID,
WorkspaceID: session.WorkspaceID,
@@ -1264,7 +1271,12 @@ func pruneRuntimeSystemAgentChatDraftRestores(ctx context.Context, q *db.Queries
if _, err := q.LockChatSessionsBySystemRuntimeAgents(ctx, runtimeID); err != nil {
return err
}
- return q.DeleteChatDraftRestoresBySystemRuntimeAgents(ctx, runtimeID)
+ if err := q.DeleteChatDraftRestoresBySystemRuntimeAgents(ctx, runtimeID); err != nil {
+ return err
+ }
+ // Builder drafts only ever hang off a system carrier, so they are pruned
+ // here and nowhere else — the archived-agent sweep above has none to find.
+ return q.DeleteAgentBuilderDraftsBySystemRuntimeAgents(ctx, runtimeID)
}
// PendingChatTasksResponse is the aggregate view consumed by the FAB.
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index fbfc28f168..ce439fadaf 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -21,6 +21,7 @@ const (
var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"activity_log": workspaceDelete,
"agent": workspaceDelete,
+ "agent_builder_draft": workspaceDelete,
"agent_invocation_target": workspaceDelete,
"agent_runtime": workspaceDelete,
"agent_skill": workspaceDelete,
diff --git a/server/migrations/252_agent_builder_draft.down.sql b/server/migrations/252_agent_builder_draft.down.sql
new file mode 100644
index 0000000000..faffbef0d3
--- /dev/null
+++ b/server/migrations/252_agent_builder_draft.down.sql
@@ -0,0 +1,4 @@
+-- Rolling back returns the studio to replaying the last <agent_draft> block out
+-- of chat_message, which is where the AI's half of the configuration still
+-- lives. Only edits the user typed and never sent are lost.
+DROP TABLE IF EXISTS agent_builder_draft;
diff --git a/server/migrations/252_agent_builder_draft.up.sql b/server/migrations/252_agent_builder_draft.up.sql
new file mode 100644
index 0000000000..3613c4dd24
--- /dev/null
+++ b/server/migrations/252_agent_builder_draft.up.sql
@@ -0,0 +1,35 @@
+-- The agent configuration a creation conversation has arrived at.
+--
+-- Half of this state was already durable: every reply from the builder ends in
+-- an <agent_draft> block, so the client could always replay the last one out of
+-- chat_message. What was not durable is the half the USER types — a rewritten
+-- instruction, an unticked skill — which lived only in React state and died on
+-- every reload, tab switch and navigation. Splitting one configuration across
+-- "the AI's half on the server, yours in the browser" also forced the client to
+-- arbitrate between the two on every restore. This table makes the whole thing
+-- one server-owned object.
+--
+-- `draft` is opaque to the server. The shape is the studio's AgentDraft and is
+-- validated client-side against a zod schema; teaching Postgres and the handler
+-- about it would create a second definition to keep in sync for no gain, since
+-- nothing server-side ever reads a field. The client also stores which
+-- assistant message it has already applied, so a restore does not re-apply the
+-- last reply over edits made after it.
+--
+-- No foreign key (repo rule), so deletion is explicit in application code —
+-- DeleteChatSession, the runtime teardown agent cascade, and the workspace
+-- teardown each prune this table, exactly as they already do for
+-- chat_draft_restore.
+--
+-- chat_session_id is the primary key rather than a surrogate id: a conversation
+-- has exactly one current draft, and making that a constraint means the write
+-- path is a plain upsert with no room for duplicate rows to accumulate. It also
+-- provides the lookup index, so no separate CREATE INDEX CONCURRENTLY is needed.
+CREATE TABLE agent_builder_draft (
+ chat_session_id UUID PRIMARY KEY,
+ -- Denormalised so the workspace teardown can prune without joining through
+ -- chat_session, which that statement deletes in the same CTE.
+ workspace_id UUID NOT NULL,
+ draft JSONB NOT NULL DEFAULT '{}'::jsonb,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/pkg/db/generated/agent_builder.sql.go b/server/pkg/db/generated/agent_builder.sql.go
new file mode 100644
index 0000000000..660e35459c
--- /dev/null
+++ b/server/pkg/db/generated/agent_builder.sql.go
@@ -0,0 +1,75 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: agent_builder.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const deleteAgentBuilderDraft = `-- name: DeleteAgentBuilderDraft :exec
+DELETE FROM agent_builder_draft WHERE chat_session_id = $1
+`
+
+// agent_builder_draft has no chat_session FK (repo rule), so every path that
+// removes a conversation has to say so explicitly.
+func (q *Queries) DeleteAgentBuilderDraft(ctx context.Context, chatSessionID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteAgentBuilderDraft, chatSessionID)
+ return err
+}
+
+const deleteAgentBuilderDraftsBySystemRuntimeAgents = `-- name: DeleteAgentBuilderDraftsBySystemRuntimeAgents :exec
+DELETE FROM agent_builder_draft
+WHERE chat_session_id IN (
+ SELECT cs.id FROM chat_session cs
+ JOIN agent a ON a.id = cs.agent_id
+ WHERE a.runtime_id = $1 AND a.kind = 'system'
+)
+`
+
+// chat_session cascades from agent, so a runtime teardown hard-deleting its
+// system carriers (DeleteSystemAgentsByRuntime) silently drops their sessions.
+// Prune the drafts in the same tx and BEFORE the agent rows go — the join below
+// needs them. Mirrors DeleteChatDraftRestoresBySystemRuntimeAgents.
+//
+// Only the system variant exists: a builder draft can only ever hang off a
+// `kind = 'system'` carrier, so the archived-agent prune has nothing to find.
+func (q *Queries) DeleteAgentBuilderDraftsBySystemRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteAgentBuilderDraftsBySystemRuntimeAgents, runtimeID)
+ return err
+}
+
+const upsertAgentBuilderDraft = `-- name: UpsertAgentBuilderDraft :one
+INSERT INTO agent_builder_draft (chat_session_id, workspace_id, draft)
+VALUES ($1, $2, $3)
+ON CONFLICT (chat_session_id) DO UPDATE
+SET draft = EXCLUDED.draft,
+ updated_at = now()
+RETURNING chat_session_id, workspace_id, draft, updated_at
+`
+
+type UpsertAgentBuilderDraftParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Draft []byte `json:"draft"`
+}
+
+// The current configuration of one creation conversation. Last write wins:
+// there is a single editor (the session's creator, on one screen at a time) and
+// the client autosaves the whole object, so a partial merge would only be able
+// to reconstruct a state the user never saw.
+func (q *Queries) UpsertAgentBuilderDraft(ctx context.Context, arg UpsertAgentBuilderDraftParams) (AgentBuilderDraft, error) {
+ row := q.db.QueryRow(ctx, upsertAgentBuilderDraft, arg.ChatSessionID, arg.WorkspaceID, arg.Draft)
+ var i AgentBuilderDraft
+ err := row.Scan(
+ &i.ChatSessionID,
+ &i.WorkspaceID,
+ &i.Draft,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 9dcc23250f..dc0f1dee6a 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -960,6 +960,113 @@ func (q *Queries) LinkUnownedChannelChatMessagesToTask(ctx context.Context, arg
return err
}
+const listAgentBuilderSessionsByCreator = `-- name: ListAgentBuilderSessionsByCreator :many
+SELECT cs.id,
+ cs.title,
+ cs.created_at,
+ cs.updated_at,
+ a.runtime_id,
+ COALESCE(lm.content, '') AS last_message_content,
+ COALESCE(lm.role, '') AS last_message_role,
+ lm.created_at AS last_message_at,
+ d.draft AS stored_draft
+FROM chat_session cs
+JOIN agent a ON a.id = cs.agent_id
+LEFT JOIN agent_builder_draft d ON d.chat_session_id = cs.id
+LEFT JOIN LATERAL (
+ SELECT content, role, created_at
+ FROM chat_message m
+ WHERE m.chat_session_id = cs.id
+ ORDER BY m.created_at DESC
+ LIMIT 1
+) lm ON true
+WHERE cs.workspace_id = $1
+ AND cs.creator_id = $2
+ AND cs.status = 'active'
+ AND a.kind = 'system'
+ AND a.system_key LIKE 'agent_builder:%'
+ AND (lm.created_at IS NOT NULL OR d.chat_session_id IS NOT NULL)
+ORDER BY COALESCE(lm.created_at, d.updated_at, cs.updated_at) DESC
+`
+
+type ListAgentBuilderSessionsByCreatorParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+}
+
+type ListAgentBuilderSessionsByCreatorRow struct {
+ ID pgtype.UUID `json:"id"`
+ Title string `json:"title"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ LastMessageContent string `json:"last_message_content"`
+ LastMessageRole string `json:"last_message_role"`
+ LastMessageAt pgtype.Timestamptz `json:"last_message_at"`
+ StoredDraft []byte `json:"stored_draft"`
+}
+
+// The caller's unfinished agent-creation conversations.
+//
+// These never appear in ListChatSessionsByCreator: that list is filtered
+// against ListAllAgents, which is `kind = 'user'` only, so a builder session —
+// whose agent is the hidden `kind = 'system'` carrier — is invisible to every
+// chat surface by construction. This statement is the only way back to one,
+// which is why the studio may stop deleting them on navigation.
+//
+// `a.runtime_id` is the whole point of the join. The carrier is what
+// SendDirectChatMessage reads to stamp a chat task's runtime, so it is the only
+// truthful answer to "where does this conversation run". Deliberately NOT
+// cs.runtime_id: that is the daemon's resume pointer, left stale on purpose
+// after a runtime switch (see RebindAgentBuilderRuntime), so resuming from it
+// would put the picker on a runtime that no longer executes anything — the
+// exact split MUL-5163 removed.
+//
+// A conversation qualifies once it holds something the user would miss: a
+// message, or a saved configuration. Requiring a message alone was wrong — the
+// form on the right is editable from the moment the session exists and
+// autosaves, so someone can open the builder, type a name, and leave before the
+// first turn. That session has real work in it and was unreachable. Requiring
+// neither is also wrong: a session opened and abandoned untouched is not a
+// draft, and would put an empty row in front of the user on every accidental
+// entry into the flow.
+// The stored draft rides along instead of needing its own fetch: the studio
+// renders this list beside the conversation it is switching between, so the
+// configuration for the row the user picks has to be in hand at click time.
+// LEFT JOIN because a conversation that has only ever been driven by the AI has
+// no saved draft — the client replays the last <agent_draft> block in that case.
+// A draft-only session has no message to sort by; fall back to when its
+// configuration was last written so it still lands in activity order.
+func (q *Queries) ListAgentBuilderSessionsByCreator(ctx context.Context, arg ListAgentBuilderSessionsByCreatorParams) ([]ListAgentBuilderSessionsByCreatorRow, error) {
+ rows, err := q.db.Query(ctx, listAgentBuilderSessionsByCreator, arg.WorkspaceID, arg.CreatorID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListAgentBuilderSessionsByCreatorRow{}
+ for rows.Next() {
+ var i ListAgentBuilderSessionsByCreatorRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.Title,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.RuntimeID,
+ &i.LastMessageContent,
+ &i.LastMessageRole,
+ &i.LastMessageAt,
+ &i.StoredDraft,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listAllChatSessionsByCreator = `-- name: ListAllChatSessionsByCreator :many
SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at, cs.project_id,
CASE WHEN cs.status = 'archived' THEN 0
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 6a56381d34..3d9cf5b771 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -54,6 +54,13 @@ type Agent struct {
ServiceTier pgtype.Text `json:"service_tier"`
}
+type AgentBuilderDraft struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Draft []byte `json:"draft"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
// Allow-list of who may invoke a public_to agent (MUL-3963). One row per (agent, target_type, target); targets stack and canInvokeAgent OR-matches. workspace rows store the agent workspace_id in target_id; member rows store the user id; team rows are reserved and inert in V1. Rows only matter when agent.permission_mode = public_to. No DB foreign keys: agent_id / created_by / member target_id relationships are maintained in the application layer (see migration comment).
type AgentInvocationTarget struct {
ID pgtype.UUID `json:"id"`
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 4f4095036b..6c37572f6d 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -248,6 +248,9 @@ deleted_draft_restores AS (
WHERE chat_session_id IN (SELECT id FROM ws_sessions)
OR task_id IN (SELECT id FROM ws_tasks)
),
+deleted_agent_builder_drafts AS (
+ DELETE FROM agent_builder_draft WHERE workspace_id = $1
+),
deleted_comment_reactions AS (
DELETE FROM comment_reaction WHERE workspace_id = $1
),
@@ -394,6 +397,9 @@ SET state = CASE
WHERE channel_media_pending_object.workspace_id = $1
`
+// Same no-FK chore as chat_draft_restore above. Matched on workspace_id rather
+// than the session set because that column exists precisely so this statement
+// does not have to join through chat_session, which it deletes in this same CTE.
// Keep the two-system cleanup ledger until object storage has been settled.
// Moving every row out of pending also prevents a concurrent media bind from
// attaching an object after the workspace teardown commits. The reconciler
diff --git a/server/pkg/db/queries/agent_builder.sql b/server/pkg/db/queries/agent_builder.sql
new file mode 100644
index 0000000000..f1137aaecc
--- /dev/null
+++ b/server/pkg/db/queries/agent_builder.sql
@@ -0,0 +1,31 @@
+-- name: UpsertAgentBuilderDraft :one
+-- The current configuration of one creation conversation. Last write wins:
+-- there is a single editor (the session's creator, on one screen at a time) and
+-- the client autosaves the whole object, so a partial merge would only be able
+-- to reconstruct a state the user never saw.
+INSERT INTO agent_builder_draft (chat_session_id, workspace_id, draft)
+VALUES (@chat_session_id, @workspace_id, @draft)
+ON CONFLICT (chat_session_id) DO UPDATE
+SET draft = EXCLUDED.draft,
+ updated_at = now()
+RETURNING *;
+
+-- name: DeleteAgentBuilderDraft :exec
+-- agent_builder_draft has no chat_session FK (repo rule), so every path that
+-- removes a conversation has to say so explicitly.
+DELETE FROM agent_builder_draft WHERE chat_session_id = $1;
+
+-- name: DeleteAgentBuilderDraftsBySystemRuntimeAgents :exec
+-- chat_session cascades from agent, so a runtime teardown hard-deleting its
+-- system carriers (DeleteSystemAgentsByRuntime) silently drops their sessions.
+-- Prune the drafts in the same tx and BEFORE the agent rows go — the join below
+-- needs them. Mirrors DeleteChatDraftRestoresBySystemRuntimeAgents.
+--
+-- Only the system variant exists: a builder draft can only ever hang off a
+-- `kind = 'system'` carrier, so the archived-agent prune has nothing to find.
+DELETE FROM agent_builder_draft
+WHERE chat_session_id IN (
+ SELECT cs.id FROM chat_session cs
+ JOIN agent a ON a.id = cs.agent_id
+ WHERE a.runtime_id = $1 AND a.kind = 'system'
+);
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index a96e41cb2e..c190ea41c7 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -75,6 +75,66 @@ LEFT JOIN LATERAL (
WHERE cs.workspace_id = $1 AND cs.creator_id = $2
ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC;
+-- name: ListAgentBuilderSessionsByCreator :many
+-- The caller's unfinished agent-creation conversations.
+--
+-- These never appear in ListChatSessionsByCreator: that list is filtered
+-- against ListAllAgents, which is `kind = 'user'` only, so a builder session —
+-- whose agent is the hidden `kind = 'system'` carrier — is invisible to every
+-- chat surface by construction. This statement is the only way back to one,
+-- which is why the studio may stop deleting them on navigation.
+--
+-- `a.runtime_id` is the whole point of the join. The carrier is what
+-- SendDirectChatMessage reads to stamp a chat task's runtime, so it is the only
+-- truthful answer to "where does this conversation run". Deliberately NOT
+-- cs.runtime_id: that is the daemon's resume pointer, left stale on purpose
+-- after a runtime switch (see RebindAgentBuilderRuntime), so resuming from it
+-- would put the picker on a runtime that no longer executes anything — the
+-- exact split MUL-5163 removed.
+--
+-- A conversation qualifies once it holds something the user would miss: a
+-- message, or a saved configuration. Requiring a message alone was wrong — the
+-- form on the right is editable from the moment the session exists and
+-- autosaves, so someone can open the builder, type a name, and leave before the
+-- first turn. That session has real work in it and was unreachable. Requiring
+-- neither is also wrong: a session opened and abandoned untouched is not a
+-- draft, and would put an empty row in front of the user on every accidental
+-- entry into the flow.
+--
+-- The stored draft rides along instead of needing its own fetch: the studio
+-- renders this list beside the conversation it is switching between, so the
+-- configuration for the row the user picks has to be in hand at click time.
+-- LEFT JOIN because a conversation that has only ever been driven by the AI has
+-- no saved draft — the client replays the last <agent_draft> block in that case.
+SELECT cs.id,
+ cs.title,
+ cs.created_at,
+ cs.updated_at,
+ a.runtime_id,
+ COALESCE(lm.content, '') AS last_message_content,
+ COALESCE(lm.role, '') AS last_message_role,
+ lm.created_at AS last_message_at,
+ d.draft AS stored_draft
+FROM chat_session cs
+JOIN agent a ON a.id = cs.agent_id
+LEFT JOIN agent_builder_draft d ON d.chat_session_id = cs.id
+LEFT JOIN LATERAL (
+ SELECT content, role, created_at
+ FROM chat_message m
+ WHERE m.chat_session_id = cs.id
+ ORDER BY m.created_at DESC
+ LIMIT 1
+) lm ON true
+WHERE cs.workspace_id = $1
+ AND cs.creator_id = $2
+ AND cs.status = 'active'
+ AND a.kind = 'system'
+ AND a.system_key LIKE 'agent_builder:%'
+ AND (lm.created_at IS NOT NULL OR d.chat_session_id IS NOT NULL)
+-- A draft-only session has no message to sort by; fall back to when its
+-- configuration was last written so it still lands in activity order.
+ORDER BY COALESCE(lm.created_at, d.updated_at, cs.updated_at) DESC;
+
-- name: UpdateChatSessionTitle :one
UPDATE chat_session SET title = $2, updated_at = now()
WHERE id = $1
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 20a68808b7..d5ee620c7f 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -148,6 +148,12 @@ deleted_draft_restores AS (
WHERE chat_session_id IN (SELECT id FROM ws_sessions)
OR task_id IN (SELECT id FROM ws_tasks)
),
+-- Same no-FK chore as chat_draft_restore above. Matched on workspace_id rather
+-- than the session set because that column exists precisely so this statement
+-- does not have to join through chat_session, which it deletes in this same CTE.
+deleted_agent_builder_drafts AS (
+ DELETE FROM agent_builder_draft WHERE workspace_id = $1
+),
deleted_comment_reactions AS (
DELETE FROM comment_reaction WHERE workspace_id = $1
),