Skip to content

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

Go

feat(agents): thinking level + Codex speed in the create flow (MUL-5390) (#6027)

Multica Eve81797b5a03ef
diff --git a/packages/views/agents/components/agent-creation-studio.duplicate-seed.test.tsx b/packages/views/agents/components/agent-creation-studio.duplicate-seed.test.tsx
new file mode 100644
index 0000000000..aecf8942a1
--- /dev/null
+++ b/packages/views/agents/components/agent-creation-studio.duplicate-seed.test.tsx
@@ -0,0 +1,127 @@
+// @vitest-environment jsdom
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, renderHook } from "@testing-library/react";
+import type { Agent, RuntimeDevice } from "@multica/core/types";
+import {
+ useDuplicateDraftSeed,
+ type AgentDraft,
+} from "./agent-creation-studio";
+
+const SOURCE_RUNTIME = {
+ id: "runtime-1",
+ name: "Codex laptop",
+ provider: "codex",
+ status: "online",
+ owner_id: "user-1",
+ visibility: "private",
+} as RuntimeDevice;
+
+const OTHER_RUNTIME = {
+ ...SOURCE_RUNTIME,
+ id: "runtime-2",
+ name: "Spare laptop",
+} as RuntimeDevice;
+
+const SOURCE = {
+ id: "agent-1",
+ runtime_id: "runtime-1",
+ name: "Fast Codex",
+ description: "",
+ instructions: "",
+ avatar_url: null,
+ custom_args: [],
+ permission_mode: "private",
+ invocation_targets: [],
+ max_concurrent_tasks: 6,
+ model: "gpt-5.6-sol",
+ thinking_level: "high",
+ service_tier: "priority",
+ skills: [],
+} as unknown as Agent;
+
+function setup(initial: { runtimesSettled: boolean; runtimes: RuntimeDevice[] }) {
+ const onSeed = vi.fn<(draft: AgentDraft, runtimeReset: boolean) => void>();
+ const view = renderHook(
+ (props: { runtimesSettled: boolean; runtimes: RuntimeDevice[] }) =>
+ useDuplicateDraftSeed({
+ source: SOURCE,
+ runtimesSettled: props.runtimesSettled,
+ runtimes: props.runtimes,
+ currentUserId: "user-1",
+ fallbackRuntimeId: props.runtimes[0]?.id ?? "",
+ nameSuffix: " copy",
+ onSeed,
+ }),
+ { initialProps: initial },
+ );
+ return { onSeed, view };
+}
+
+// Regression for the cold-start ordering bug: the agent list and the runtime
+// list are independent queries, so on a direct ?duplicate=<id> link the agent
+// can arrive while runtimes are still pending. Seeding then judged the source
+// runtime "unavailable" and permanently cleared model / thinking / speed.
+describe("useDuplicateDraftSeed", () => {
+ afterEach(cleanup);
+
+ it("waits for the runtime query before seeding", () => {
+ const { onSeed, view } = setup({ runtimesSettled: false, runtimes: [] });
+
+ expect(onSeed).not.toHaveBeenCalled();
+
+ // Runtimes resolve late, still holding the source runtime.
+ view.rerender({ runtimesSettled: true, runtimes: [SOURCE_RUNTIME] });
+
+ expect(onSeed).toHaveBeenCalledTimes(1);
+ const [draft, runtimeReset] = onSeed.mock.calls[0]!;
+ expect(draft).toMatchObject({
+ runtimeId: "runtime-1",
+ model: "gpt-5.6-sol",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ });
+ expect(runtimeReset).toBe(false);
+ });
+
+ it("seeds exactly once, so later runtime updates cannot overwrite edits", () => {
+ const { onSeed, view } = setup({
+ runtimesSettled: true,
+ runtimes: [SOURCE_RUNTIME],
+ });
+
+ expect(onSeed).toHaveBeenCalledTimes(1);
+ view.rerender({
+ runtimesSettled: true,
+ runtimes: [SOURCE_RUNTIME, OTHER_RUNTIME],
+ });
+
+ expect(onSeed).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports the reset when the settled list cannot serve the source runtime", () => {
+ const { onSeed } = setup({
+ runtimesSettled: true,
+ runtimes: [OTHER_RUNTIME],
+ });
+
+ expect(onSeed).toHaveBeenCalledTimes(1);
+ const [draft, runtimeReset] = onSeed.mock.calls[0]!;
+ expect(draft).toMatchObject({
+ runtimeId: "runtime-2",
+ model: "",
+ thinkingLevel: "",
+ serviceTier: "",
+ });
+ expect(runtimeReset).toBe(true);
+ });
+
+ // A failed runtime query is a decidable answer: the source runtime cannot be
+ // confirmed, so falling back is correct — unlike a pending one.
+ it("seeds on a failed runtime query rather than hanging", () => {
+ const { onSeed } = setup({ runtimesSettled: true, runtimes: [] });
+
+ expect(onSeed).toHaveBeenCalledTimes(1);
+ expect(onSeed.mock.calls[0]![1]).toBe(true);
+ });
+});
diff --git a/packages/views/agents/components/agent-creation-studio.execution.test.tsx b/packages/views/agents/components/agent-creation-studio.execution.test.tsx
new file mode 100644
index 0000000000..9cd7462915
--- /dev/null
+++ b/packages/views/agents/components/agent-creation-studio.execution.test.tsx
@@ -0,0 +1,186 @@
+// @vitest-environment jsdom
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import type {
+ RuntimeDevice,
+ RuntimeModel,
+ RuntimeModelListRequest,
+} from "@multica/core/types";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enAgents from "../../locales/en/agents.json";
+import enCommon from "../../locales/en/common.json";
+import enIssues from "../../locales/en/issues.json";
+
+const mockInitiateListModels = vi.hoisted(() => vi.fn());
+const mockGetListModelsResult = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/api", () => ({
+ api: {
+ initiateListModels: (...args: unknown[]) => mockInitiateListModels(...args),
+ getListModelsResult: (...args: unknown[]) =>
+ mockGetListModelsResult(...args),
+ },
+ ApiError: class ApiError extends Error {},
+}));
+
+import {
+ AgentExecutionOverrides,
+ type AgentDraft,
+} from "./agent-creation-studio";
+
+const FAST_MODEL: RuntimeModel = {
+ id: "gpt-5.6-sol",
+ label: "GPT-5.6 Sol",
+ thinking: {
+ supported_levels: [
+ { value: "medium", label: "Medium" },
+ { value: "high", label: "High" },
+ ],
+ },
+ service_tiers: [{ id: "priority", name: "Fast", description: "1.5x speed" }],
+};
+
+const PLAIN_MODEL: RuntimeModel = { id: "gpt-5.4-mini", label: "GPT-5.4 mini" };
+
+const ONLINE_RUNTIME = {
+ id: "runtime-1",
+ name: "Codex laptop",
+ provider: "codex",
+ status: "online",
+} as RuntimeDevice;
+
+function listResult(models: RuntimeModel[]): RuntimeModelListRequest {
+ return {
+ id: "request-1",
+ runtime_id: "runtime-1",
+ status: "completed",
+ models,
+ supported: true,
+ created_at: "2026-07-28T00:00:00Z",
+ updated_at: "2026-07-28T00:00:00Z",
+ };
+}
+
+const baseDraft: AgentDraft = {
+ name: "Fast Codex",
+ description: "",
+ instructions: "",
+ avatarUrl: null,
+ runtimeId: "runtime-1",
+ model: "gpt-5.6-sol",
+ thinkingLevel: "",
+ serviceTier: "",
+ skillIds: new Set(),
+ permissionScope: "private",
+ memberIds: new Set(),
+ teamIds: new Set(),
+};
+
+function renderOverrides(
+ props: Partial<React.ComponentProps<typeof AgentExecutionOverrides>> = {},
+) {
+ const onChange = vi.fn();
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ render(
+ <I18nProvider
+ locale="en"
+ resources={{
+ en: { common: enCommon, agents: enAgents, issues: enIssues },
+ }}
+ >
+ <QueryClientProvider client={queryClient}>
+ <AgentExecutionOverrides
+ draft={baseDraft}
+ runtime={ONLINE_RUNTIME}
+ onChange={onChange}
+ {...props}
+ />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+ return { onChange };
+}
+
+// MUL-5390: the create flow never offered these two, so a Fast Codex agent had
+// to be created first and fixed afterwards in settings.
+describe("AgentExecutionOverrides", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockInitiateListModels.mockResolvedValue(listResult([FAST_MODEL]));
+ mockGetListModelsResult.mockResolvedValue(listResult([FAST_MODEL]));
+ });
+
+ afterEach(cleanup);
+
+ it("offers Speed for a model whose catalog advertises a tier", async () => {
+ const { onChange } = renderOverrides();
+
+ await screen.findByText("Speed");
+ fireEvent.click(screen.getByRole("button", { name: /speed/i }));
+ fireEvent.click(await screen.findByText("Fast"));
+
+ expect(onChange).toHaveBeenCalledWith(
+ expect.objectContaining({ serviceTier: "priority" }),
+ );
+ });
+
+ it("offers the exact model's thinking levels", async () => {
+ const { onChange } = renderOverrides();
+
+ await screen.findByText("Thinking");
+ fireEvent.click(screen.getByRole("button", { name: /thinking/i }));
+ fireEvent.click(await screen.findByText("High"));
+
+ expect(onChange).toHaveBeenCalledWith(
+ expect.objectContaining({ thinkingLevel: "high" }),
+ );
+ });
+
+ it("hides both fields when the model advertises neither capability", async () => {
+ mockInitiateListModels.mockResolvedValue(listResult([PLAIN_MODEL]));
+ mockGetListModelsResult.mockResolvedValue(listResult([PLAIN_MODEL]));
+ renderOverrides({ draft: { ...baseDraft, model: "gpt-5.4-mini" } });
+
+ await waitFor(() => expect(mockInitiateListModels).toHaveBeenCalled());
+ expect(screen.queryByText("Speed")).toBeNull();
+ expect(screen.queryByText("Thinking")).toBeNull();
+ });
+
+ it("stays hidden and asks the daemon nothing while the runtime is offline", async () => {
+ renderOverrides({
+ runtime: { ...ONLINE_RUNTIME, status: "offline" } as RuntimeDevice,
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByText("Speed")).toBeNull();
+ });
+ expect(mockInitiateListModels).not.toHaveBeenCalled();
+ });
+
+ it("stays hidden when model discovery fails", async () => {
+ mockInitiateListModels.mockRejectedValue(new Error("discovery failed"));
+ renderOverrides();
+
+ await waitFor(() => expect(mockInitiateListModels).toHaveBeenCalled());
+ expect(screen.queryByText("Speed")).toBeNull();
+ expect(screen.queryByText("Thinking")).toBeNull();
+ });
+
+ it("fails closed for an empty model that follows the runtime default", async () => {
+ renderOverrides({ draft: { ...baseDraft, model: "" } });
+
+ await waitFor(() => expect(mockInitiateListModels).toHaveBeenCalled());
+ expect(screen.queryByText("Speed")).toBeNull();
+ expect(screen.queryByText("Thinking")).toBeNull();
+ });
+});
diff --git a/packages/views/agents/components/agent-creation-studio.test.ts b/packages/views/agents/components/agent-creation-studio.test.ts
index f9bc177d45..013fcea1e2 100644
--- a/packages/views/agents/components/agent-creation-studio.test.ts
+++ b/packages/views/agents/components/agent-creation-studio.test.ts
@@ -2,16 +2,22 @@ import { createElement } from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { ApiError } from "@multica/core/api";
+import type { Agent, RuntimeDevice } from "@multica/core/types";
import {
AgentNameField,
ModeChooser,
StudioFooter,
+ applyDraftModelChange,
+ applyDraftRuntimeChange,
+ buildCreateAgentRequest,
+ buildDuplicateDraft,
buildInvocationTargets,
classifyAgentCreateError,
decodeBuilderInput,
deriveDuplicateAccess,
encodeBuilderInput,
getAgentCreationScreenKey,
+ isDraftDescriptionWithinLimit,
mergeBuilderDraft,
parseBuilderDraft,
pickBuilderRestore,
@@ -187,6 +193,8 @@ const draft = (): AgentDraft => ({
avatarUrl: null,
runtimeId: "runtime-1",
model: "model-1",
+ thinkingLevel: "",
+ serviceTier: "",
skillIds: new Set(["skill-1"]),
permissionScope: "private",
memberIds: new Set(),
@@ -423,3 +431,241 @@ Return findings."}</agent_draft>`;
).toBe("workspace");
});
});
+
+const CODEX_RUNTIME: RuntimeDevice = {
+ id: "runtime-1",
+ workspace_id: "ws-1",
+ name: "Codex laptop",
+ provider: "codex",
+ status: "online",
+ owner_id: "user-1",
+ visibility: "private",
+} as RuntimeDevice;
+
+const OTHER_RUNTIME: RuntimeDevice = {
+ ...CODEX_RUNTIME,
+ id: "runtime-2",
+ name: "Spare laptop",
+} as RuntimeDevice;
+
+const sourceAgent = (overrides: Partial<Agent> = {}): Agent =>
+ ({
+ id: "agent-1",
+ workspace_id: "ws-1",
+ runtime_id: "runtime-1",
+ name: "Fast Codex",
+ description: "Ships quickly",
+ instructions: "Be quick",
+ avatar_url: null,
+ runtime_mode: "managed",
+ runtime_config: {},
+ custom_args: ["--verbose"],
+ visibility: "private",
+ permission_mode: "private",
+ invocation_targets: [],
+ status: "idle",
+ max_concurrent_tasks: 9,
+ model: "gpt-5.6-sol",
+ thinking_level: "high",
+ service_tier: "priority",
+ owner_id: "user-1",
+ skills: [{ id: "skill-1", name: "Review", description: "" }],
+ created_at: "2026-07-28T00:00:00Z",
+ updated_at: "2026-07-28T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+ ...overrides,
+ }) as Agent;
+
+// MUL-5390: thinking_level / service_tier are runtime + model scoped. The create
+// flow never exposed them, so a Fast Codex agent could only be configured after
+// the fact and a Duplicate silently dropped the setting.
+describe("Agent creation studio execution overrides", () => {
+ it("sends the selected thinking level and service tier", () => {
+ const request = buildCreateAgentRequest({
+ draft: {
+ ...draft(),
+ model: "gpt-5.6-sol",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ },
+ runtimeId: "runtime-1",
+ });
+
+ expect(request).toMatchObject({
+ runtime_id: "runtime-1",
+ model: "gpt-5.6-sol",
+ thinking_level: "high",
+ service_tier: "priority",
+ });
+ });
+
+ it("omits empty overrides instead of sending an empty string", () => {
+ const request = buildCreateAgentRequest({
+ draft: { ...draft(), model: "" },
+ runtimeId: "runtime-1",
+ });
+
+ expect(request.model).toBeUndefined();
+ expect(request.thinking_level).toBeUndefined();
+ expect(request.service_tier).toBeUndefined();
+ expect("thinking_level" in request).toBe(true);
+ expect(JSON.parse(JSON.stringify(request))).not.toHaveProperty(
+ "thinking_level",
+ );
+ });
+
+ it("carries the runtime-independent duplicate config", () => {
+ const request = buildCreateAgentRequest({
+ draft: { ...draft(), thinkingLevel: "high", serviceTier: "priority" },
+ runtimeId: "runtime-1",
+ duplicateSource: sourceAgent(),
+ });
+
+ expect(request.custom_args).toEqual(["--verbose"]);
+ expect(request.max_concurrent_tasks).toBe(9);
+ expect(request.thinking_level).toBe("high");
+ });
+
+ it("clears model, thinking level and service tier on a runtime change", () => {
+ const current = {
+ ...draft(),
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ };
+
+ expect(applyDraftRuntimeChange(current, "runtime-2")).toMatchObject({
+ runtimeId: "runtime-2",
+ model: "",
+ thinkingLevel: "",
+ serviceTier: "",
+ });
+ });
+
+ it("clears only the per-model overrides on a model change", () => {
+ const current = {
+ ...draft(),
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ };
+ const next = applyDraftModelChange(current, "gpt-5.4-mini");
+
+ expect(next).toMatchObject({
+ runtimeId: "runtime-1",
+ model: "gpt-5.4-mini",
+ thinkingLevel: "",
+ serviceTier: "",
+ });
+ // Re-selecting the same model must not wipe a choice the user just made.
+ expect(applyDraftModelChange(current, "model-1")).toBe(current);
+ });
+
+ it("copies the execution config when the duplicate stays on its runtime", () => {
+ const duplicate = buildDuplicateDraft(sourceAgent(), {
+ runtimes: [CODEX_RUNTIME],
+ currentUserId: "user-1",
+ fallbackRuntimeId: "runtime-1",
+ nameSuffix: " copy",
+ });
+
+ expect(duplicate).toMatchObject({
+ name: "Fast Codex copy",
+ runtimeId: "runtime-1",
+ model: "gpt-5.6-sol",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ });
+ expect([...duplicate.skillIds]).toEqual(["skill-1"]);
+ });
+
+ it("drops the execution config when the duplicate falls back to another runtime", () => {
+ // Source runtime is gone from the list (deleted, or private to someone
+ // else), so the draft lands on the fallback. Keeping the source model here
+ // is what persisted a cross-provider model before MUL-5390.
+ const duplicate = buildDuplicateDraft(sourceAgent(), {
+ runtimes: [OTHER_RUNTIME],
+ currentUserId: "user-1",
+ fallbackRuntimeId: "runtime-2",
+ nameSuffix: " copy",
+ });
+
+ expect(duplicate).toMatchObject({
+ runtimeId: "runtime-2",
+ model: "",
+ thinkingLevel: "",
+ serviceTier: "",
+ });
+ });
+
+ it("drops the execution config when the source runtime is private to someone else", () => {
+ const duplicate = buildDuplicateDraft(sourceAgent(), {
+ runtimes: [
+ { ...CODEX_RUNTIME, owner_id: "user-2" } as RuntimeDevice,
+ { ...OTHER_RUNTIME, owner_id: "user-1" } as RuntimeDevice,
+ ],
+ currentUserId: "user-1",
+ fallbackRuntimeId: "runtime-2",
+ nameSuffix: " copy",
+ });
+
+ expect(duplicate).toMatchObject({
+ runtimeId: "runtime-2",
+ model: "",
+ thinkingLevel: "",
+ serviceTier: "",
+ });
+ });
+
+ it("keeps the overrides while the AI builder leaves the model alone", () => {
+ const current = {
+ ...draft(),
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ };
+
+ expect(
+ mergeBuilderDraft(
+ current,
+ { name: "Renamed" },
+ new Set(),
+ new Set(),
+ new Set(["model-1"]),
+ ),
+ ).toMatchObject({
+ name: "Renamed",
+ model: "model-1",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ });
+ });
+
+ it("drops the overrides when the AI builder moves the model", () => {
+ const current = {
+ ...draft(),
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ };
+
+ expect(
+ mergeBuilderDraft(
+ current,
+ { model: "gpt-5.4-mini" },
+ new Set(),
+ new Set(),
+ new Set(["model-1", "gpt-5.4-mini"]),
+ ),
+ ).toMatchObject({
+ model: "gpt-5.4-mini",
+ thinkingLevel: "",
+ serviceTier: "",
+ });
+ });
+
+ it("enforces the 255-rune description limit the create API applies", () => {
+ expect(isDraftDescriptionWithinLimit("a".repeat(255))).toBe(true);
+ expect(isDraftDescriptionWithinLimit("a".repeat(256))).toBe(false);
+ // Runes, not UTF-16 units: 255 CJK characters are exactly at the limit.
+ expect(isDraftDescriptionWithinLimit("汉".repeat(255))).toBe(true);
+ expect(isDraftDescriptionWithinLimit("汉".repeat(256))).toBe(false);
+ });
+});
diff --git a/packages/views/agents/components/agent-creation-studio.tsx b/packages/views/agents/components/agent-creation-studio.tsx
index 498a1541af..83a072c236 100644
--- a/packages/views/agents/components/agent-creation-studio.tsx
+++ b/packages/views/agents/components/agent-creation-studio.tsx
@@ -17,6 +17,7 @@ import { toast } from "sonner";
import { api, ApiError } from "@multica/core/api";
import { useAuthStore } from "@multica/core/auth";
import {
+ AGENT_DESCRIPTION_MAX_LENGTH,
agentTemplateDetailOptions,
agentTemplateListOptions,
} from "@multica/core/agents";
@@ -73,6 +74,9 @@ import {
SettingsSection,
} from "../../settings/components/settings-layout";
import { ModelDropdown } from "./model-dropdown";
+import { CharCounter } from "./char-counter";
+import { ServiceTierSettingField } from "./inspector/service-tier-setting-field";
+import { ThinkingSettingField } from "./inspector/thinking-prop-row";
import { RuntimePicker, isRuntimeUsableForUser } from "./runtime-picker";
import { SkillMultiSelect } from "./skill-multi-select";
@@ -102,6 +106,10 @@ export interface AgentDraft {
avatarUrl: string | null;
runtimeId: string;
model: string;
+ /** Runtime-native reasoning/effort token, scoped to `model`. */
+ thinkingLevel: string;
+ /** Runtime-native execution tier (Codex Speed), scoped to `model`. */
+ serviceTier: string;
skillIds: Set<string>;
permissionScope: PermissionScope;
memberIds: Set<string>;
@@ -109,6 +117,47 @@ export interface AgentDraft {
teamIds: Set<string>;
}
+/**
+ * Draft fields whose only meaning comes from the currently selected
+ * runtime + model pair. A runtime change invalidates all three; a model
+ * change invalidates the two that hang off the exact model catalog. Keeping
+ * them together is what stops an orphan `thinking_level` / `service_tier`
+ * from being persisted for a model that never advertised it — the daemon
+ * would silently fall back at execution time and the settings page would
+ * disagree with what actually ran (MUL-5390).
+ */
+export function applyDraftRuntimeChange(
+ draft: AgentDraft,
+ runtimeId: string,
+): AgentDraft {
+ return {
+ ...draft,
+ runtimeId,
+ model: "",
+ thinkingLevel: "",
+ serviceTier: "",
+ };
+}
+
+/** Model change: drop the per-model capability overrides, keep the runtime. */
+export function applyDraftModelChange(
+ draft: AgentDraft,
+ model: string,
+): AgentDraft {
+ if (model === draft.model) return draft;
+ return { ...draft, model, thinkingLevel: "", serviceTier: "" };
+}
+
+/**
+ * Mirrors the server's `utf8.RuneCountInString` check (agent.go:1013). The
+ * textarea's `maxLength` covers typing and pasting, but a duplicated agent or
+ * an AI-builder draft can seed a longer value programmatically — without this
+ * the create button would submit into a guaranteed 400.
+ */
+export function isDraftDescriptionWithinLimit(description: string): boolean {
+ return [...description].length <= AGENT_DESCRIPTION_MAX_LENGTH;
+}
+
export interface BuilderDraftPayload {
name?: unknown;
description?: unknown;
@@ -145,6 +194,8 @@ const EMPTY_DRAFT: AgentDraft = {
avatarUrl: null,
runtimeId: "",
model: "",
+ thinkingLevel: "",
+ serviceTier: "",
skillIds: new Set(),
permissionScope: "private",
memberIds: new Set(),
@@ -163,9 +214,12 @@ export function AgentCreationStudio() {
const shouldReduceMotion = useReducedMotion() ?? false;
const { data: agents = [] } = useQuery(agentListOptions(wsId));
- const { data: runtimes = [], isLoading: runtimesLoading } = useQuery(
- runtimeListOptions(wsId),
- );
+ const {
+ data: runtimes = [],
+ isLoading: runtimesLoading,
+ isSuccess: runtimesLoaded,
+ isError: runtimesFailed,
+ } = useQuery(runtimeListOptions(wsId));
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: workspaceSkills = [] } = useQuery(skillListOptions(wsId));
const { data: templates = [], isLoading: templatesLoading } = useQuery(
@@ -179,6 +233,9 @@ export function AgentCreationStudio() {
const [transitionDirection, setTransitionDirection] =
useState<TransitionDirection>(1);
const [draft, setDraft] = useState<AgentDraft>(EMPTY_DRAFT);
+ // True when a duplicate had to fall back to another runtime, which drops the
+ // source's model / thinking / speed. The notice explains the empty fields.
+ const [duplicateRuntimeReset, setDuplicateRuntimeReset] = useState(false);
const [sourceTemplate, setSourceTemplate] = useState<AgentTemplateSummary | null>(null);
const [selectedTemplate, setSelectedTemplate] = useState<AgentTemplateSummary | null>(null);
const [templateSearch, setTemplateSearch] = useState("");
@@ -194,7 +251,6 @@ export function AgentCreationStudio() {
id: string;
content: string;
} | null>(null);
- const duplicateAppliedRef = useRef(false);
const appliedAssistantMessageRef = useRef<string | null>(null);
const builderSessionIdRef = useRef("");
@@ -329,29 +385,24 @@ export function AgentCreationStudio() {
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]);
+ useDuplicateDraftSeed({
+ source: duplicateAgent,
+ // `buildDuplicateDraft` decides whether the copy can stay on the source
+ // runtime by looking it up in this list. An error is a decidable answer
+ // (the runtime cannot be confirmed, so the fallback is right); a pending
+ // query is not.
+ runtimesSettled: runtimesLoaded || runtimesFailed,
+ runtimes,
+ currentUserId: currentUser?.id ?? null,
+ fallbackRuntimeId: usableRuntimes[0]?.id ?? "",
+ nameSuffix: t(($) => $.create_dialog.duplicate_copy_suffix),
+ onSeed: (duplicated, runtimeReset) => {
+ // Only the forced fallback gets the notice; a later manual runtime switch
+ // is the user's own doing and needs no explanation.
+ setDuplicateRuntimeReset(runtimeReset);
+ setDraft(duplicated);
+ },
+ });
const skillIdSet = useMemo(
() => new Set(workspaceSkills.map((skill) => skill.id)),
@@ -420,8 +471,12 @@ export function AgentCreationStudio() {
draft.name.trim().length > 0 &&
selectedRuntime != null &&
isRuntimeUsableForUser(selectedRuntime, currentUser?.id ?? null) &&
+ isDraftDescriptionWithinLimit(draft.description) &&
!accessInvalid &&
!creating;
+ // Duplicating onto a different runtime than the source: the runtime-specific
+ // execution config was dropped, so say it instead of letting the user notice
+ // an empty model later.
const currentModeLabel =
mode === "choose"
? t(($) => $.creation_studio.step_choose)
@@ -542,7 +597,7 @@ export function AgentCreationStudio() {
// Before the conversation exists there is no carrier to rebind, so the
// picker is still plain draft state.
if (!builderSessionId) {
- setDraft((current) => ({ ...current, runtimeId, model: "" }));
+ setDraft((current) => applyDraftRuntimeChange(current, runtimeId));
return;
}
if (builderSwitchingRuntime) return;
@@ -558,9 +613,10 @@ export function AgentCreationStudio() {
// split this whole change removes. The client fallback already resolves an
// unparseable success body to the requested id.
const boundRuntimeId = result.runtime_id || runtimeId;
- // Model ids are per-runtime; clear it so the new runtime resolves its own
- // default instead of keeping one it may not serve.
- setDraft((current) => ({ ...current, runtimeId: boundRuntimeId, model: "" }));
+ // Model ids are per-runtime; clear it — with the per-model thinking /
+ // speed overrides — so the new runtime resolves its own defaults instead
+ // of keeping values it may not serve.
+ setDraft((current) => applyDraftRuntimeChange(current, boundRuntimeId));
toast.success(t(($) => $.creation_studio.builder.switch_runtime_success));
} catch (error) {
setBuilderError(
@@ -680,25 +736,12 @@ export function AgentCreationStudio() {
});
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],
+ const request = buildCreateAgentRequest({
+ draft,
+ runtimeId: selectedRuntime.id,
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;
- }
+ duplicateSource: duplicateAgent,
+ });
agent = await api.createAgent(request);
}
@@ -865,6 +908,11 @@ export function AgentCreationStudio() {
{t(($) => $.creation_studio.duplicate_env_notice)}
</div>
)}
+ {duplicateRuntimeReset && (
+ <div className="mb-5 rounded-lg border border-warning/30 bg-warning/5 px-4 py-3 text-sm">
+ {t(($) => $.creation_studio.duplicate_runtime_reset_notice)}
+ </div>
+ )}
<ConfigurationPanel
draft={draft}
onChange={setDraft}
@@ -1175,9 +1223,10 @@ function ConfigurationPanel({
onRuntimeSelect(id);
return;
}
- // Model is per-runtime; clear it on runtime change so the new
- // runtime resolves its own default instead of a stale value.
- onChange({ ...draft, runtimeId: id, model: "" });
+ // Model is per-runtime; clear it — and the per-model thinking / speed
+ // overrides — on runtime change so the new runtime resolves its own
+ // defaults instead of stale values.
+ onChange(applyDraftRuntimeChange(draft, id));
};
return (
@@ -1214,17 +1263,27 @@ function ConfigurationPanel({
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"
- />
+ <div>
+ <Textarea
+ id="agent-create-description"
+ name="agent-description"
+ autoComplete="off"
+ aria-label={t(($) => $.create_dialog.description_label)}
+ value={draft.description}
+ onChange={(event) => set("description", event.target.value)}
+ placeholder={t(($) => $.create_dialog.description_placeholder)}
+ rows={compact ? 3 : 4}
+ // The create API rejects >255 characters with a 400. Cap the
+ // input and show the counter so the limit is visible before
+ // submitting, matching the settings page.
+ maxLength={AGENT_DESCRIPTION_MAX_LENGTH}
+ className="resize-y"
+ />
+ <CharCounter
+ length={[...draft.description].length}
+ max={AGENT_DESCRIPTION_MAX_LENGTH}
+ />
+ </div>
</DraftFieldRow>
</SettingsCard>
</SettingsSection>
@@ -1289,12 +1348,23 @@ function ConfigurationPanel({
runtimeId={selectedRuntime?.id ?? null}
runtimeOnline={selectedRuntime?.status === "online"}
value={draft.model}
- onChange={(value) => set("model", value)}
+ onChange={(value) => onChange(applyDraftModelChange(draft, value))}
// A successful switch clears the model, so an edit made while the
// rebind is in flight would be silently discarded.
disabled={!selectedRuntime || runtimeSwitchInFlight}
/>
</div>
+ {/* Both fields fail closed: they render only when the exact selected
+ model's live catalog advertises the capability (or a value is
+ already set and needs clearing), so an offline runtime, a failed
+ discovery or an empty model shows nothing instead of an input
+ that cannot be honoured. */}
+ <AgentExecutionOverrides
+ draft={draft}
+ runtime={selectedRuntime}
+ disabled={runtimeLocked}
+ onChange={onChange}
+ />
</SettingsCard>
</SettingsSection>
@@ -1437,6 +1507,52 @@ export function AgentNameField({
);
}
+/**
+ * Per-model execution overrides (thinking level + Codex speed) for the create
+ * flow. Capability comes from the exact selected model's live catalog on the
+ * selected runtime, so nothing renders while that cannot be resolved — an
+ * offline runtime, failed discovery, or an empty "use the runtime default"
+ * model. That is the same fail-closed rule the settings page follows, and it is
+ * why no value can be sent that the daemon would refuse to honour.
+ */
+export function AgentExecutionOverrides({
+ draft,
+ runtime,
+ disabled = false,
+ onChange,
+}: {
+ draft: AgentDraft;
+ runtime: RuntimeDevice | null;
+ disabled?: boolean;
+ onChange: (draft: AgentDraft) => void;
+}) {
+ const { t } = useT("agents");
+ const runtimeOnline = runtime?.status === "online";
+ return (
+ <>
+ <ThinkingSettingField
+ label={t(($) => $.creation_studio.thinking_label)}
+ runtimeId={runtime?.id ?? null}
+ runtimeOnline={runtimeOnline}
+ provider={runtime?.provider ?? ""}
+ model={draft.model}
+ value={draft.thinkingLevel}
+ canEdit={!disabled}
+ onChange={(thinkingLevel) => onChange({ ...draft, thinkingLevel })}
+ />
+ <ServiceTierSettingField
+ label={t(($) => $.creation_studio.speed_label)}
+ runtimeId={runtime?.id ?? null}
+ runtimeOnline={runtimeOnline}
+ model={draft.model}
+ value={draft.serviceTier}
+ canEdit={!disabled}
+ onChange={(serviceTier) => onChange({ ...draft, serviceTier })}
+ />
+ </>
+ );
+}
+
function DraftFieldRow({
label,
children,
@@ -1475,7 +1591,7 @@ function DraftFieldRow({
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) => { if (runtimeId !== draft.runtimeId) onChange({ ...draft, runtimeId, model: "" }); }} /><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>;
+ 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) => { if (runtimeId !== draft.runtimeId) onChange(applyDraftRuntimeChange(draft, runtimeId)); }} /><ModelDropdown runtimeId={selectedRuntime?.id ?? null} runtimeOnline={selectedRuntime?.status === "online"} value={draft.model} onChange={(model) => onChange(applyDraftModelChange(draft, model))} disabled={!selectedRuntime} /></div>{error && <div role="alert" className="mt-4 text-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({
@@ -1692,6 +1808,145 @@ export function deriveDuplicateAccess(
teamIds: new Set(teamIds),
};
}
+
+/**
+ * Seeds the studio draft from the agent being duplicated.
+ *
+ * `model` / `thinkingLevel` / `serviceTier` only mean something on the runtime
+ * they were chosen for, so they ride along only when the copy stays on that
+ * exact runtime. When the source runtime is gone, private to somebody else or
+ * offline, the draft falls back to another runtime and the three are cleared
+ * for the user to pick again — the same rule `multica agent copy` already
+ * enforces server-side (cmd_agent_copy.go). Before MUL-5390 the fallback kept
+ * the source `model` and silently persisted a cross-provider value.
+ */
+export function buildDuplicateDraft(
+ source: Agent,
+ options: {
+ runtimes: RuntimeDevice[];
+ currentUserId: string | null;
+ fallbackRuntimeId: string;
+ nameSuffix: string;
+ },
+): AgentDraft {
+ const keepsRuntime =
+ !!source.runtime_id &&
+ options.runtimes.some(
+ (runtime) =>
+ runtime.id === source.runtime_id &&
+ isRuntimeUsableForUser(runtime, options.currentUserId),
+ );
+ return {
+ ...EMPTY_DRAFT,
+ name: `${source.name}${options.nameSuffix}`,
+ description: source.description ?? "",
+ instructions: source.instructions ?? "",
+ avatarUrl: source.avatar_url ?? null,
+ runtimeId: keepsRuntime
+ ? (source.runtime_id as string)
+ : options.fallbackRuntimeId,
+ model: keepsRuntime ? source.model ?? "" : "",
+ thinkingLevel: keepsRuntime ? source.thinking_level ?? "" : "",
+ serviceTier: keepsRuntime ? source.service_tier ?? "" : "",
+ skillIds: new Set(source.skills.map((skill) => skill.id)),
+ ...deriveDuplicateAccess(source),
+ };
+}
+
+/**
+ * Seeds the duplicate draft exactly once, and only from a runtime list that has
+ * actually answered.
+ *
+ * The ordering matters: the agent list and the runtime list are independent
+ * queries, so on a cold start (a direct `?duplicate=<id>` link, or a refresh)
+ * the agent can arrive while runtimes are still pending. Seeding then would run
+ * `buildDuplicateDraft` against `[]`, read the source runtime as unavailable,
+ * and clear the model / thinking / speed that a same-runtime copy must keep —
+ * permanently, because seeding happens once. Re-running on every runtime change
+ * instead would overwrite edits the user already made, so the gate is on the
+ * query being decidable rather than on the data changing.
+ */
+export function useDuplicateDraftSeed({
+ source,
+ runtimesSettled,
+ runtimes,
+ currentUserId,
+ fallbackRuntimeId,
+ nameSuffix,
+ onSeed,
+}: {
+ source: Agent | null;
+ /** The runtime query resolved or failed — `false` while it is pending. */
+ runtimesSettled: boolean;
+ runtimes: RuntimeDevice[];
+ currentUserId: string | null;
+ fallbackRuntimeId: string;
+ nameSuffix: string;
+ onSeed: (draft: AgentDraft, runtimeReset: boolean) => void;
+}): void {
+ const seededRef = useRef(false);
+ // The callback is recreated every render by design (it closes over setState),
+ // so keep it out of the effect's dependency list.
+ const onSeedRef = useRef(onSeed);
+ onSeedRef.current = onSeed;
+
+ useEffect(() => {
+ if (seededRef.current || !source || !runtimesSettled) return;
+ seededRef.current = true;
+ const draft = buildDuplicateDraft(source, {
+ runtimes,
+ currentUserId,
+ fallbackRuntimeId,
+ nameSuffix,
+ });
+ onSeedRef.current(draft, draft.runtimeId !== source.runtime_id);
+ }, [
+ currentUserId,
+ fallbackRuntimeId,
+ nameSuffix,
+ runtimes,
+ runtimesSettled,
+ source,
+ ]);
+}
+
+/**
+ * Assembles the `POST /api/agents` body. Empty execution overrides are omitted
+ * rather than sent as `""` so the runtime resolves its own default, and the
+ * duplicate-only fields are the runtime-independent ones (`custom_args`,
+ * concurrency) — mirroring `multica agent copy`.
+ */
+export function buildCreateAgentRequest(options: {
+ draft: AgentDraft;
+ runtimeId: string;
+ /** Template attribution for the `agent_created` event, not a template create. */
+ template?: string;
+ duplicateSource?: Agent | null;
+}): CreateAgentRequest {
+ const { draft, runtimeId, template, duplicateSource } = options;
+ const request: CreateAgentRequest = {
+ name: draft.name.trim(),
+ description: draft.description.trim(),
+ instructions: draft.instructions.trim() || undefined,
+ avatar_url: draft.avatarUrl ?? undefined,
+ runtime_id: runtimeId,
+ model: draft.model.trim() || undefined,
+ thinking_level: draft.thinkingLevel.trim() || undefined,
+ service_tier: draft.serviceTier.trim() || undefined,
+ permission_mode:
+ draft.permissionScope === "private" ? "private" : "public_to",
+ invocation_targets: buildInvocationTargets(draft),
+ skill_ids: [...draft.skillIds],
+ template,
+ };
+ if (duplicateSource) {
+ if (duplicateSource.custom_args.length > 0) {
+ request.custom_args = duplicateSource.custom_args;
+ }
+ request.max_concurrent_tasks = duplicateSource.max_concurrent_tasks;
+ }
+ return request;
+}
export function parseBuilderDraft(content: string): BuilderDraftPayload | null {
const match = content.match(/<agent_draft>([\s\S]*?)<\/agent_draft>/);
if (!match?.[1]) return null;
@@ -1905,6 +2160,11 @@ export function mergeBuilderDraft(
? payload.instructions
: current.instructions,
model,
+ // The builder can move the model, which invalidates whatever thinking /
+ // speed the user picked for the previous one. It never sets these two
+ // itself, so an unchanged model simply preserves them.
+ thinkingLevel: model === current.model ? current.thinkingLevel : "",
+ serviceTier: model === current.model ? current.serviceTier : "",
skillIds: new Set(skillIds),
permissionScope: scope,
memberIds: new Set(scope === "members" ? memberIds : []),
diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsx
index cdcb2e69c9..1b8891ff09 100644
--- a/packages/views/agents/components/agent-detail-inspector.tsx
+++ b/packages/views/agents/components/agent-detail-inspector.tsx
@@ -1,12 +1,14 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
import type {
Agent,
AgentRuntime,
MemberWithUser,
} from "@multica/core/types";
import { AGENT_DESCRIPTION_MAX_LENGTH } from "@multica/core/agents";
+import { runtimeModelsOptions } from "@multica/core/runtimes";
import { isImeComposing } from "@multica/core/utils";
import { Input } from "@multica/ui/components/ui/input";
import { Textarea } from "@multica/ui/components/ui/textarea";
@@ -22,6 +24,10 @@ import { useT } from "../../i18n";
import { CharCounter } from "./char-counter";
import { ResourceLabelPicker } from "../../labels/resource-label-picker";
import { ModelPicker } from "./inspector/model-picker";
+import {
+ buildModelChangeUpdate,
+ type ModelCatalog,
+} from "./inspector/model-change-cleanup";
import { RuntimePicker } from "./inspector/runtime-picker";
import { ThinkingSettingField } from "./inspector/thinking-prop-row";
import { ServiceTierSettingField } from "./inspector/service-tier-setting-field";
@@ -108,6 +114,34 @@ export function AgentDetailInspector({
const isOnline = runtime?.status === "online";
const nameInvalid = name.trim().length === 0;
+ // Same query the Thinking / Speed fields already use, so switching model
+ // costs no extra request. `null` = not authoritative (offline runtime, still
+ // loading, or discovery failed) and must not trigger any clearing.
+ const modelsQuery = useQuery(
+ runtimeModelsOptions(isOnline ? agent.runtime_id : null),
+ );
+ const modelCatalog = useMemo<ModelCatalog>(
+ () =>
+ modelsQuery.isSuccess
+ ? modelsQuery.data.supported
+ ? modelsQuery.data.models
+ : []
+ : null,
+ [modelsQuery.data, modelsQuery.isSuccess],
+ );
+ const handleModelChange = useCallback(
+ (model: string) =>
+ update(
+ buildModelChangeUpdate({
+ model,
+ thinkingLevel: agent.thinking_level ?? "",
+ serviceTier: agent.service_tier ?? "",
+ catalog: modelCatalog,
+ }),
+ ),
+ [agent.service_tier, agent.thinking_level, modelCatalog, update],
+ );
+
return (
<div className="space-y-8">
<SettingsSection
@@ -245,7 +279,7 @@ export function AgentDetailInspector({
runtimeOnline={!!isOnline}
value={agent.model ?? ""}
canEdit={canEdit}
- onChange={(model) => update({ model })}
+ onChange={handleModelChange}
/>
</SettingsRow>
<ThinkingSettingField
diff --git a/packages/views/agents/components/inspector/model-change-cleanup.test.ts b/packages/views/agents/components/inspector/model-change-cleanup.test.ts
new file mode 100644
index 0000000000..2cd0f809d1
--- /dev/null
+++ b/packages/views/agents/components/inspector/model-change-cleanup.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it } from "vitest";
+import type { RuntimeModel } from "@multica/core/types";
+import { buildModelChangeUpdate } from "./model-change-cleanup";
+
+const FAST_HIGH: RuntimeModel = {
+ id: "gpt-5.6-sol",
+ label: "GPT-5.6 Sol",
+ thinking: {
+ supported_levels: [
+ { value: "medium", label: "Medium" },
+ { value: "high", label: "High" },
+ ],
+ },
+ service_tiers: [{ id: "priority", name: "Fast" }],
+};
+
+const PLAIN: RuntimeModel = {
+ id: "gpt-5.4-mini",
+ label: "GPT-5.4 mini",
+};
+
+const MEDIUM_ONLY: RuntimeModel = {
+ id: "gpt-5.5",
+ label: "GPT-5.5",
+ thinking: { supported_levels: [{ value: "medium", label: "Medium" }] },
+ service_tiers: [{ id: "priority", name: "Fast" }],
+};
+
+const CATALOG = [FAST_HIGH, PLAIN, MEDIUM_ONLY];
+
+describe("buildModelChangeUpdate (MUL-5390)", () => {
+ it("clears overrides the new model does not advertise", () => {
+ expect(
+ buildModelChangeUpdate({
+ model: "gpt-5.4-mini",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ catalog: CATALOG,
+ }),
+ ).toEqual({
+ model: "gpt-5.4-mini",
+ thinking_level: "",
+ service_tier: "",
+ });
+ });
+
+ it("keeps overrides the new model still supports", () => {
+ expect(
+ buildModelChangeUpdate({
+ model: "gpt-5.6-sol",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ catalog: CATALOG,
+ }),
+ ).toEqual({ model: "gpt-5.6-sol" });
+ });
+
+ it("clears only the unsupported half", () => {
+ expect(
+ buildModelChangeUpdate({
+ model: "gpt-5.5",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ catalog: CATALOG,
+ }),
+ ).toEqual({ model: "gpt-5.5", thinking_level: "" });
+ });
+
+ // Clearing on an unknown catalog would delete a value the daemon would have
+ // honoured, so an offline runtime / in-flight or failed discovery only writes
+ // the model.
+ it("leaves overrides untouched when the catalog is not authoritative", () => {
+ expect(
+ buildModelChangeUpdate({
+ model: "gpt-5.4-mini",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ catalog: null,
+ }),
+ ).toEqual({ model: "gpt-5.4-mini" });
+ });
+
+ it("leaves overrides untouched for an unresolvable runtime-default model", () => {
+ expect(
+ buildModelChangeUpdate({
+ model: "",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ catalog: CATALOG,
+ }),
+ ).toEqual({ model: "" });
+ });
+
+ it("leaves overrides untouched for a model missing from the catalog", () => {
+ expect(
+ buildModelChangeUpdate({
+ model: "custom-local-build",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ catalog: CATALOG,
+ }),
+ ).toEqual({ model: "custom-local-build" });
+ });
+
+ it("never sends a clear when nothing is set", () => {
+ expect(
+ buildModelChangeUpdate({
+ model: "gpt-5.4-mini",
+ thinkingLevel: "",
+ serviceTier: "",
+ catalog: CATALOG,
+ }),
+ ).toEqual({ model: "gpt-5.4-mini" });
+ });
+});
diff --git a/packages/views/agents/components/inspector/model-change-cleanup.ts b/packages/views/agents/components/inspector/model-change-cleanup.ts
new file mode 100644
index 0000000000..1a95e781f5
--- /dev/null
+++ b/packages/views/agents/components/inspector/model-change-cleanup.ts
@@ -0,0 +1,63 @@
+import type { RuntimeModel } from "@multica/core/types";
+
+/**
+ * The exact per-model catalog for the agent's runtime, or `null` when it is not
+ * authoritative — the runtime is offline, discovery is still in flight, or it
+ * failed. `[]` means the provider answered and offers no models.
+ */
+export type ModelCatalog = readonly RuntimeModel[] | null;
+
+/** Type alias (not an interface) so it stays assignable to the inspector's
+ * `Record<string, unknown>` update payload. */
+export type ModelChangeUpdate = {
+ model: string;
+ thinking_level?: string;
+ service_tier?: string;
+};
+
+/**
+ * Builds the single PATCH body for a model change on the settings page.
+ *
+ * `thinking_level` / `service_tier` are per-model capabilities: keeping a value
+ * the new model never advertised leaves an orphan override that the daemon
+ * silently drops at execution time, so the settings page would claim a tier
+ * that never ran (MUL-5390). Clearing unconditionally is worse though — moving
+ * between two models that both support Fast would throw the user's choice away,
+ * and clearing while the catalog is unknown would delete a value the daemon
+ * would have honoured.
+ *
+ * So: clear only what the authoritative catalog says the new model does not
+ * support. Unknown catalog, unknown model, or an empty model ("follow the
+ * runtime default", which resolves from the daemon host's own config and cannot
+ * be checked here) leave the stored values untouched — they stay visible in the
+ * inspector so the user can clear them explicitly.
+ *
+ * Both clears travel with the model in ONE request: a second follow-up write
+ * would leave a window where the agent is persisted with a model/tier
+ * combination the UI never intended.
+ */
+export function buildModelChangeUpdate(input: {
+ model: string;
+ thinkingLevel: string;
+ serviceTier: string;
+ catalog: ModelCatalog;
+}): ModelChangeUpdate {
+ const update: ModelChangeUpdate = { model: input.model };
+ if (!input.thinkingLevel && !input.serviceTier) return update;
+ if (input.catalog === null || !input.model) return update;
+
+ const entry = input.catalog.find((model) => model.id === input.model);
+ if (!entry) return update;
+
+ const supportsThinking = (entry.thinking?.supported_levels ?? []).some(
+ (level) => level.value === input.thinkingLevel,
+ );
+ if (input.thinkingLevel && !supportsThinking) update.thinking_level = "";
+
+ const supportsTier = (entry.service_tiers ?? []).some(
+ (tier) => tier.id === input.serviceTier,
+ );
+ if (input.serviceTier && !supportsTier) update.service_tier = "";
+
+ return update;
+}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index d90736c498..bab6580f1a 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -315,10 +315,12 @@
"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.",
+ "execution_hint": "Choose where the agent runs, and optionally override the runtime's default model, thinking level and speed.",
"access": "Access",
"access_hint": "Control who can start runs with this agent. You can change this later."
},
+ "thinking_label": "Thinking",
+ "speed_label": "Speed",
"access": {
"private": {
"title": "Only me",
@@ -360,7 +362,8 @@
},
"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.",
+ "duplicate_env_notice": "Instructions, skills and command arguments are copied. Environment variables, MCP servers and machine-local runtime config are not.",
+ "duplicate_runtime_reset_notice": "The original runtime is unavailable, so this copy runs on another one. Model, thinking level and speed were cleared because they only apply to the runtime they were chosen on.",
"create_and_open": "Create & open agent",
"create_and_add": "Create & add to squad",
"creating": "Creating agent…",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 6883be7094..8ce59251a1 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -770,10 +770,12 @@
"behavior": "動作と機能",
"behavior_hint": "動作方法を定義し、利用できるワークスペースのスキルを追加します。",
"execution": "実行環境",
- "execution_hint": "エージェントを実行する場所を選び、必要に応じてランタイムの既定モデルを変更します。",
+ "execution_hint": "エージェントを実行する場所を選び、必要に応じてランタイムの既定モデル・思考レベル・速度を変更します。",
"access": "アクセス",
"access_hint": "このエージェントを実行できるユーザーを設定します。後から変更できます。"
},
+ "thinking_label": "思考",
+ "speed_label": "速度",
"access": {
"private": {
"title": "自分のみ",
@@ -815,7 +817,8 @@
},
"live_draft": "エージェント設定",
"live_draft_hint": "会話内容がここに反映され、各項目を直接調整できます。",
- "duplicate_env_notice": "指示、スキル、モデル、コマンド引数がコピーされます。セキュリティ上、環境変数はコピーされません。",
+ "duplicate_env_notice": "指示、スキル、コマンド引数がコピーされます。環境変数、MCP サーバー、マシンローカルのランタイム設定はコピーされません。",
+ "duplicate_runtime_reset_notice": "元のランタイムが利用できないため、このコピーは別のランタイムで実行されます。モデル・思考レベル・速度は選択したランタイムでのみ有効なため、クリアされました。",
"create_and_open": "作成して開く",
"create_and_add": "作成してスクワッドに追加",
"creating": "エージェントを作成中…",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 75fe4483f7..2b2e6821d5 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -770,10 +770,12 @@
"behavior": "동작 및 기능",
"behavior_hint": "작업 방식을 정의하고 사용할 워크스페이스 스킬을 추가하세요.",
"execution": "실행",
- "execution_hint": "에이전트를 실행할 위치를 선택하고 필요하면 런타임 기본 모델을 변경하세요.",
+ "execution_hint": "에이전트를 실행할 위치를 선택하고 필요하면 런타임 기본 모델, 추론 수준, 속도를 변경하세요.",
"access": "접근 권한",
"access_hint": "이 에이전트를 실행할 수 있는 사용자를 설정합니다. 나중에 변경할 수 있습니다."
},
+ "thinking_label": "추론",
+ "speed_label": "속도",
"access": {
"private": {
"title": "나만",
@@ -815,7 +817,8 @@
},
"live_draft": "에이전트 설정",
"live_draft_hint": "대화 내용이 여기에 반영되며 각 항목을 직접 조정할 수 있습니다.",
- "duplicate_env_notice": "지침, 스킬, 모델 및 명령 인수는 복사됩니다. 보안을 위해 환경 변수는 복사되지 않습니다.",
+ "duplicate_env_notice": "지침, 스킬, 명령 인수는 복사됩니다. 환경 변수, MCP 서버, 머신 로컬 런타임 설정은 복사되지 않습니다.",
+ "duplicate_runtime_reset_notice": "원래 런타임을 사용할 수 없어 이 복사본은 다른 런타임에서 실행됩니다. 모델, 추론 수준, 속도는 선택한 런타임에서만 유효하므로 초기화되었습니다.",
"create_and_open": "만들고 열기",
"create_and_add": "만들고 스쿼드에 추가",
"creating": "에이전트 만드는 중…",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index e316315e04..455ac8f0cf 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -306,10 +306,12 @@
"behavior": "行为与能力",
"behavior_hint": "定义它的工作方式,并添加可使用的工作区 skill。",
"execution": "运行方式",
- "execution_hint": "选择智能体使用的运行时,也可以覆盖运行时的默认模型。",
+ "execution_hint": "选择智能体使用的运行时,也可以覆盖运行时的默认模型、思考等级和速度。",
"access": "访问权限",
"access_hint": "控制谁可以运行此智能体,创建后仍可修改。"
},
+ "thinking_label": "思考",
+ "speed_label": "速度",
"access": {
"private": {
"title": "只有我",
@@ -351,7 +353,8 @@
},
"live_draft": "智能体配置",
"live_draft_hint": "对话生成的建议会更新到这里,你也可以随时直接调整。",
- "duplicate_env_notice": "指令、skill、模型和命令行参数会被复制。出于安全考虑,环境变量不会复制。",
+ "duplicate_env_notice": "指令、skill 和命令行参数会被复制。环境变量、MCP 服务器和本机运行时配置不会复制。",
+ "duplicate_runtime_reset_notice": "原运行时当前不可用,副本已改用其他运行时。模型、思考等级和速度只在所选运行时上有效,因此已被清空。",
"create_and_open": "创建并打开",
"create_and_add": "创建并加入小队",
"creating": "正在创建…",