Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(agents): add conversational creation studio (#5296)
Jiayuan Zhang1427e8abd3ad
diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsxindex 9157630935..929a43ff9d 100644--- a/apps/desktop/src/renderer/src/routes.tsx+++ b/apps/desktop/src/renderer/src/routes.tsx@@ -22,6 +22,7 @@ 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 { SquadsPage, SquadDetailPage as SquadDetailPageView } from "@multica/views/squads/components";import { InboxPage } from "@multica/views/inbox";import { ChatPage } from "@multica/views/chat";@@ -170,6 +171,7 @@ 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/:id",element: <AgentDetailPage />,diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/page.tsxnew file mode 100644index 0000000000..f2551163c0--- /dev/null+++ b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/page.tsx@@ -0,0 +1,5 @@+import { AgentCreationStudio } from "@multica/views/agents";++export default function NewAgentRoute() {+ return <AgentCreationStudio />;+}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 7feb40d899..90592a04fa 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -17,6 +17,7 @@ import type {AgentTemplateSummary,CreateAgentFromTemplateRequest,CreateAgentFromTemplateResponse,+ AgentBuilderSession,UpdateAgentRequest,AgentEnvResponse,UpdateAgentEnvRequest,@@ -161,6 +162,7 @@ import {CloudRuntimeNodeListSchema,CloudRuntimeNodeSchema,CreateAgentFromTemplateResponseSchema,+ AgentBuilderSessionSchema,DashboardAgentRunTimeListSchema,DashboardRunTimeDailyListSchema,DashboardUsageByAgentListSchema,@@ -172,6 +174,7 @@ import {EMPTY_CLOUD_RUNTIME_NODE,EMPTY_CLOUD_RUNTIME_NODE_LIST,EMPTY_CREATE_AGENT_FROM_TEMPLATE_RESPONSE,+ EMPTY_AGENT_BUILDER_SESSION,EMPTY_GROUPED_ISSUES_RESPONSE,EMPTY_LIST_ISSUES_RESPONSE,EMPTY_SEARCH_ISSUES_RESPONSE,@@ -866,6 +869,22 @@ export class ApiClient {});}+ async createAgentBuilderSession(data: {+ runtime_id: string;+ model?: string;+ }): Promise<AgentBuilderSession> {+ const raw = await this.fetch<unknown>("/api/agent-builder/sessions", {+ method: "POST",+ body: JSON.stringify(data),+ });+ return parseWithFallback(+ raw,+ AgentBuilderSessionSchema,+ EMPTY_AGENT_BUILDER_SESSION,+ { endpoint: "POST /api/agent-builder/sessions" },+ );+ }+async listAgentTemplates(): Promise<AgentTemplateSummary[]> {const raw = await this.fetch<unknown>("/api/agent-templates");return parseWithFallback(diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex ce2dde32cd..d63d44d90b 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -3,6 +3,7 @@ import type {Agent,AgentTemplate,AgentTemplateSummary,+ AgentBuilderSession,Attachment,BillingBalance,BillingBatchesPage,@@ -767,6 +768,18 @@ export const EMPTY_CREATE_AGENT_FROM_TEMPLATE_RESPONSE: CreateAgentFromTemplateRreused_skill_ids: [],};+export const AgentBuilderSessionSchema = z.object({+ session_id: z.string(),+ builder_agent_id: z.string(),+ runtime_id: z.string(),+}).loose();++export const EMPTY_AGENT_BUILDER_SESSION: AgentBuilderSession = {+ session_id: "",+ builder_agent_id: "",+ runtime_id: "",+};+// Squad list responses carry lightweight membership previews used by hover// cards. The preview fields are additive API fields, so older backends default// cleanly to no preview instead of breaking newer frontends.diff --git a/packages/core/paths/consistency.test.ts b/packages/core/paths/consistency.test.tsindex c1618127a9..d3a8fe282f 100644--- a/packages/core/paths/consistency.test.ts+++ b/packages/core/paths/consistency.test.ts@@ -22,6 +22,7 @@ describe("paths.workspace() shape", () => {"projects","autopilots","agents",+ "newAgent","chat","squads","inbox",@@ -36,14 +37,15 @@ describe("paths.workspace() shape", () => {it("each parameterless route emits /{slug}/{segment}", () => {const ws = paths.workspace("acme");- // Check that none of the parameterless paths embed a leaked literal- // and that their second URL segment matches the method name's kebab-case.+ // Check that none of the parameterless paths embed a leaked literal and+ // that each method emits its explicitly registered workspace subpath.const expectedSegments: Array<[string, string]> = [["usage", "usage"],["issues", "issues"],["projects", "projects"],["autopilots", "autopilots"],["agents", "agents"],+ ["newAgent", "agents/new"],["chat", "chat"],["squads", "squads"],["inbox", "inbox"],diff --git a/packages/core/paths/paths.test.ts b/packages/core/paths/paths.test.tsindex 5df542a301..de43b106ca 100644--- a/packages/core/paths/paths.test.ts+++ b/packages/core/paths/paths.test.ts@@ -13,6 +13,7 @@ describe("paths.workspace(slug)", () => {expect(ws.autopilots()).toBe("/acme/autopilots");expect(ws.autopilotDetail("a1")).toBe("/acme/autopilots/a1");expect(ws.agents()).toBe("/acme/agents");+ expect(ws.newAgent()).toBe("/acme/agents/new");expect(ws.memberDetail("u1")).toBe("/acme/members/u1");expect(ws.inbox()).toBe("/acme/inbox");expect(ws.myIssues()).toBe("/acme/my-issues");diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.tsindex ad73dc4a49..61d95144ab 100644--- a/packages/core/paths/paths.ts+++ b/packages/core/paths/paths.ts@@ -26,6 +26,7 @@ function workspaceScoped(slug: string) {autopilots: () => `${ws}/autopilots`,autopilotDetail: (id: string) => `${ws}/autopilots/${encode(id)}`,agents: () => `${ws}/agents`,+ newAgent: () => `${ws}/agents/new`,agentDetail: (id: string) => `${ws}/agents/${encode(id)}`,memberDetail: (id: string) => `${ws}/members/${encode(id)}`,squads: () => `${ws}/squads`,diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 3980d370ec..87d9537da2 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -440,6 +440,14 @@ export interface CreateAgentRequest {/** Optional template slug used by the onboarding agent picker. Surfaced* as the `template` property on the `agent_created` PostHog event. */template?: string;+ /** Workspace skill IDs attached atomically with the agent row. */+ skill_ids?: string[];+}++export interface AgentBuilderSession {+ session_id: string;+ builder_agent_id: string;+ runtime_id: string;}/** Agent template summary — fields needed by the picker grid. Does NOTdiff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 00dfe09660..2cfa7e6403 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -19,6 +19,7 @@ export type {CreateRuntimeProfileRequest,UpdateRuntimeProfileRequest,CreateAgentRequest,+ AgentBuilderSession,AgentTemplate,AgentTemplateSummary,AgentTemplateSkillRef,diff --git a/packages/ui/components/common/submit-button.tsx b/packages/ui/components/common/submit-button.tsxindex 69d604ee13..ba9089ab83 100644--- a/packages/ui/components/common/submit-button.tsx+++ b/packages/ui/components/common/submit-button.tsx@@ -22,8 +22,12 @@ interface SubmitButtonProps {* free of `@multica/core` (platform-detection) and i18n imports.*/tooltip?: ReactNode;+ /** Accessible name for the icon-only submit button. */+ ariaLabel?: string;/** Tooltip shown over the stop button while a run is in progress. */stopTooltip?: ReactNode;+ /** Accessible name for the icon-only stop button. */+ stopAriaLabel?: string;}function SubmitButton({@@ -33,12 +37,19 @@ function SubmitButton({running,onStop,tooltip,+ ariaLabel,stopTooltip,+ stopAriaLabel,}: SubmitButtonProps) {if (running) {const stopButton = (- <Button size="icon-sm" className="rounded-full" onClick={onStop}>- <Square className="fill-current" />+ <Button+ size="icon-sm"+ className="rounded-full"+ onClick={onStop}+ aria-label={stopAriaLabel}+ >+ <Square className="fill-current" aria-hidden="true" /></Button>);if (!stopTooltip) return stopButton;@@ -56,8 +67,13 @@ function SubmitButton({className="rounded-full"disabled={disabled || loading}onClick={onClick}+ aria-label={ariaLabel}>- {loading ? <Loader2 className="animate-spin" /> : <ArrowUp />}+ {loading ? (+ <Loader2 className="animate-spin" aria-hidden="true" />+ ) : (+ <ArrowUp aria-hidden="true" />+ )}</Button>);if (!tooltip) return submitButton;diff --git a/packages/views/agents/components/agent-creation-studio.test.ts b/packages/views/agents/components/agent-creation-studio.test.tsnew file mode 100644index 0000000000..256356f975--- /dev/null+++ b/packages/views/agents/components/agent-creation-studio.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it } from "vitest";+import {+ buildInvocationTargets,+ decodeBuilderInput,+ deriveDuplicateAccess,+ encodeBuilderInput,+ mergeBuilderDraft,+ parseBuilderDraft,+ stripBuilderDraft,+ type AgentDraft,+} from "./agent-creation-studio";++const draft = (): AgentDraft => ({+ name: "Old name",+ description: "Old description",+ instructions: "Old instructions",+ avatarUrl: null,+ runtimeId: "runtime-1",+ model: "model-1",+ skillIds: new Set(["skill-1"]),+ permissionScope: "private",+ memberIds: new Set(),+ teamIds: new Set(),+});++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(), [], []);++ expect(decodeBuilderInput(content)).toBe("Create a release manager");+ expect(decodeBuilderInput("ordinary chat message")).toBe(+ "ordinary chat message",+ );+ });++ 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"]),+ );++ 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("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");+ });+});diff --git a/packages/views/agents/components/agent-creation-studio.tsx b/packages/views/agents/components/agent-creation-studio.tsxnew file mode 100644index 0000000000..796822610d--- /dev/null+++ b/packages/views/agents/components/agent-creation-studio.tsx@@ -0,0 +1,1519 @@+"use client";++import { useEffect, useMemo, useRef, useState, type ReactNode } from "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 } from "@multica/core/api";+import { useAuthStore } from "@multica/core/auth";+import {+ 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 { runtimeListOptions } from "@multica/core/runtimes";+import type {+ Agent,+ AgentInvocationTargetInput,+ AgentTemplateSummary,+ ChatMessage,+ CreateAgentRequest,+ MemberWithUser,+ RuntimeDevice,+} 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 { cn } from "@multica/ui/lib/utils";+import { AvatarUploadControl } from "../../common/avatar-upload-control";+import { ChatInput } from "../../chat/components/chat-input";+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 { RuntimePicker, isRuntimeUsableForUser } from "./runtime-picker";+import { SkillMultiSelect } from "./skill-multi-select";++type StudioMode = "choose" | "templates" | "blank" | "template" | "ai";+type PermissionScope = "private" | "workspace" | "members";++export interface AgentDraft {+ name: string;+ description: string;+ instructions: string;+ avatarUrl: string | null;+ runtimeId: string;+ model: 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>;+}++export interface BuilderDraftPayload {+ name?: unknown;+ description?: unknown;+ instructions?: unknown;+ model?: unknown;+ skill_ids?: unknown;+ permission_scope?: unknown;+ member_ids?: unknown;+}++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: "",+ 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 { data: agents = [] } = useQuery(agentListOptions(wsId));+ const { data: runtimes = [], isLoading: runtimesLoading } = 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 [draft, setDraft] = useState<AgentDraft>(EMPTY_DRAFT);+ const [sourceTemplate, setSourceTemplate] = useState<AgentTemplateSummary | null>(null);+ const [selectedTemplate, setSelectedTemplate] = useState<AgentTemplateSummary | null>(null);+ const [templateSearch, setTemplateSearch] = useState("");+ const [creating, setCreating] = useState(false);+ const [createError, setCreateError] = useState<string | null>(null);+ const [builderSessionId, setBuilderSessionId] = useState("");+ const [builderStarting, setBuilderStarting] = useState(false);+ const [builderClosing, setBuilderClosing] = useState(false);+ const [builderError, setBuilderError] = useState<string | null>(null);+ const [builderRestoreDraft, setBuilderRestoreDraft] = useState<{+ id: string;+ content: string;+ } | null>(null);+ const duplicateAppliedRef = useRef(false);+ const appliedAssistantMessageRef = useRef<string | null>(null);+ const builderSessionIdRef = useRef("");++ 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],+ );++ useEffect(() => {+ if (draft.runtimeId || usableRuntimes.length === 0) return;+ setDraft((current) => ({ ...current, runtimeId: usableRuntimes[0]?.id ?? "" }));+ }, [draft.runtimeId, usableRuntimes]);++ useEffect(() => {+ if (!duplicateAgent || duplicateAppliedRef.current) return;+ duplicateAppliedRef.current = true;+ const duplicateAccess = deriveDuplicateAccess(duplicateAgent);+ setDraft({+ name: `${duplicateAgent.name}${t(($) => $.create_dialog.duplicate_copy_suffix)}`,+ description: duplicateAgent.description ?? "",+ instructions: duplicateAgent.instructions ?? "",+ avatarUrl: duplicateAgent.avatar_url ?? null,+ runtimeId:+ duplicateAgent.runtime_id &&+ runtimes.some(+ (runtime) =>+ runtime.id === duplicateAgent.runtime_id &&+ isRuntimeUsableForUser(runtime, currentUser?.id ?? null),+ )+ ? duplicateAgent.runtime_id+ : usableRuntimes[0]?.id ?? "",+ model: duplicateAgent.model ?? "",+ skillIds: new Set(duplicateAgent.skills.map((skill) => skill.id)),+ ...duplicateAccess,+ });+ }, [currentUser?.id, duplicateAgent, runtimes, t, usableRuntimes]);++ 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));+ }, [+ latestBuilderDraftMessageContent,+ latestBuilderDraftMessageId,+ memberIdSet,+ skillIdSet,+ ]);++ 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 selectedRuntime =+ runtimes.find((runtime) => runtime.id === draft.runtimeId) ?? null;+ 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) &&+ !accessInvalid &&+ !creating;+ 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 = () => {+ setMode("choose");+ setSelectedTemplate(null);+ setSourceTemplate(null);+ setBuilderSessionId("");+ };++ 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 = "";+ setBuilderSessionId("");+ 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;+ }+ 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 || "",+ }));+ setMode("blank");+ };++ 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 || "",+ }));+ 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));+ setBuilderSessionId(session.session_id);+ } catch (error) {+ setBuilderError(+ error instanceof Error ? error.message : t(($) => $.creation_studio.builder.start_failed),+ );+ } finally {+ setBuilderStarting(false);+ }+ };++ const sendBuilderMessage = async (content: string): Promise<boolean> => {+ const text = content.trim();+ if (!text || !builderSessionId || builderPending) return false;+ setBuilderError(null);+ try {+ const encodedContent = encodeBuilderInput(+ text,+ draft,+ workspaceSkills,+ members,+ );+ 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);+ setCreateError(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: CreateAgentRequest = {+ name: draft.name.trim(),+ description: draft.description.trim(),+ instructions: draft.instructions.trim() || undefined,+ 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,+ skill_ids: [...draft.skillIds],+ template: mode === "ai" ? "agent_builder" : undefined,+ };+ if (duplicateAgent) {+ if (duplicateAgent.custom_args.length > 0) {+ request.custom_args = duplicateAgent.custom_args;+ }+ request.max_concurrent_tasks = duplicateAgent.max_concurrent_tasks;+ }+ 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) {+ setCreateError(+ error instanceof Error ? error.message : t(($) => $.creation_studio.create_failed),+ );+ setCreating(false);+ }+ };++ 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-sm 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-xs text-muted-foreground">+ {currentModeLabel}+ </p>+ </div>+ {mode !== "choose" && mode !== "templates" && (+ <div className="ml-auto hidden items-center gap-2 text-xs 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">+ {selectedRuntime.name || selectedRuntime.provider}+ </span>+ )}+ </div>+ )}+ </header>++ {mode === "choose" && (+ <ModeChooser+ onBlank={chooseBlank}+ onTemplate={() => setMode("templates")}+ onAI={() => setMode("ai")}+ />+ )}++ {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-sm">+ {t(($) => $.creation_studio.duplicate_env_notice)}+ </div>+ )}+ <ConfigurationPanel+ draft={draft}+ onChange={setDraft}+ runtimes={runtimes}+ runtimesLoading={runtimesLoading}+ members={members}+ currentUserId={currentUser?.id ?? null}+ createError={createError}+ />+ </div>+ <StudioFooter+ canCreate={canCreate}+ creating={creating}+ squad={!!squadId}+ 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={builderRestoreDraft}+ onRestoreDraftConsumed={() => setBuilderRestoreDraft(null)}+ 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-base font-semibold tracking-tight">+ {t(($) => $.creation_studio.live_draft)}+ </h2>+ <p className="mt-1 text-xs 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}+ createError={createError}+ />+ </div>+ <StudioFooter+ canCreate={canCreate && !builderPending}+ creating={creating}+ squad={!!squadId}+ onCreate={createAgent}+ />+ </div>+ </div>+ )}+ </div>+ );+}++function ModeChooser({+ onBlank,+ onTemplate,+ onAI,+}: {+ onBlank: () => void;+ onTemplate: () => 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: Bot,+ title: t(($) => $.creation_studio.modes.template.title),+ description: t(($) => $.creation_studio.modes.template.description),+ action: onTemplate,+ },+ {+ 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-xs font-medium uppercase tracking-wider text-muted-foreground">+ {t(($) => $.creation_studio.eyebrow)}+ </div>+ <h2 className="mt-2 text-balance text-2xl font-semibold tracking-tight sm:text-3xl">+ {t(($) => $.creation_studio.choose_title)}+ </h2>+ <p className="mt-3 text-pretty text-sm text-muted-foreground">+ {t(($) => $.creation_studio.choose_description)}+ </p>+ </div>+ <div className="mt-9 grid gap-4 md:grid-cols-3">+ {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-[10px] 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-base font-semibold">{title}</span>+ <span className="mt-2 text-sm leading-6 text-muted-foreground">{description}</span>+ <span className="mt-auto flex items-center gap-1 pt-5 text-xs 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-sm 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-sm font-medium">{template.name}</span>+ {template.category && <span className="ml-auto shrink-0 text-[10px] text-muted-foreground">{template.category}</span>}+ </span>+ <span className="mt-1 line-clamp-2 block text-xs 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-sm">{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-xl font-semibold">{selected.name}</h2><p className="mt-1 text-sm leading-6 text-muted-foreground">{selected.description}</p></div>+ </div>+ {selected.skills.length > 0 && (+ <div className="mt-7"><h3 className="text-xs 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-sm font-medium">{skill.cached_name}</div><div className="mt-0.5 text-xs text-muted-foreground">{skill.cached_description}</div></div></div>)}</div></div>+ )}+ <div className="mt-7"><h3 className="text-xs 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-sm 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,+ createError,+ compact = false,+}: {+ draft: AgentDraft;+ onChange: (draft: AgentDraft) => void;+ runtimes: RuntimeDevice[];+ runtimesLoading: boolean;+ members: MemberWithUser[];+ currentUserId: string | null;+ createError: string | null;+ compact?: 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);++ 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)}+ onClear={() => set("avatarUrl", null)}+ />+ </div>+ </DraftFieldRow>+ <DraftFieldRow+ compact={compact}+ label={t(($) => $.create_dialog.name_label)}+ htmlFor="agent-create-name"+ >+ <Input+ id="agent-create-name"+ name="agent-name"+ autoComplete="off"+ aria-label={t(($) => $.create_dialog.name_label)}+ value={draft.name}+ onChange={(event) => set("name", event.target.value)}+ placeholder={t(($) => $.create_dialog.name_placeholder)}+ />+ </DraftFieldRow>+ <DraftFieldRow+ compact={compact}+ align="start"+ label={t(($) => $.create_dialog.description_label)}+ htmlFor="agent-create-description"+ >+ <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}+ className="resize-y"+ />+ </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-[13px] 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")}>+ <RuntimePicker+ runtimes={runtimes}+ runtimesLoading={runtimesLoading}+ members={members}+ currentUserId={currentUserId}+ selectedRuntimeId={draft.runtimeId}+ onSelect={(id) => set("runtimeId", id)}+ />+ <ModelDropdown+ runtimeId={selectedRuntime?.id ?? null}+ runtimeOnline={selectedRuntime?.status === "online"}+ value={draft.model}+ onChange={(value) => set("model", value)}+ disabled={!selectedRuntime}+ />+ </div>+ </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-sm font-medium">+ {t(($) => $.creation_studio.access[scope].title)}+ </span>+ <span className="mt-0.5 block text-xs 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-sm">+ {member.name}+ </span>+ </label>+ );+ })}+ {draft.memberIds.size === 0 ? (+ <p className="px-2 py-1 text-xs text-destructive">+ {t(($) => $.creation_studio.access.members.required)}+ </p>+ ) : null}+ </div>+ ) : null}+ </SettingsCard>+ </SettingsSection>++ {createError ? (+ <div+ role="alert"+ aria-live="polite"+ className="rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive"+ >+ {createError}+ </div>+ ) : null}+ </div>+ );+}++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-sm font-medium">+ {label}+ </label>+ ) : (+ <div className="text-sm 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-xl font-semibold">{t(($) => $.creation_studio.builder.setup_title)}</h2><p className="mt-2 text-sm 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) => onChange({ ...draft, runtimeId })} /><ModelDropdown runtimeId={selectedRuntime?.id ?? null} runtimeOnline={selectedRuntime?.status === "online"} value={draft.model} onChange={(model) => onChange({ ...draft, model })} disabled={!selectedRuntime} /></div>{error && <div role="alert" className="mt-4 text-sm 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,+ onRestoreDraftConsumed,+ 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;+ onRestoreDraftConsumed: () => 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 (+ <section className="flex min-h-0 flex-col bg-background">+ <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-sm font-semibold">+ {t(($) => $.creation_studio.builder.chat_title)}+ </h2>+ <p className="truncate text-xs text-muted-foreground">+ {t(($) => $.creation_studio.builder.chat_hint)}+ </p>+ </div>+ <div className="flex shrink-0 items-center gap-1.5 text-xs 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-lg font-semibold">+ {t(($) => $.creation_studio.builder.empty_title)}+ </h3>+ <p className="mx-auto mt-2 max-w-md text-pretty text-sm 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-xs 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-sm 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}+ onRestoreDraftConsumed={onRestoreDraftConsumed}+ />+ </section>+ );+}++function StudioFooter({ canCreate, creating, squad, onCreate }: { canCreate: boolean; creating: boolean; squad: boolean; onCreate: () => void; }) { const { t } = useT("agents"); return <div className="sticky bottom-0 mt-8 flex items-center justify-end gap-3 border-t bg-background/95 px-5 py-3 backdrop-blur"><Button type="button" 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),+ };+}+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 }>,+): 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],+ },+ 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 function mergeBuilderDraft(+ current: AgentDraft,+ payload: BuilderDraftPayload,+ validSkillIds: Set<string>,+ validMemberIds: Set<string>,+): 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];++ 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: typeof payload.model === "string" ? payload.model : current.model,+ skillIds: new Set(skillIds),+ permissionScope: scope,+ memberIds: new Set(scope === "members" ? memberIds : []),+ teamIds: current.teamIds,+ };+}diff --git a/packages/views/agents/components/agents-page.tsx b/packages/views/agents/components/agents-page.tsxindex 73ad5c89b1..4961fb2a5c 100644--- a/packages/views/agents/components/agents-page.tsx+++ b/packages/views/agents/components/agents-page.tsx@@ -17,7 +17,6 @@ import { toast } from "sonner";import type {Agent,AgentRuntime,- CreateAgentRequest,MemberWithUser,} from "@multica/core/types";import {@@ -80,7 +79,6 @@ import {CollectionPageState,} from "../../layout/collection-page";import { availabilityConfig } from "../presence";-import { CreateAgentDialog } from "./create-agent-dialog";import { AgentRowActions } from "./agent-row-actions";import {AgentListToolbar,@@ -793,7 +791,6 @@ export function AgentsPage(_props: AgentsPageProps = {}) {const paths = useWorkspacePaths();const navigation = useNavigation();const rowLink = useRowLink();- const qc = useQueryClient();const currentUser = useAuthStore((s) => s.user);const {@@ -802,7 +799,7 @@ export function AgentsPage(_props: AgentsPageProps = {}) {error: listError,refetch: refetchList,} = useQuery(agentListOptions(wsId));- const { data: runtimes = [], isLoading: runtimesLoading } = useQuery(+ const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId),);const { data: members = [] } = useQuery(memberListOptions(wsId));@@ -810,10 +807,6 @@ export function AgentsPage(_props: AgentsPageProps = {}) {const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);const { byAgent: activityMap } = useWorkspaceActivityMap(wsId);- const [showCreate, setShowCreate] = useState(false);- const [duplicateTemplate, setDuplicateTemplate] = useState<Agent | null>(- null,- );const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(new Set(),);@@ -1020,25 +1013,9 @@ export function AgentsPage(_props: AgentsPageProps = {}) {overscan: 10,});- const handleCreate = async (data: CreateAgentRequest): Promise<Agent> => {- const agent = await api.createAgent(data);- qc.setQueryData<Agent[]>(workspaceKeys.agents(wsId), (current = []) => {- const exists = current.some((a) => a.id === agent.id);- return exists- ? current.map((a) => (a.id === agent.id ? agent : a))- : [...current, agent];- });- setShowCreate(false);- setDuplicateTemplate(null);- navigation.push(paths.agentDetail(agent.id));- qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });- return agent;- };-const handleDuplicate = useCallback((agent: Agent) => {- setDuplicateTemplate(agent);- setShowCreate(true);- }, []);+ navigation.push(`${paths.newAgent()}?duplicate=${encodeURIComponent(agent.id)}`);+ }, [navigation, paths]);const selectedRows = rows.filter((row) => selectedIds.has(row.agent.id));const allSelected = rows.length > 0 && selectedRows.length === rows.length;@@ -1062,7 +1039,7 @@ export function AgentsPage(_props: AgentsPageProps = {}) {if (listError) {return (<ListError- onCreate={() => setShowCreate(true)}+ onCreate={() => navigation.push(paths.newAgent())}listError={listError}onRetry={() => refetchList()}/>@@ -1078,7 +1055,7 @@ export function AgentsPage(_props: AgentsPageProps = {}) {<div className="relative flex flex-1 min-h-0 flex-col"><PageHeaderBartotalCount={totalCount}- onCreate={() => setShowCreate(true)}+ onCreate={() => navigation.push(paths.newAgent())}/>{isLoading ? (@@ -1087,7 +1064,7 @@ export function AgentsPage(_props: AgentsPageProps = {}) {</div>) : showEmpty ? (<div className="flex flex-1 items-center justify-center">- <EmptyState onCreate={() => setShowCreate(true)} />+ <EmptyState onCreate={() => navigation.push(paths.newAgent())} /></div>) : (<>@@ -1227,20 +1204,6 @@ export function AgentsPage(_props: AgentsPageProps = {}) {onClear={() => setSelectedIds(new Set())}/>- {showCreate && (- <CreateAgentDialog- runtimes={runtimes}- runtimesLoading={runtimesLoading}- members={members}- currentUserId={currentUser?.id ?? null}- template={duplicateTemplate}- onClose={() => {- setShowCreate(false);- setDuplicateTemplate(null);- }}- onCreate={handleCreate}- />- )}</div>);}diff --git a/packages/views/agents/components/create-agent-dialog.tsx b/packages/views/agents/components/create-agent-dialog.tsxindex 19df59a347..b650543f1e 100644--- a/packages/views/agents/components/create-agent-dialog.tsx+++ b/packages/views/agents/components/create-agent-dialog.tsx@@ -227,6 +227,7 @@ export function CreateAgentDialog({model: model.trim() || undefined,instructions: trimmedInstructions || undefined,avatar_url: avatarUrl ?? undefined,+ skill_ids: [...selectedSkillIds],};if (accessPickerEnabled) {// New MUL-3963 shape: send the authoritative permission fields and@@ -272,29 +273,6 @@ export function CreateAgentDialog({}}const createdAgent = await onCreate(data);- // Follow-up: attach selected skills to the newly created agent.- // onCreate returns the created Agent for this path; if the caller- // doesn't return it we fall back to skipping (preserves- // backward compatibility with non-skill-aware callers).- if (createdAgent && selectedSkillIds.size > 0) {- try {- await api.setAgentSkills(createdAgent.id, {- skill_ids: [...selectedSkillIds],- });- if (wsId) {- queryClient.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });- }- } catch (skillErr) {- // Non-fatal: agent exists, skills can be added on the detail- // page. Surface as a warning toast so the user knows.- toast.warning(- t(($) => $.create_dialog.skill_attach_failed_toast, {- error:- skillErr instanceof Error ? skillErr.message : "unknown error",- }),- );- }- }// Squad context: attach the agent after skills land so the// squad's Members tab shows the agent with its skills already// in place. Atomicity is best-effort by design (see plan indiff --git a/packages/views/agents/components/index.ts b/packages/views/agents/components/index.tsindex c459fd7799..f0b04c9a55 100644--- a/packages/views/agents/components/index.ts+++ b/packages/views/agents/components/index.ts@@ -1,2 +1,3 @@export { AgentsPage } from "./agents-page";export { AgentDetailPage } from "./agent-detail-page";+export { AgentCreationStudio } from "./agent-creation-studio";diff --git a/packages/views/agents/index.ts b/packages/views/agents/index.tsindex 486547b34f..1c73d0d314 100644--- a/packages/views/agents/index.ts+++ b/packages/views/agents/index.ts@@ -1 +1 @@-export { AgentsPage, AgentDetailPage } from "./components";+export { AgentsPage, AgentDetailPage, AgentCreationStudio } from "./components";diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsxindex 60aa35eb63..5d10a68342 100644--- a/packages/views/chat/components/chat-input.tsx+++ b/packages/views/chat/components/chat-input.tsx@@ -90,6 +90,13 @@ interface ChatInputProps {* 0 (the initial value) is inert, so a plain deep-link open never steals* focus; only an explicit bump does. */focusRequest?: number;+ /**+ * Optional storage/identity isolation for embedded chat surfaces that use+ * the shared composer without participating in the global chat selection+ * store (for example Agent Builder).+ */+ draftKeyOverride?: string;+ editorKeyOverride?: string;}export function ChatInput({@@ -106,6 +113,8 @@ export function ChatInput({leftAdornment,contextItems,focusRequest,+ draftKeyOverride,+ editorKeyOverride,}: ChatInputProps) {const { t } = useT("chat");const sendShortcut = useShortcut("send");@@ -139,7 +148,8 @@ export function ChatInput({// user would see the image flash on then disappear. Keeping editor// identity stable across the lazy-create event is what makes// first-upload-creates-session work the same as second-upload.- const draftKey = activeSessionId ?? newSessionDraftKey(selectedAgentId);+ const draftKey =+ draftKeyOverride ?? activeSessionId ?? newSessionDraftKey(selectedAgentId);// Select a primitive — empty-string fallback keeps referential stability.const inputDraft = useChatStore((s) => s.inputDrafts[draftKey] ?? "");const draftAttachments = useChatStore(@@ -152,7 +162,7 @@ export function ChatInput({const [isEmpty, setIsEmpty] = useState(!inputDraft.trim());const [isSubmitting, setIsSubmitting] = useState(false);const consumedRestoreIdRef = useRef<string | null>(null);- const editorKey = selectedAgentId ?? "no-agent";+ const editorKey = editorKeyOverride ?? selectedAgentId ?? "no-agent";// Number of in-flight uploads. We track this explicitly (rather than// peeking at the editor on every render) so the SubmitButton visibly// disables the instant an upload starts and re-enables the instant it@@ -429,7 +439,9 @@ export function ChatInput({tooltip={sendShortcut? `${t(($) => $.input.send_tooltip)} · ${formatShortcut(sendShortcut)}`: t(($) => $.input.send_tooltip)}+ ariaLabel={t(($) => $.input.send_tooltip)}stopTooltip={t(($) => $.input.stop_tooltip)}+ stopAriaLabel={t(($) => $.input.stop_tooltip)}/></div>{uploadEnabled && isDragOver && <FileDropOverlay />}diff --git a/packages/views/chat/components/chat-message-list.test.tsx b/packages/views/chat/components/chat-message-list.test.tsxindex 977dae58ed..ef281515ad 100644--- a/packages/views/chat/components/chat-message-list.test.tsx+++ b/packages/views/chat/components/chat-message-list.test.tsx@@ -98,4 +98,35 @@ describe("ChatMessageList live timeline (MUL-3960 regression)", () => {await screen.findByText("3 steps");expect(screen.queryByText("Bash")).not.toBeInTheDocument();});++ it("applies an embedded surface content transform to streamed text", async () => {+ const qc = new QueryClient();+ qc.setQueryData(chatKeys.taskMessages(TASK_ID), [+ taskMsg(0, "text", {+ content:+ "Draft ready.\n<agent_draft>{\"name\":\"Hidden protocol\"}</agent_draft>",+ }),+ ]);++ render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <QueryClientProvider client={qc}>+ <ChatMessageList+ messages={[]}+ pendingTask={{ task_id: TASK_ID, status: "running" }}+ availability="online"+ transformContent={(content) =>+ content.replace(+ /<agent_draft>[\s\S]*?<\/agent_draft>/g,+ "",+ )+ }+ />+ </QueryClientProvider>+ </I18nProvider>,+ );++ expect(await screen.findByText("Draft ready.")).toBeInTheDocument();+ expect(screen.queryByText(/Hidden protocol/)).not.toBeInTheDocument();+ });});diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsxindex ac65d525b9..d0050636de 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -52,6 +52,8 @@ interface ChatMessageListProps {hasOlderMessages?: boolean;isFetchingOlderMessages?: boolean;onLoadOlderMessages?: () => void;+ /** Transform assistant task text for embedded chat protocols before render/copy. */+ transformContent?: (content: string) => string;}// ─── Virtuoso chrome ─────────────────────────────────────────────────────@@ -122,6 +124,7 @@ export function ChatMessageList({hasOlderMessages = false,isFetchingOlderMessages = false,onLoadOlderMessages,+ transformContent,}: ChatMessageListProps) {const scrollRef = useRef<HTMLDivElement>(null);const [scrollContainerEl, setScrollContainerEl] = useState<HTMLDivElement | null>(null);@@ -154,8 +157,8 @@ export function ChatMessageList({// the array reference when a duplicate event arrives, so this recomputes// only when a genuinely new message lands — not on unrelated re-renders.const liveTimeline: ChatTimelineItem[] = useMemo(- () => buildTimeline(liveTaskMessages ?? []),- [liveTaskMessages],+ () => transformTimeline(buildTimeline(liveTaskMessages ?? []), transformContent),+ [liveTaskMessages, transformContent],);const hasLive = showLiveTimeline && liveTimeline.length > 0;const showStatusPill = !!pendingTaskId && !pendingAlreadyPersisted && !!pendingTask;@@ -206,6 +209,7 @@ export function ChatMessageList({<MessageBubblemessage={msg}isPending={!!pendingTaskId && msg.task_id === pendingTaskId}+ transformContent={transformContent}/></div>)}@@ -252,9 +256,11 @@ export function ChatMessageSkeleton() {const MessageBubble = memo(function MessageBubble({message,isPending,+ transformContent,}: {message: ChatMessage;isPending: boolean;+ transformContent?: (content: string) => string;}) {if (message.role === "user") {return (@@ -277,15 +283,23 @@ const MessageBubble = memo(function MessageBubble({);}- return <AssistantMessage message={message} isPending={isPending} />;+ return (+ <AssistantMessage+ message={message}+ isPending={isPending}+ transformContent={transformContent}+ />+ );});function AssistantMessage({message,isPending,+ transformContent,}: {message: ChatMessage;isPending: boolean;+ transformContent?: (content: string) => string;}) {const taskId = message.task_id;const canFetchTaskMessages = isTaskMessageTaskId(taskId);@@ -300,8 +314,8 @@ function AssistantMessage({// Same memoization rationale as the live timeline in ChatMessageList.const timeline: ChatTimelineItem[] = useMemo(- () => buildTimeline(taskMessages ?? []),- [taskMessages],+ () => transformTimeline(buildTimeline(taskMessages ?? []), transformContent),+ [taskMessages, transformContent],);// Failure bubble path: when the server's FailTask wrote a failure@@ -349,6 +363,18 @@ function AssistantMessage({);}+function transformTimeline(+ timeline: ChatTimelineItem[],+ transformContent?: (content: string) => string,+): ChatTimelineItem[] {+ if (!transformContent) return timeline;+ return timeline.map((item) =>+ item.type === "text" && item.content+ ? { ...item, content: transformContent(item.content) }+ : item,+ );+}+// Muted, localized notice shown in place of assistant text when a turn// completed with no reply (message_kind === "no_response"). Explains the empty// turn instead of rendering a blank bubble (MUL-4351).diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex afac8c57ef..6ac0a44fa1 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -260,6 +260,79 @@"discard_keep": "Keep editing","discard_confirm": "Discard changes"},+ "creation_studio": {+ "title": "Create an agent",+ "squad_title": "Create an agent for this squad",+ "duplicate_title": "Duplicate {{name}}",+ "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.",+ "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": {+ "blank": { "title": "Start blank", "description": "Configure every field yourself. Best when you already know exactly how this agent should work." },+ "template": { "title": "Use a template", "description": "Start from curated instructions and skills, then adapt every detail to your workspace." },+ "ai": { "title": "Build with AI", "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.",+ "behavior": "Behavior & capabilities",+ "behavior_hint": "Define how it should work and attach workspace skills it can rely on.",+ "execution": "Execution",+ "execution_hint": "Choose where the agent runs and optionally override the runtime's default model.",+ "access": "Access",+ "access_hint": "Control who can start runs with this agent. You can change this later."+ },+ "access": {+ "private": { "title": "Only me", "description": "Only you can run this agent." },+ "workspace": { "title": "Entire workspace", "description": "Every workspace member can run it." },+ "members": { "title": "Specific people", "description": "Only selected members can run it.", "required": "Select at least one member." }+ },+ "builder": {+ "setup_title": "Choose a runtime for Agent Builder",+ "setup_description": "The selected online runtime powers the setup conversation and becomes the new agent's runtime by default.",+ "start": "Start conversation",+ "connect_runtime": "Connect a runtime",+ "start_failed": "Could not start Agent Builder.",+ "send_failed": "Could not send your message.",+ "stop_failed": "Could not stop the current generation.",+ "chat_title": "Agent Builder",+ "chat_hint": "Shape the requirements through conversation and refine the configuration beside it.",+ "runtime_online": "Runtime online",+ "runtime_offline": "Runtime offline",+ "empty_title": "What should this agent do?",+ "empty_description": "Describe its role, workflow, output, or constraints. A useful first draft will appear on the right.",+ "prompt_review": "Review frontend pull requests",+ "prompt_research": "Research competitors and summarize findings",+ "prompt_assistant": "Help our team plan and write projects",+ "thinking": "Updating the draft…",+ "placeholder": "Describe the agent you need…",+ "send": "Send message"+ },+ "live_draft": "Agent configuration",+ "live_draft_hint": "Conversation updates appear here, and you can adjust any field directly.",+ "duplicate_env_notice": "Instructions, skills, model, and command arguments are copied. Environment variables are not copied for security.",+ "create_and_open": "Create & open agent",+ "create_and_add": "Create & add to squad",+ "creating": "Creating agent…",+ "create_failed": "Could not create the agent.",+ "created": "{{name}} was created"+ },"create_dialog": {"title_create": "Create Agent","title_duplicate": "Duplicate Agent",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 0af8b1b0dc..3565c070c7 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -679,6 +679,98 @@"section_owner": "オーナー","section_model": "モデル"},+ "creation_studio": {+ "title": "エージェントを作成",+ "squad_title": "このスクワッド用のエージェントを作成",+ "duplicate_title": "{{name}} を複製",+ "back": "戻る",+ "eyebrow": "エージェント作成",+ "choose_title": "どの方法で始めますか?",+ "choose_description": "すべて自分で設定するか、実績のあるテンプレートを調整するか、必要なものを説明して会話から作成できます。",+ "recommended": "おすすめ",+ "continue": "続ける",+ "step_choose": "開始方法を選択",+ "step_template": "テンプレートを選択",+ "step_configure": "確認して設定",+ "step_ai": "会話で作成",+ "modes": {+ "blank": {+ "title": "空白から始める",+ "description": "すべての項目を自分で設定します。エージェントの動作が明確に決まっている場合に最適です。"+ },+ "template": {+ "title": "テンプレートを使用",+ "description": "整理された指示とスキルを基に、ワークスペースに合わせて詳細を調整します。"+ },+ "ai": {+ "title": "AI で作成",+ "description": "期待する成果を説明すると、Agent Builder が重要な質問を行い、下書きをリアルタイムで作成します。"+ }+ },+ "templates": {+ "search": "テンプレートを検索…",+ "search_label": "エージェントテンプレートを検索",+ "empty": "検索に一致するテンプレートはありません。",+ "select_hint": "テンプレートを選択して、指示とスキルをプレビューします。",+ "skills": "含まれるスキル",+ "instructions": "指示",+ "use": "このテンプレートを使用"+ },+ "sections": {+ "identity": "基本情報",+ "identity_hint": "識別しやすい名前と簡潔な目的を設定します。",+ "behavior": "動作と機能",+ "behavior_hint": "動作方法を定義し、利用できるワークスペースのスキルを追加します。",+ "execution": "実行環境",+ "execution_hint": "エージェントを実行する場所を選び、必要に応じてランタイムの既定モデルを変更します。",+ "access": "アクセス",+ "access_hint": "このエージェントを実行できるユーザーを設定します。後から変更できます。"+ },+ "access": {+ "private": {+ "title": "自分のみ",+ "description": "このエージェントを実行できるのは自分だけです。"+ },+ "workspace": {+ "title": "ワークスペース全体",+ "description": "すべてのワークスペースメンバーが実行できます。"+ },+ "members": {+ "title": "特定のメンバー",+ "description": "選択したメンバーだけが実行できます。",+ "required": "メンバーを1人以上選択してください。"+ }+ },+ "builder": {+ "setup_title": "Agent Builder のランタイムを選択",+ "setup_description": "選択したオンラインのランタイムが設定会話を実行し、新しいエージェントの既定ランタイムになります。",+ "start": "会話を開始",+ "connect_runtime": "ランタイムを接続",+ "start_failed": "Agent Builder を開始できませんでした。",+ "send_failed": "メッセージを送信できませんでした。",+ "stop_failed": "現在の生成を停止できませんでした。",+ "chat_title": "Agent Builder",+ "chat_hint": "会話で要件を整理し、隣の設定を調整します。",+ "runtime_online": "ランタイムはオンライン",+ "runtime_offline": "ランタイムはオフライン",+ "empty_title": "このエージェントに何をさせますか?",+ "empty_description": "役割、ワークフロー、出力、制約を説明してください。右側に最初の下書きが表示されます。",+ "prompt_review": "フロントエンドの Pull Request をレビュー",+ "prompt_research": "競合を調査して結果を要約",+ "prompt_assistant": "チームのプロジェクト計画と文章作成を支援",+ "thinking": "下書きを更新中…",+ "placeholder": "必要なエージェントを説明…",+ "send": "メッセージを送信"+ },+ "live_draft": "エージェント設定",+ "live_draft_hint": "会話内容がここに反映され、各項目を直接調整できます。",+ "duplicate_env_notice": "指示、スキル、モデル、コマンド引数がコピーされます。セキュリティ上、環境変数はコピーされません。",+ "create_and_open": "作成して開く",+ "create_and_add": "作成してスクワッドに追加",+ "creating": "エージェントを作成中…",+ "create_failed": "エージェントを作成できませんでした。",+ "created": "{{name}} を作成しました"+ },"actions": {"selected_other": "{{count}} 件選択中","clear_selection": "選択を解除"diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex cf3af40b93..472df910ed 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -679,6 +679,98 @@"section_owner": "소유자","section_model": "모델"},+ "creation_studio": {+ "title": "에이전트 만들기",+ "squad_title": "이 스쿼드용 에이전트 만들기",+ "duplicate_title": "{{name}} 복제",+ "back": "뒤로",+ "eyebrow": "에이전트 만들기",+ "choose_title": "어떻게 시작하시겠어요?",+ "choose_description": "모든 항목을 직접 설정하거나, 검증된 템플릿을 수정하거나, 필요한 내용을 설명하고 대화로 만들 수 있습니다.",+ "recommended": "추천",+ "continue": "계속",+ "step_choose": "시작 방법 선택",+ "step_template": "템플릿 선택",+ "step_configure": "검토 및 설정",+ "step_ai": "대화로 만들기",+ "modes": {+ "blank": {+ "title": "빈 상태로 시작",+ "description": "모든 항목을 직접 설정합니다. 에이전트의 동작 방식을 정확히 알고 있을 때 적합합니다."+ },+ "template": {+ "title": "템플릿 사용",+ "description": "정리된 지침과 스킬을 바탕으로 워크스페이스에 맞게 세부 항목을 조정합니다."+ },+ "ai": {+ "title": "AI로 만들기",+ "description": "원하는 결과를 설명하면 Agent Builder가 핵심 질문을 하고 실시간 초안을 준비합니다."+ }+ },+ "templates": {+ "search": "템플릿 검색…",+ "search_label": "에이전트 템플릿 검색",+ "empty": "검색과 일치하는 템플릿이 없습니다.",+ "select_hint": "템플릿을 선택하여 지침과 스킬을 미리 확인하세요.",+ "skills": "포함된 스킬",+ "instructions": "지침",+ "use": "이 템플릿 사용"+ },+ "sections": {+ "identity": "기본 정보",+ "identity_hint": "알아보기 쉬운 이름과 간결한 목적을 지정하세요.",+ "behavior": "동작 및 기능",+ "behavior_hint": "작업 방식을 정의하고 사용할 워크스페이스 스킬을 추가하세요.",+ "execution": "실행",+ "execution_hint": "에이전트를 실행할 위치를 선택하고 필요하면 런타임 기본 모델을 변경하세요.",+ "access": "접근 권한",+ "access_hint": "이 에이전트를 실행할 수 있는 사용자를 설정합니다. 나중에 변경할 수 있습니다."+ },+ "access": {+ "private": {+ "title": "나만",+ "description": "나만 이 에이전트를 실행할 수 있습니다."+ },+ "workspace": {+ "title": "전체 워크스페이스",+ "description": "모든 워크스페이스 멤버가 실행할 수 있습니다."+ },+ "members": {+ "title": "특정 멤버",+ "description": "선택한 멤버만 실행할 수 있습니다.",+ "required": "멤버를 한 명 이상 선택하세요."+ }+ },+ "builder": {+ "setup_title": "Agent Builder 런타임 선택",+ "setup_description": "선택한 온라인 런타임이 설정 대화를 실행하고 새 에이전트의 기본 런타임이 됩니다.",+ "start": "대화 시작",+ "connect_runtime": "런타임 연결",+ "start_failed": "Agent Builder를 시작하지 못했습니다.",+ "send_failed": "메시지를 보내지 못했습니다.",+ "stop_failed": "현재 생성을 중지하지 못했습니다.",+ "chat_title": "Agent Builder",+ "chat_hint": "대화로 요구 사항을 정리하고 옆의 설정을 다듬으세요.",+ "runtime_online": "런타임 온라인",+ "runtime_offline": "런타임 오프라인",+ "empty_title": "이 에이전트는 무엇을 해야 하나요?",+ "empty_description": "역할, 작업 흐름, 출력 또는 제약 사항을 설명하세요. 오른쪽에 첫 초안이 표시됩니다.",+ "prompt_review": "프런트엔드 Pull Request 검토",+ "prompt_research": "경쟁사를 조사하고 결과 요약",+ "prompt_assistant": "팀의 프로젝트 계획과 작성 지원",+ "thinking": "초안 업데이트 중…",+ "placeholder": "필요한 에이전트를 설명하세요…",+ "send": "메시지 보내기"+ },+ "live_draft": "에이전트 설정",+ "live_draft_hint": "대화 내용이 여기에 반영되며 각 항목을 직접 조정할 수 있습니다.",+ "duplicate_env_notice": "지침, 스킬, 모델 및 명령 인수는 복사됩니다. 보안을 위해 환경 변수는 복사되지 않습니다.",+ "create_and_open": "만들고 열기",+ "create_and_add": "만들고 스쿼드에 추가",+ "creating": "에이전트 만드는 중…",+ "create_failed": "에이전트를 만들지 못했습니다.",+ "created": "{{name}}을(를) 만들었습니다"+ },"actions": {"selected_other": "{{count}}개 선택됨","clear_selection": "선택 해제"diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex 8e54dbbb24..fbe96954ab 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -251,6 +251,79 @@"discard_keep": "继续编辑","discard_confirm": "放弃修改"},+ "creation_studio": {+ "title": "创建智能体",+ "squad_title": "为小队创建智能体",+ "duplicate_title": "复制 {{name}}",+ "back": "返回",+ "eyebrow": "创建智能体",+ "choose_title": "你想从哪里开始?",+ "choose_description": "从空白配置、基于成熟模板修改,或者直接描述需求,通过对话完成创建。",+ "recommended": "推荐",+ "continue": "继续",+ "step_choose": "选择起点",+ "step_template": "选择模板",+ "step_configure": "检查并配置",+ "step_ai": "通过对话创建",+ "modes": {+ "blank": { "title": "从空白开始", "description": "自己配置每个字段。适合已经明确知道智能体应该如何工作的用户。" },+ "template": { "title": "使用模板", "description": "从整理好的指令和 skill 开始,再根据工作区需要修改每个细节。" },+ "ai": { "title": "通过 AI 创建", "description": "描述你想要的结果。Agent Builder 会提出关键问题并实时生成草稿。" }+ },+ "templates": {+ "search": "搜索模板…",+ "search_label": "搜索智能体模板",+ "empty": "没有匹配的模板。",+ "select_hint": "选择一个模板,预览它的指令和 skill。",+ "skills": "包含的 skill",+ "instructions": "指令",+ "use": "使用此模板"+ },+ "sections": {+ "identity": "身份",+ "identity_hint": "为智能体设置容易识别的名称和简洁的用途。",+ "behavior": "行为与能力",+ "behavior_hint": "定义它的工作方式,并添加可使用的工作区 skill。",+ "execution": "运行方式",+ "execution_hint": "选择智能体使用的运行时,也可以覆盖运行时的默认模型。",+ "access": "访问权限",+ "access_hint": "控制谁可以运行此智能体,创建后仍可修改。"+ },+ "access": {+ "private": { "title": "只有我", "description": "只有你可以运行此智能体。" },+ "workspace": { "title": "整个工作区", "description": "工作区中的所有成员都可以运行。" },+ "members": { "title": "指定成员", "description": "只有选中的成员可以运行。", "required": "请至少选择一位成员。" }+ },+ "builder": {+ "setup_title": "为 Agent Builder 选择运行时",+ "setup_description": "所选的在线运行时将用于创建对话,并默认成为新智能体的运行时。",+ "start": "开始对话",+ "connect_runtime": "连接运行时",+ "start_failed": "无法启动 Agent Builder。",+ "send_failed": "无法发送消息。",+ "stop_failed": "无法停止当前生成任务。",+ "chat_title": "Agent Builder",+ "chat_hint": "通过对话梳理需求,并持续完善右侧配置。",+ "runtime_online": "运行时在线",+ "runtime_offline": "运行时离线",+ "empty_title": "这个智能体需要做什么?",+ "empty_description": "描述它的角色、工作流程、输出或约束,右侧会生成第一版草稿。",+ "prompt_review": "审查前端 Pull Request",+ "prompt_research": "研究竞品并整理结论",+ "prompt_assistant": "帮助团队规划和撰写项目",+ "thinking": "正在更新草稿…",+ "placeholder": "描述你需要的智能体…",+ "send": "发送消息"+ },+ "live_draft": "智能体配置",+ "live_draft_hint": "对话生成的建议会更新到这里,你也可以随时直接调整。",+ "duplicate_env_notice": "指令、skill、模型和命令行参数会被复制。出于安全考虑,环境变量不会复制。",+ "create_and_open": "创建并打开",+ "create_and_add": "创建并加入小队",+ "creating": "正在创建…",+ "create_failed": "无法创建智能体。",+ "created": "已创建 {{name}}"+ },"create_dialog": {"title_create": "创建智能体","title_duplicate": "复制智能体",diff --git a/packages/views/squads/components/squad-detail-page.tsx b/packages/views/squads/components/squad-detail-page.tsxindex 31fd4d6791..ac720c0216 100644--- a/packages/views/squads/components/squad-detail-page.tsx+++ b/packages/views/squads/components/squad-detail-page.tsx@@ -11,8 +11,6 @@ import { isImeComposing } from "@multica/core/utils";import { getShortcut, shortcutMatchesEvent } from "@multica/core/shortcuts";import { useTimeAgo } from "../../i18n";import { agentListOptions, memberListOptions, squadMemberStatusOptions, workspaceKeys } from "@multica/core/workspace/queries";-import { runtimeListOptions } from "@multica/core/runtimes";-import { CreateAgentDialog } from "../../agents/components/create-agent-dialog";import { useNavigation } from "../../navigation";import { AppLink } from "../../navigation";import { BreadcrumbHeader } from "../../layout/breadcrumb-header";@@ -61,7 +59,7 @@ import {} from "../../issues/components/pickers/property-picker";import { ChevronDown, UserPlus } from "lucide-react";import { toast } from "sonner";-import type { Squad, SquadMember, SquadMemberStatus, SquadMemberStatusValue, Agent, CreateAgentRequest, MemberWithUser } from "@multica/core/types";+import type { Squad, SquadMember, SquadMemberStatus, SquadMemberStatusValue, Agent, MemberWithUser } from "@multica/core/types";import { useT } from "../../i18n";import { matchesPinyin } from "../../editor/extensions/pinyin-match";@@ -103,10 +101,6 @@ export function SquadDetailPage() {const { data: agents = [] } = useQuery(agentListOptions(wsId));const { data: wsMembers = [] } = useQuery(memberListOptions(wsId));- // Runtimes are only fetched when the Create Agent dialog might open;- // gating on canManage below means users who can't manage this squad never- // trigger the request. The runtime list mirrors the agents page so the- // picker (and the "only my runtimes" filter) behaves identically here.const currentUser = useAuthStore((s) => s.user);const myRole = useMemo(() => {if (!currentUser) return null;@@ -121,13 +115,7 @@ export function SquadDetailPage() {const canManage =isWorkspaceAdmin || (!!currentUser && squad?.creator_id === currentUser.id);- const { data: runtimes = [], isLoading: runtimesLoading } = useQuery({- ...runtimeListOptions(wsId),- enabled: !!wsId && canManage,- });-const [showAddMember, setShowAddMember] = useState(false);- const [showCreateAgent, setShowCreateAgent] = useState(false);const [confirmArchive, setConfirmArchive] = useState(false);const updateSquadMut = useMutation({@@ -189,25 +177,6 @@ export function SquadDetailPage() {toast.error(err instanceof Error && err.message ? err.message : "Failed to archive squad"),});- // CreateAgentDialog's onCreate contract: hit POST /api/agents and- // return the created agent so the dialog can run its skill follow-up.- // We deliberately do NOT navigate to the agent detail page (that's- // the agents-page behaviour) — the user clicked Create Agent from- // inside this squad, so the dialog will stay open just long enough- // to also call addSquadMember (handled by the dialog when squadId- // is set), then close the user back to Members where they can- // verify the new agent appeared. Cache-update keeps the agents list- // fresh for any pickers that read from it.- const handleCreateAgent = async (data: CreateAgentRequest): Promise<Agent> => {- const agent = await api.createAgent(data);- queryClient.setQueryData<Agent[]>(workspaceKeys.agents(wsId), (current = []) => {- const exists = current.some((a) => a.id === agent.id);- return exists ? current.map((a) => (a.id === agent.id ? agent : a)) : [...current, agent];- });- queryClient.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });- return agent;- };-const getEntityName = (type: string, id: string) => {if (type === "agent") return agents.find((a: Agent) => a.id === id)?.name ?? id.slice(0, 8);return wsMembers.find((m) => m.user_id === id)?.name ?? id.slice(0, 8);@@ -274,7 +243,7 @@ export function SquadDetailPage() {isArchived={isArchived}getEntityName={getEntityName}onAddMemberClick={() => setShowAddMember(true)}- onCreateAgentClick={canManage ? () => setShowCreateAgent(true) : undefined}+ onCreateAgentClick={canManage ? () => push(`${p.newAgent()}?squad=${encodeURIComponent(squadId)}`) : undefined}onSetLeader={(id) => setLeaderMut.mutate(id)}onRemoveMember={(m) => removeMemberMut.mutate(m)}onUpdateRole={async (m, role) => { await updateRoleMut.mutateAsync({ member: m, role }); }}@@ -292,25 +261,6 @@ export function SquadDetailPage() {/>)}- {/* Squad-scoped create flow: same dialog as the Agents page but- with squadId set, so the dialog runs api.addSquadMember after- api.createAgent and skips the agent-detail navigation. Only- mounted for users who can manage this squad (workspace owner/admin- or the creator); for everyone else the trigger never renders. The- newly created agent is owned by the creator, so it is always one- they can invoke and add to the squad. */}- {showCreateAgent && canManage && (- <CreateAgentDialog- runtimes={runtimes}- runtimesLoading={runtimesLoading}- members={wsMembers}- currentUserId={currentUser?.id ?? null}- squadId={squadId}- onClose={() => setShowCreateAgent(false)}- onCreate={handleCreateAgent}- />- )}-{confirmArchive && (<AlertDialogopendiff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex f01bf5aaa4..1c1a138546 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1164,6 +1164,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/", h.ListAgentTemplates)r.Get("/{slug}", h.GetAgentTemplate)})+ r.Post("/api/agent-builder/sessions", h.CreateAgentBuilderSession)// Skillsr.Route("/api/skills", func(r chi.Router) {diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex e49beee642..512f71ab0e 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -308,37 +308,37 @@ type AgentTaskResponse struct {// when WorkDir is empty, or when stripping leaves nothing. See// relativeWorkDir() for the full rules. Older clients can still read// WorkDir directly; newer UIs should prefer RelativeWorkDir.- RelativeWorkDir string `json:"relative_work_dir,omitempty"`- TriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this task- CoalescedCommentIDs []string `json:"coalesced_comment_ids,omitempty"` // MUL-4195: earlier comments folded into this run when it had not yet started, so a single run still covers every deliberate comment; trigger_comment_id is the newest. Surfaced so the UI can show which comments a run covered. omitempty so old clients ignore it- CoalescedComments []CoalescedCommentData `json:"coalesced_comments,omitempty"` // MUL-4195: full detail (thread_id/author/created_at/content) of the folded comments, so the daemon prompt can address each without assuming they share the triggering thread. omitempty so old clients ignore it- DeliveredCommentIDs []string `json:"delivered_comment_ids"` // always present: [] is an authoritative empty receipt, while field absence identifies responses from legacy servers- TriggerThreadID string `json:"trigger_thread_id,omitempty"` // root comment ID for the triggering thread- TriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering comment- TriggerSummary *string `json:"trigger_summary,omitempty"` // canonical short description snapshot — comment text / autopilot title — taken at task creation; survives source edits/deletes- TriggerAuthorType string `json:"trigger_author_type,omitempty"` // "agent" or "member" — author kind of the triggering comment- TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author- NewCommentCount int `json:"new_comment_count,omitempty"` // trigger-thread comments since last run; excludes injected trigger + own comments; omitempty so old daemons ignore it- NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; omitempty so old daemons ignore it- ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks- ChatChannelType string `json:"chat_channel_type,omitempty"` // "slack" when the chat session is backed by an IM channel; empty for a web-only chat. Makes the agent channel-aware (read history from the channel, not Multica)- ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; tells the agent to start with `multica chat thread` vs `multica chat history`- ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks- ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entry- ChatIntro bool `json:"chat_intro,omitempty"` // true for the agent's proactive self-introduction chat (is_agent_intro session, no user message); the daemon builds an intro prompt instead of a reply prompt- AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot-spawned tasks- AutopilotID string `json:"autopilot_id,omitempty"` // autopilot that spawned this task- AutopilotTitle string `json:"autopilot_title,omitempty"` // autopilot title used as task context- AutopilotDescription string `json:"autopilot_description,omitempty"` // autopilot description used as task prompt- AutopilotSource string `json:"autopilot_source,omitempty"` // manual, schedule, webhook, or api- AutopilotTriggerPayload json.RawMessage `json:"autopilot_trigger_payload,omitempty"` // optional trigger payload for webhook/api runs- QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks- QuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids,omitempty"` // attachment ids uploaded in the quick-create prompt and bound on issue create- HandoffNote string `json:"handoff_note,omitempty"` // assignment handoff instruction; rendered into the run's opening prompt + issue_context.md (omitempty so old daemons ignore it)- SquadID string `json:"squad_id,omitempty"` // for quick-create tasks where the picker was a squad; Agent is still the resolved leader- SquadName string `json:"squad_name,omitempty"` // display name for the picker squad- ParentIssueID string `json:"parent_issue_id,omitempty"` // for quick-create tasks opened from "Add sub issue" — UUID of the parent issue the new issue should be filed under- ParentIssueIdentifier string `json:"parent_issue_identifier,omitempty"` // human-readable identifier (e.g. MUL-123) of the quick-create parent issue, resolved on claim for prompt context+ RelativeWorkDir string `json:"relative_work_dir,omitempty"`+ TriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this task+ CoalescedCommentIDs []string `json:"coalesced_comment_ids,omitempty"` // MUL-4195: earlier comments folded into this run when it had not yet started, so a single run still covers every deliberate comment; trigger_comment_id is the newest. Surfaced so the UI can show which comments a run covered. omitempty so old clients ignore it+ CoalescedComments []CoalescedCommentData `json:"coalesced_comments,omitempty"` // MUL-4195: full detail (thread_id/author/created_at/content) of the folded comments, so the daemon prompt can address each without assuming they share the triggering thread. omitempty so old clients ignore it+ DeliveredCommentIDs []string `json:"delivered_comment_ids"` // always present: [] is an authoritative empty receipt, while field absence identifies responses from legacy servers+ TriggerThreadID string `json:"trigger_thread_id,omitempty"` // root comment ID for the triggering thread+ TriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering comment+ TriggerSummary *string `json:"trigger_summary,omitempty"` // canonical short description snapshot — comment text / autopilot title — taken at task creation; survives source edits/deletes+ TriggerAuthorType string `json:"trigger_author_type,omitempty"` // "agent" or "member" — author kind of the triggering comment+ TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author+ NewCommentCount int `json:"new_comment_count,omitempty"` // trigger-thread comments since last run; excludes injected trigger + own comments; omitempty so old daemons ignore it+ NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; omitempty so old daemons ignore it+ ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks+ ChatChannelType string `json:"chat_channel_type,omitempty"` // "slack" when the chat session is backed by an IM channel; empty for a web-only chat. Makes the agent channel-aware (read history from the channel, not Multica)+ ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; tells the agent to start with `multica chat thread` vs `multica chat history`+ ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks+ ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entry+ ChatIntro bool `json:"chat_intro,omitempty"` // true for the agent's proactive self-introduction chat (is_agent_intro session, no user message); the daemon builds an intro prompt instead of a reply prompt+ AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot-spawned tasks+ AutopilotID string `json:"autopilot_id,omitempty"` // autopilot that spawned this task+ AutopilotTitle string `json:"autopilot_title,omitempty"` // autopilot title used as task context+ AutopilotDescription string `json:"autopilot_description,omitempty"` // autopilot description used as task prompt+ AutopilotSource string `json:"autopilot_source,omitempty"` // manual, schedule, webhook, or api+ AutopilotTriggerPayload json.RawMessage `json:"autopilot_trigger_payload,omitempty"` // optional trigger payload for webhook/api runs+ QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks+ QuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids,omitempty"` // attachment ids uploaded in the quick-create prompt and bound on issue create+ HandoffNote string `json:"handoff_note,omitempty"` // assignment handoff instruction; rendered into the run's opening prompt + issue_context.md (omitempty so old daemons ignore it)+ SquadID string `json:"squad_id,omitempty"` // for quick-create tasks where the picker was a squad; Agent is still the resolved leader+ SquadName string `json:"squad_name,omitempty"` // display name for the picker squad+ ParentIssueID string `json:"parent_issue_id,omitempty"` // for quick-create tasks opened from "Add sub issue" — UUID of the parent issue the new issue should be filed under+ ParentIssueIdentifier string `json:"parent_issue_identifier,omitempty"` // human-readable identifier (e.g. MUL-123) of the quick-create parent issue, resolved on claim for prompt context// RequestingUserName + RequestingUserProfileDescription mirror the user// the agent is acting on behalf of (see daemon/types.go). v1 sources them// from the runtime owner so they're populated for daemon runtimes and@@ -801,6 +801,9 @@ type CreateAgentRequest struct {// event still fires with `template=""`, which is the correct signal// for "manually authored agent".Template string `json:"template"`+ // SkillIDs are attached inside the same transaction as the agent row so a+ // create never becomes visible in a partially configured state.+ SkillIDs []string `json:"skill_ids"`}func decodeJSONBodyWithRawFields(body io.Reader, dst any) (map[string]json.RawMessage, error) {@@ -950,7 +953,29 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {allowlist = nil}- created, err := h.Queries.CreateAgent(r.Context(), db.CreateAgentParams{+ skillUUIDs, ok := parseUUIDSliceOrBadRequest(w, req.SkillIDs, "skill_ids")+ if !ok {+ return+ }+ for _, skillID := range skillUUIDs {+ if _, err := h.Queries.GetSkillInWorkspace(r.Context(), db.GetSkillInWorkspaceParams{+ ID: skillID,+ WorkspaceID: wsUUID,+ }); err != nil {+ writeError(w, http.StatusBadRequest, "skill does not belong to this workspace")+ return+ }+ }++ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to start agent create transaction")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)++ created, err := qtx.CreateAgent(r.Context(), db.CreateAgentParams{WorkspaceID: wsUUID,Name: req.Name,Description: req.Description,@@ -982,14 +1007,24 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to create agent: "+err.Error())return}- slog.Info("agent created", append(logger.RequestAttrs(r), "agent_id", uuidToString(created.ID), "name", created.Name, "workspace_id", workspaceID)...)-- // Persist the invocation allow-list (MUL-3963). Best-effort log on failure- // but do not fail the create — the agent row already exists and defaults- // to no targets (deny-by-default private).- if err := h.replaceInvocationTargets(r.Context(), created.ID, parseUUID(ownerID), perm.targets); err != nil {- slog.Warn("create agent: persist invocation targets failed", append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(created.ID))...)+ if err := replaceInvocationTargetsWithQueries(r.Context(), qtx, created.ID, parseUUID(ownerID), perm.targets); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to save agent access")+ return+ }+ for _, skillID := range skillUUIDs {+ if err := qtx.AddAgentSkill(r.Context(), db.AddAgentSkillParams{+ AgentID: created.ID,+ SkillID: skillID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to attach agent skill")+ return+ }+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to commit agent create")+ return}+ slog.Info("agent created", append(logger.RequestAttrs(r), "agent_id", uuidToString(created.ID), "name", created.Name, "workspace_id", workspaceID)...)if runtime.Status == "online" {h.TaskService.ReconcileAgentStatus(r.Context(), created.ID)@@ -997,14 +1032,17 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {}resp := agentToResponse(created)+ if err := h.attachAgentSkills(r.Context(), &resp, created.ID); err != nil {+ slog.Warn("create agent: load skills for response failed", append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(created.ID))...)+ }if err := h.enrichAgentResponseWithTargets(r.Context(), &resp, created.ID); err != nil {slog.Warn("create agent: load invocation targets for response failed", append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(created.ID))...)}actorType, actorID := h.resolveActor(r, ownerID, workspaceID)h.publish(protocol.EventAgentCreated, workspaceID, actorType, actorID, map[string]any{"agent": broadcastAgentResponse(resp)})- // Kick off a "meet your new agent" chat so the agent introduces itself- // (LLM-generated via a real run, not a canned template). Best effort.+ // Start the existing proactive introduction only after the complete Agent+ // configuration has committed, so the first run sees its skills and access.h.sendAgentWelcomeChat(r.Context(), created, ownerID, workspaceID)obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.AgentCreated(diff --git a/server/internal/handler/agent_builder.go b/server/internal/handler/agent_builder.gonew file mode 100644index 0000000000..e66f6c537e--- /dev/null+++ b/server/internal/handler/agent_builder.go@@ -0,0 +1,146 @@+package handler++import (+ "encoding/json"+ "fmt"+ "net/http"+ "strings"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const agentBuilderInstructions = `You are Multica Agent Builder. Help the user design one practical AI agent through a short conversation.++Your job is to propose and refine configuration, never to create resources yourself. Ask only questions that materially change behavior. Prefer making a reasonable draft immediately, then ask at most two focused questions per turn.++Every response MUST end with exactly one <agent_draft> JSON block using this shape:+<agent_draft>{"name":"","description":"","instructions":"","model":"","skill_ids":[],"permission_scope":"private","member_ids":[]}</agent_draft>++Rules:+- The JSON must be valid, compact JSON on one physical line. Do not wrap it in Markdown fences.+- Escape every line break inside instructions as \n. Never place a literal newline inside a JSON string.+- Preserve good existing draft fields supplied in the user's message unless the user asks to change them.+- name is concise and suitable for a workspace list.+- description is one sentence, at most 200 characters.+- instructions are a complete Markdown system prompt describing role, workflow, output, and constraints.+- skill_ids may only contain IDs explicitly listed in AVAILABLE WORKSPACE SKILLS.+- permission_scope must be private, workspace, or members. Default to private unless the user explicitly requests sharing.+- member_ids may only contain IDs explicitly listed in AVAILABLE WORKSPACE MEMBERS, and only when permission_scope is members.+- Never request, expose, or place secrets, tokens, passwords, or environment-variable values in the draft.+- Do not claim that the agent has been created. The user must review and confirm the draft in the UI.`++type CreateAgentBuilderSessionRequest struct {+ RuntimeID string `json:"runtime_id"`+ Model string `json:"model,omitempty"`+}++type CreateAgentBuilderSessionResponse struct {+ SessionID string `json:"session_id"`+ BuilderAgentID string `json:"builder_agent_id"`+ RuntimeID string `json:"runtime_id"`+}++// CreateAgentBuilderSession starts a private configuration conversation on an+// existing runtime. A hidden system agent is the execution carrier because the+// chat/task pipeline is intentionally agent-backed; it never appears in normal+// agent lists and cannot be selected as an assignee.+func (h *Handler) CreateAgentBuilderSession(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }++ var req CreateAgentBuilderSessionRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ runtimeID := strings.TrimSpace(req.RuntimeID)+ if runtimeID == "" {+ writeError(w, http.StatusBadRequest, "runtime_id is required")+ return+ }++ workspaceUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")+ if !ok {+ return+ }+ runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{+ ID: runtimeUUID,+ WorkspaceID: workspaceUUID,+ })+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid runtime_id")+ return+ }+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return+ }+ if !canUseRuntimeForAgent(member, runtime) {+ writeError(w, http.StatusForbidden, "this runtime is private; only its owner or a workspace admin can use it")+ return+ }+ if runtime.Status != "online" {+ writeError(w, http.StatusConflict, "runtime must be online to start an agent builder session")+ return+ }++ flowID := uuid.NewString()+ ownerUUID := parseUUID(userID)+ model := strings.TrimSpace(req.Model)+ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to start agent builder session")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)++ builder, err := qtx.CreateAgentBuilder(r.Context(), db.CreateAgentBuilderParams{+ WorkspaceID: workspaceUUID,+ Name: fmt.Sprintf(".multica-agent-builder-%s", flowID),+ RuntimeMode: runtime.RuntimeMode,+ RuntimeID: runtime.ID,+ OwnerID: ownerUUID,+ Instructions: agentBuilderInstructions,+ Model: pgtype.Text{String: model, Valid: model != ""},+ SystemKey: pgtype.Text{+ String: fmt.Sprintf("agent_builder:%s", flowID),+ Valid: true,+ },+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to prepare agent builder")+ return+ }++ session, err := qtx.CreateChatSession(r.Context(), db.CreateChatSessionParams{+ WorkspaceID: workspaceUUID,+ AgentID: builder.ID,+ CreatorID: ownerUUID,+ Title: "Create an agent",+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create agent builder session")+ return+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to commit agent builder session")+ return+ }++ writeJSON(w, http.StatusCreated, CreateAgentBuilderSessionResponse{+ SessionID: uuidToString(session.ID),+ BuilderAgentID: uuidToString(builder.ID),+ RuntimeID: runtimeID,+ })+}diff --git a/server/internal/handler/agent_builder_test.go b/server/internal/handler/agent_builder_test.gonew file mode 100644index 0000000000..a59ed4eade--- /dev/null+++ b/server/internal/handler/agent_builder_test.go@@ -0,0 +1,149 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestCreateAgentBuilderSessionCreatesIsolatedHiddenBuilder(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `+ DELETE FROM agent+ WHERE workspace_id = $1 AND kind = 'system' AND system_key LIKE 'agent_builder:%'+ `, testWorkspaceID)+ })++ create := func(model string) CreateAgentBuilderSessionResponse {+ w := httptest.NewRecorder()+ testHandler.CreateAgentBuilderSession(w, newRequest(http.MethodPost, "/api/agent-builder/sessions", map[string]any{+ "runtime_id": testRuntimeID,+ "model": model,+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateAgentBuilderSession: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var response CreateAgentBuilderSessionResponse+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if response.SessionID == "" || response.BuilderAgentID == "" {+ t.Fatalf("missing builder identifiers: %+v", response)+ }+ return response+ }++ first := create("builder-model-a")+ second := create("builder-model-b")+ if first.BuilderAgentID == second.BuilderAgentID {+ t.Fatalf("builder sessions unexpectedly shared an agent: %s", first.BuilderAgentID)+ }+ if first.SessionID == second.SessionID {+ t.Fatalf("each creation flow must receive a fresh chat session")+ }++ var kind, systemKey, firstModel string+ if err := testPool.QueryRow(context.Background(), `+ SELECT kind, system_key, model FROM agent WHERE id = $1+ `, first.BuilderAgentID).Scan(&kind, &systemKey, &firstModel); err != nil {+ t.Fatalf("load builder agent: %v", err)+ }+ if kind != "system" || !strings.HasPrefix(systemKey, "agent_builder:") {+ t.Fatalf("unexpected builder identity kind=%q system_key=%q", kind, systemKey)+ }+ if firstModel != "builder-model-a" {+ t.Fatalf("first builder model was mutated: got %q", firstModel)+ }++ w := httptest.NewRecorder()+ testHandler.ListAgents(w, newRequest(http.MethodGet, "/api/agents", nil))+ if w.Code != http.StatusOK {+ t.Fatalf("ListAgents: %d: %s", w.Code, w.Body.String())+ }+ var listed []AgentResponse+ if err := json.Unmarshal(w.Body.Bytes(), &listed); err != nil {+ t.Fatalf("decode agent list: %v", err)+ }+ for _, agent := range listed {+ if agent.ID == first.BuilderAgentID {+ t.Fatalf("system builder leaked into the user-facing agent list")+ }+ }++ // Knowing the ID must not expose system infrastructure through the public+ // Agent detail/update/archive loaders.+ w = httptest.NewRecorder()+ req := withURLParams(newRequest(http.MethodGet, "/api/agents/"+first.BuilderAgentID, nil), "id", first.BuilderAgentID)+ testHandler.GetAgent(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("GetAgent(system): expected 404, got %d: %s", w.Code, w.Body.String())+ }++ // Deleting the private Builder chat also removes its session-scoped hidden+ // Agent, so completed/cancelled flows do not accumulate infrastructure rows.+ w = httptest.NewRecorder()+ req = withURLParams(newRequest(http.MethodDelete, "/api/chat/sessions/"+first.SessionID, nil), "sessionId", first.SessionID)+ req = withChatTestWorkspaceCtx(t, req)+ testHandler.DeleteChatSession(w, req)+ if w.Code != http.StatusNoContent {+ t.Fatalf("DeleteChatSession(builder): expected 204, got %d: %s", w.Code, w.Body.String())+ }+ var remaining int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM agent WHERE id = $1`, first.BuilderAgentID).Scan(&remaining); err != nil {+ t.Fatalf("count deleted builder: %v", err)+ }+ if remaining != 0 {+ t.Fatalf("builder agent survived chat deletion")+ }+}++func TestCreateAgentAttachesSkillsInCreateTransaction(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ var skillID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO skill (workspace_id, name, description, content, config, created_by)+ VALUES ($1, 'Atomic Create Skill', '', '# Atomic', '{}'::jsonb, $2)+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&skillID); err != nil {+ t.Fatalf("create skill fixture: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent WHERE workspace_id = $1 AND name = 'Atomic Skill Agent'`, testWorkspaceID)+ _, _ = testPool.Exec(context.Background(), `DELETE FROM skill WHERE id = $1`, skillID)+ })++ w := httptest.NewRecorder()+ testHandler.CreateAgent(w, newRequest(http.MethodPost, "/api/agents", map[string]any{+ "name": "Atomic Skill Agent",+ "runtime_id": testRuntimeID,+ "skill_ids": []string{skillID},+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateAgent: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var response AgentResponse+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if len(response.Skills) != 1 || response.Skills[0].ID != skillID {+ t.Fatalf("create response did not include attached skill: %+v", response.Skills)+ }+ var introSessions int+ if err := testPool.QueryRow(ctx, `+ SELECT count(*) FROM chat_session WHERE agent_id = $1 AND is_agent_intro = true+ `, response.ID).Scan(&introSessions); err != nil {+ t.Fatalf("count welcome chat sessions: %v", err)+ }+ if introSessions != 1 {+ t.Fatalf("welcome chat sessions = %d, want 1", introSessions)+ }+}diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex 50d93b1193..564d93e310 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -474,6 +474,10 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to delete chat session")return}+ if err := qtx.DeleteSystemAgentByID(r.Context(), session.AgentID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to clean up chat session agent")+ return+ }if err := tx.Commit(r.Context()); err != nil {slog.Warn("commit chat session delete failed", "session_id", sessionID, "error", err)diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex fde3df44c2..5120b578ef 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -809,6 +809,10 @@ func (h *Handler) loadAgentForUser(w http.ResponseWriter, r *http.Request, agentwriteError(w, http.StatusNotFound, "agent not found")return db.Agent{}, false}+ if agent.Kind != "user" {+ writeError(w, http.StatusNotFound, "agent not found")+ return db.Agent{}, false+ }return agent, true}diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex c3c948a305..77df0608cb 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -776,6 +776,10 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")return}+ if err := qtx.DeleteSystemAgentsByRuntime(r.Context(), rt.ID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to clean up system agents")+ return+ }if err := qtx.DeleteAgentRuntime(r.Context(), rt.ID); err != nil {writeError(w, http.StatusInternalServerError, "failed to delete runtime")@@ -1032,6 +1036,10 @@ func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.RwriteError(w, http.StatusInternalServerError, "failed to clean up archived agents")return}+ if err := qtx.DeleteSystemAgentsByRuntime(r.Context(), rt.ID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to clean up system agents")+ return+ }// 5. Finally delete the runtime row itself.if err := qtx.DeleteAgentRuntime(r.Context(), rt.ID); err != nil {diff --git a/server/migrations/163_agent_builder.down.sql b/server/migrations/163_agent_builder.down.sqlnew file mode 100644index 0000000000..8909b91640--- /dev/null+++ b/server/migrations/163_agent_builder.down.sql@@ -0,0 +1,5 @@+DROP INDEX IF EXISTS agent_system_identity_unique;++ALTER TABLE agent+DROP COLUMN IF EXISTS system_key,+DROP COLUMN IF EXISTS kind;diff --git a/server/migrations/163_agent_builder.up.sql b/server/migrations/163_agent_builder.up.sqlnew file mode 100644index 0000000000..6f2620f663--- /dev/null+++ b/server/migrations/163_agent_builder.up.sql@@ -0,0 +1,8 @@+ALTER TABLE agent+ADD COLUMN kind TEXT NOT NULL DEFAULT 'user'+ CHECK (kind IN ('user', 'system')),+ADD COLUMN system_key TEXT;++CREATE UNIQUE INDEX agent_system_identity_unique+ ON agent (workspace_id, owner_id, runtime_id, system_key)+ WHERE system_key IS NOT NULL;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 50f63139c5..c0ef682c36 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -14,7 +14,7 @@ import (const archiveAgent = `-- name: ArchiveAgent :oneUPDATE agent SET archived_at = now(), archived_by = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`type ArchiveAgentParams struct {@@ -50,6 +50,8 @@ func (q *Queries) ArchiveAgent(ctx context.Context, arg ArchiveAgentParams) (Age&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}@@ -58,7 +60,7 @@ const archiveAgentsByIDs = `-- name: ArchiveAgentsByIDs :manyUPDATE agentSET archived_at = now(), archived_by = $1, updated_at = now()WHERE id = ANY($2::uuid[]) AND archived_at IS NULL-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`type ArchiveAgentsByIDsParams struct {@@ -108,6 +110,8 @@ func (q *Queries) ArchiveAgentsByIDs(ctx context.Context, arg ArchiveAgentsByIDs&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,); err != nil {return nil, err}@@ -123,7 +127,7 @@ const archiveAgentsByRuntime = `-- name: ArchiveAgentsByRuntime :manyUPDATE agentSET archived_at = now(), archived_by = $1, updated_at = now()WHERE runtime_id = ANY($2::uuid[]) AND archived_at IS NULL-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`type ArchiveAgentsByRuntimeParams struct {@@ -169,6 +173,8 @@ func (q *Queries) ArchiveAgentsByRuntime(ctx context.Context, arg ArchiveAgentsB&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,); err != nil {return nil, err}@@ -873,7 +879,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)const clearAgentComposioToolkitAllowlist = `-- name: ClearAgentComposioToolkitAllowlist :oneUPDATE agent SET composio_toolkit_allowlist = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`// Explicit NULL-clear for composio_toolkit_allowlist. The COALESCE-based@@ -910,6 +916,8 @@ func (q *Queries) ClearAgentComposioToolkitAllowlist(ctx context.Context, id pgt&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}@@ -917,7 +925,7 @@ func (q *Queries) ClearAgentComposioToolkitAllowlist(ctx context.Context, id pgtconst clearAgentMcpConfig = `-- name: ClearAgentMcpConfig :oneUPDATE agent SET mcp_config = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agent, error) {@@ -948,6 +956,8 @@ func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agen&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}@@ -955,7 +965,7 @@ func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agenconst clearAgentThinkingLevel = `-- name: ClearAgentThinkingLevel :oneUPDATE agent SET thinking_level = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`// Explicit NULL-clear for thinking_level. COALESCE-based UpdateAgent cannot@@ -989,6 +999,8 @@ func (q *Queries) ClearAgentThinkingLevel(ctx context.Context, id pgtype.UUID) (&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}@@ -1083,7 +1095,7 @@ INSERT INTO agent ($17::text[],COALESCE($18, 'private'))-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`type CreateAgentParams struct {@@ -1154,6 +1166,79 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,+ )+ return i, err+}++const createAgentBuilder = `-- name: CreateAgentBuilder :one+INSERT INTO agent (+ workspace_id, name, description, runtime_mode, runtime_config, runtime_id,+ visibility, permission_mode, max_concurrent_tasks, owner_id, instructions,+ custom_env, custom_args, model, kind, system_key+) VALUES (+ $1, $2, '', $3, '{}'::jsonb, $4,+ 'private', 'private', 1, $5, $6,+ '{}'::jsonb, '[]'::jsonb, $7, 'system', $8+)+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key+`++type CreateAgentBuilderParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Name string `json:"name"`+ RuntimeMode string `json:"runtime_mode"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ OwnerID pgtype.UUID `json:"owner_id"`+ Instructions string `json:"instructions"`+ Model pgtype.Text `json:"model"`+ SystemKey pgtype.Text `json:"system_key"`+}++// One hidden builder agent per creation session. Keeping the execution carrier+// session-scoped freezes its model/runtime configuration when multiple builder+// flows are open concurrently, while `kind = 'system'` keeps it out of normal+// agent lists and assignment surfaces.+func (q *Queries) CreateAgentBuilder(ctx context.Context, arg CreateAgentBuilderParams) (Agent, error) {+ row := q.db.QueryRow(ctx, createAgentBuilder,+ arg.WorkspaceID,+ arg.Name,+ arg.RuntimeMode,+ arg.RuntimeID,+ arg.OwnerID,+ arg.Instructions,+ arg.Model,+ arg.SystemKey,+ )+ var i Agent+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.AvatarUrl,+ &i.RuntimeMode,+ &i.RuntimeConfig,+ &i.Visibility,+ &i.Status,+ &i.MaxConcurrentTasks,+ &i.OwnerID,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Description,+ &i.RuntimeID,+ &i.Instructions,+ &i.ArchivedAt,+ &i.ArchivedBy,+ &i.CustomEnv,+ &i.CustomArgs,+ &i.McpConfig,+ &i.Model,+ &i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}@@ -1555,6 +1640,19 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParamsreturn i, err}+const deleteSystemAgentByID = `-- name: DeleteSystemAgentByID :exec+DELETE FROM agent+WHERE id = $1 AND kind = 'system' AND system_key LIKE 'agent_builder:%'+`++// Builder sessions own their hidden execution agent. Deleting the session+// removes that carrier and its task rows; the kind guard prevents this cleanup+// path from ever deleting a user-authored agent.+func (q *Queries) DeleteSystemAgentByID(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteSystemAgentByID, id)+ return err+}+const expireStaleQueuedTasks = `-- name: ExpireStaleQueuedTasks :manyWITH victims AS (SELECT id FROM agent_task_queue@@ -1938,7 +2036,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)}const getAgent = `-- name: GetAgent :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key FROM agentWHERE id = $1`@@ -1970,12 +2068,14 @@ func (q *Queries) GetAgent(ctx context.Context, id pgtype.UUID) (Agent, error) {&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}const getAgentForClaimUpdate = `-- name: GetAgentForClaimUpdate :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key FROM agentWHERE id = $1FOR UPDATE`@@ -2008,13 +2108,15 @@ func (q *Queries) GetAgentForClaimUpdate(ctx context.Context, id pgtype.UUID) (A&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}const getAgentInWorkspace = `-- name: GetAgentInWorkspace :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agent-WHERE id = $1 AND workspace_id = $2+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key FROM agent+WHERE id = $1 AND workspace_id = $2 AND kind = 'user'`type GetAgentInWorkspaceParams struct {@@ -2050,6 +2152,8 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}@@ -2535,8 +2639,8 @@ func (q *Queries) LinkTaskToIssue(ctx context.Context, arg LinkTaskToIssueParams}const listActiveAgentsByRuntime = `-- name: ListActiveAgentsByRuntime :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agent-WHERE runtime_id = $1 AND archived_at IS NULL+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key FROM agent+WHERE runtime_id = $1 AND archived_at IS NULL AND kind = 'user'ORDER BY name ASC`@@ -2580,6 +2684,8 @@ func (q *Queries) ListActiveAgentsByRuntime(ctx context.Context, runtimeID pgtyp&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,); err != nil {return nil, err}@@ -2592,8 +2698,8 @@ func (q *Queries) ListActiveAgentsByRuntime(ctx context.Context, runtimeID pgtyp}const listActiveAgentsByRuntimeForUpdate = `-- name: ListActiveAgentsByRuntimeForUpdate :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agent-WHERE runtime_id = $1 AND archived_at IS NULL+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key FROM agent+WHERE runtime_id = $1 AND archived_at IS NULL AND kind = 'user'ORDER BY name ASCFOR UPDATE`@@ -2640,6 +2746,8 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,); err != nil {return nil, err}@@ -2787,8 +2895,8 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag}const listAgents = `-- name: ListAgents :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agent-WHERE workspace_id = $1 AND archived_at IS NULL+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key FROM agent+WHERE workspace_id = $1 AND archived_at IS NULL AND kind = 'user'ORDER BY created_at ASC`@@ -2826,6 +2934,8 @@ func (q *Queries) ListAgents(ctx context.Context, workspaceID pgtype.UUID) ([]Ag&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,); err != nil {return nil, err}@@ -2838,8 +2948,8 @@ func (q *Queries) ListAgents(ctx context.Context, workspaceID pgtype.UUID) ([]Ag}const listAllAgents = `-- name: ListAllAgents :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agent-WHERE workspace_id = $1+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key FROM agent+WHERE workspace_id = $1 AND kind = 'user'ORDER BY created_at ASC`@@ -2877,6 +2987,8 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,); err != nil {return nil, err}@@ -3580,7 +3692,7 @@ SET status = CASE WHEN EXISTS () THEN 'working' ELSE 'idle' END,updated_at = now()WHERE a.id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`func (q *Queries) RefreshAgentStatusFromTasks(ctx context.Context, id pgtype.UUID) (Agent, error) {@@ -3611,6 +3723,8 @@ func (q *Queries) RefreshAgentStatusFromTasks(ctx context.Context, id pgtype.UUI&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}@@ -3689,7 +3803,7 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Reqconst restoreAgent = `-- name: RestoreAgent :oneUPDATE agent SET archived_at = NULL, archived_by = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, error) {@@ -3720,6 +3834,8 @@ func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, erro&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}@@ -3854,7 +3970,7 @@ UPDATE agent SETcomposio_toolkit_allowlist = COALESCE($18::text[], composio_toolkit_allowlist),updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`type UpdateAgentParams struct {@@ -3931,6 +4047,8 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agent&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}@@ -3939,7 +4057,7 @@ const updateAgentCustomEnv = `-- name: UpdateAgentCustomEnv :oneUPDATE agentSET custom_env = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`type UpdateAgentCustomEnvParams struct {@@ -3980,6 +4098,8 @@ func (q *Queries) UpdateAgentCustomEnv(ctx context.Context, arg UpdateAgentCusto&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}@@ -3987,7 +4107,7 @@ func (q *Queries) UpdateAgentCustomEnv(ctx context.Context, arg UpdateAgentCustoconst updateAgentStatus = `-- name: UpdateAgentStatus :oneUPDATE agent SET status = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key`type UpdateAgentStatusParams struct {@@ -4023,6 +4143,8 @@ func (q *Queries) UpdateAgentStatus(ctx context.Context, arg UpdateAgentStatusPa&i.ThinkingLevel,&i.ComposioToolkitAllowlist,&i.PermissionMode,+ &i.Kind,+ &i.SystemKey,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 15d84f447b..3d34488f5a 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -47,7 +47,9 @@ type Agent struct {// Composio toolkit slugs this agent is allowed to mount as MCP. NULL or empty array = no MCP overlay. Mounted for any run that passes the agent invocation-permission gate (MUL-3963); the overlay uses the agent OWNER's active Composio connection, so sharing the agent (public_to) shares these apps with whoever may invoke it. No longer gated on originator == owner. Stored as TEXT[] so the dispatch path can intersect against the owner's active connections with a single SQL ANY() filter.ComposioToolkitAllowlist []string `json:"composio_toolkit_allowlist"`// Agent invocation permission mode (MUL-3963). private = owner only; public_to = allow-list in agent_invocation_target. Replaces visibility as the authorization source for triggering runs; visibility is now a derived legacy field. Default private = deny-by-default.- PermissionMode string `json:"permission_mode"`+ PermissionMode string `json:"permission_mode"`+ Kind string `json:"kind"`+ SystemKey pgtype.Text `json:"system_key"`}// 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).diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex bfe2ce0e54..9f2aca9075 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -196,6 +196,18 @@ func (q *Queries) DeleteStaleOfflineRuntimes(ctx context.Context, staleSeconds freturn items, nil}+const deleteSystemAgentsByRuntime = `-- name: DeleteSystemAgentsByRuntime :exec+DELETE FROM agent WHERE runtime_id = $1 AND kind = 'system'+`++// System agents are invisible execution infrastructure (for example the Agent+// Builder). Remove them before deleting their runtime so the RESTRICT runtime+// FK cannot block an otherwise dependency-free delete.+func (q *Queries) DeleteSystemAgentsByRuntime(ctx context.Context, runtimeID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteSystemAgentsByRuntime, runtimeID)+ return err+}+const failTasksForOfflineRuntimes = `-- name: FailTasksForOfflineRuntimes :manyUPDATE agent_task_queueSET status = 'failed', completed_at = now(), error = 'runtime went offline',diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex ac931eaf41..b8fa638b7c 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -1,11 +1,11 @@-- name: ListAgents :manySELECT * FROM agent-WHERE workspace_id = $1 AND archived_at IS NULL+WHERE workspace_id = $1 AND archived_at IS NULL AND kind = 'user'ORDER BY created_at ASC;-- name: ListAllAgents :manySELECT * FROM agent-WHERE workspace_id = $1+WHERE workspace_id = $1 AND kind = 'user'ORDER BY created_at ASC;-- name: GetAgent :one@@ -14,7 +14,7 @@ WHERE id = $1;-- name: GetAgentInWorkspace :oneSELECT * FROM agent-WHERE id = $1 AND workspace_id = $2;+WHERE id = $1 AND workspace_id = $2 AND kind = 'user';-- name: CreateAgent :oneINSERT INTO agent (@@ -31,6 +31,29 @@ INSERT INTO agent ()RETURNING *;+-- name: CreateAgentBuilder :one+-- One hidden builder agent per creation session. Keeping the execution carrier+-- session-scoped freezes its model/runtime configuration when multiple builder+-- flows are open concurrently, while `kind = 'system'` keeps it out of normal+-- agent lists and assignment surfaces.+INSERT INTO agent (+ workspace_id, name, description, runtime_mode, runtime_config, runtime_id,+ visibility, permission_mode, max_concurrent_tasks, owner_id, instructions,+ custom_env, custom_args, model, kind, system_key+) VALUES (+ @workspace_id, @name, '', @runtime_mode, '{}'::jsonb, @runtime_id,+ 'private', 'private', 1, @owner_id, @instructions,+ '{}'::jsonb, '[]'::jsonb, sqlc.narg('model'), 'system', @system_key+)+RETURNING *;++-- name: DeleteSystemAgentByID :exec+-- Builder sessions own their hidden execution agent. Deleting the session+-- removes that carrier and its task rows; the kind guard prevents this cleanup+-- path from ever deleting a user-authored agent.+DELETE FROM agent+WHERE id = $1 AND kind = 'system' AND system_key LIKE 'agent_builder:%';+-- name: UpdateAgent :one-- composio_toolkit_allowlist is set wholesale: the API layer is responsible-- for normalising the request payload to either (a) the new slug list — sent@@ -132,7 +155,7 @@ RETURNING *;-- and so the cascade endpoint's expected_active_agent_ids check has a stable-- snapshot to compare against. Ordered by name for a deterministic display.SELECT * FROM agent-WHERE runtime_id = $1 AND archived_at IS NULL+WHERE runtime_id = $1 AND archived_at IS NULL AND kind = 'user'ORDER BY name ASC;-- name: ListActiveAgentsByRuntimeForUpdate :many@@ -145,7 +168,7 @@ ORDER BY name ASC;-- that the set we compared against expected_active_agent_ids is exactly-- the set ArchiveAgentsByIDs will operate on — no race window.SELECT * FROM agent-WHERE runtime_id = $1 AND archived_at IS NULL+WHERE runtime_id = $1 AND archived_at IS NULL AND kind = 'user'ORDER BY name ASCFOR UPDATE;diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex 90eca2a2e8..123f35d8a1 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -272,6 +272,12 @@ RETURNING *;-- name: DeleteAgentRuntime :execDELETE FROM agent_runtime WHERE id = $1;+-- name: DeleteSystemAgentsByRuntime :exec+-- System agents are invisible execution infrastructure (for example the Agent+-- Builder). Remove them before deleting their runtime so the RESTRICT runtime+-- FK cannot block an otherwise dependency-free delete.+DELETE FROM agent WHERE runtime_id = $1 AND kind = 'system';+-- name: CountActiveAgentsByRuntime :oneSELECT count(*) FROM agent WHERE runtime_id = $1 AND archived_at IS NULL;