Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-3495: support custom runtime args and registration errors (#4408)
Multica Eve12ea1f6a8c70
diff --git a/docs/custom-runtimes.md b/docs/custom-runtimes.mdnew file mode 100644index 0000000000..126b9e2cca--- /dev/null+++ b/docs/custom-runtimes.md@@ -0,0 +1,61 @@+# Custom runtimes++Custom runtime profiles let a workspace register an AI CLI that speaks one of+Multica's supported protocol families but is launched through a team-specific+command.++## Command and arguments++Paste the same argv-style command you would run in a terminal:++```sh+agent --model composer-2.5+```++Multica stores this as:++- `command_name`: `agent`+- `fixed_args`: `["--model", "composer-2.5"]`++The daemon starts the process directly with `exec.Command(command_name,+fixed_args...)`; it does not run a shell.++Supported input:++- plain arguments separated by whitespace+- single or double quotes for values with spaces+- backslash escaping for literal spaces or quote characters++The UI parser is argv-oriented, not a full POSIX shell. Inside double quotes,+`\` escapes the next character directly; use single quotes when you need `$` or+backticks to stay literal. Running tasks keep the launch args they started with;+profile command or argument edits apply to newly claimed tasks after the daemon+re-registers.++Unsupported input:++- pipes, redirects, `;`, `&&`, `||`+- backticks+- `$VAR` or `$(...)` expansion++Use a wrapper script when the runtime needs shell behavior.++## Command not found++Desktop-launched daemons may not inherit the same `PATH` as an interactive+terminal. If a custom runtime shows a registration error even though the command+works in your shell, pin the absolute path on that machine:++```sh+multica runtime profile set-path <profile-id> --path /abs/path/to/agent+```++Then restart or refresh the daemon so it re-registers the profile.++## Upgrade order++Custom runtime arguments and registration-error reporting require both the+server and daemon versions that support `fixed_args` launch specs and+`failed_profiles` registration reports. In mixed deployments, upgrade the server+before rolling out newer daemons so failed custom-only profiles can be recorded+instead of being rejected as an empty runtime registration.diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.jsonindex c0ab3f6869..e1fd1247c0 100644--- a/packages/views/locales/en/runtimes.json+++ b/packages/views/locales/en/runtimes.json@@ -271,6 +271,7 @@"badge_registering": "Registering","pending_health": "Registering with daemon","pending_health_warning": "Waiting for daemon sync",+ "pending_health_error": "Registration error","pending_cli_unknown": "waiting"},"profiles": {@@ -317,11 +318,17 @@"display_name_label": "Display name","display_name_placeholder": "My custom Claude","command_name_label": "Command",- "command_name_placeholder": "claude",+ "command_name_placeholder": "agent --model composer-2.5","description_label": "Description","description_placeholder": "Optional — what this runtime is for","error_display_name_required": "Display name is required.","error_command_required": "Command is required.",+ "error_command_unclosed_quote": "Close the quote before saving.",+ "error_command_trailing_escape": "Complete or remove the trailing backslash before saving.",+ "error_command_shell_syntax": "Shell pipelines, redirects, and control operators are not supported. Use a wrapper script for that.",+ "error_command_shell_expansion": "Shell variable and command expansion is not supported. Use an absolute path or wrapper script.",+ "command_preview_executable": "Executable:",+ "command_preview_args": "Args:","back": "Back","cancel": "Cancel","next": "Next",diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.jsonindex e0c93ee2c2..90043fcab8 100644--- a/packages/views/locales/ja/runtimes.json+++ b/packages/views/locales/ja/runtimes.json@@ -259,6 +259,7 @@"badge_registering": "登録中","pending_health": "Daemon に登録中","pending_health_warning": "Daemon 同期待ち",+ "pending_health_error": "登録エラー","pending_cli_unknown": "待機中"},"profiles": {@@ -305,11 +306,17 @@"display_name_label": "表示名","display_name_placeholder": "マイカスタム Claude","command_name_label": "コマンド",- "command_name_placeholder": "claude",+ "command_name_placeholder": "agent --model composer-2.5","description_label": "説明","description_placeholder": "任意 — このランタイムの用途","error_display_name_required": "表示名は必須です。","error_command_required": "コマンドは必須です。",+ "error_command_unclosed_quote": "保存する前に引用符を閉じてください。",+ "error_command_trailing_escape": "保存する前に末尾のバックスラッシュを補完するか削除してください。",+ "error_command_shell_syntax": "シェルのパイプ、リダイレクト、制御演算子はサポートされていません。必要な場合はラッパースクリプトを使用してください。",+ "error_command_shell_expansion": "シェル変数やコマンド展開はサポートされていません。絶対パスまたはラッパースクリプトを使用してください。",+ "command_preview_executable": "実行ファイル:",+ "command_preview_args": "引数:","back": "戻る","cancel": "キャンセル","next": "次へ",diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.jsonindex a0d8918044..ed5dbcbf91 100644--- a/packages/views/locales/ko/runtimes.json+++ b/packages/views/locales/ko/runtimes.json@@ -271,6 +271,7 @@"badge_registering": "등록 중","pending_health": "Daemon에 등록 중","pending_health_warning": "Daemon 동기화 대기 중",+ "pending_health_error": "등록 오류","pending_cli_unknown": "대기 중"},"profiles": {@@ -317,11 +318,17 @@"display_name_label": "표시 이름","display_name_placeholder": "내 사용자 지정 Claude","command_name_label": "명령",- "command_name_placeholder": "claude",+ "command_name_placeholder": "agent --model composer-2.5","description_label": "설명","description_placeholder": "선택 사항 — 이 런타임의 용도","error_display_name_required": "표시 이름은 필수입니다.","error_command_required": "명령은 필수입니다.",+ "error_command_unclosed_quote": "저장하기 전에 따옴표를 닫으세요.",+ "error_command_trailing_escape": "저장하기 전에 끝의 백슬래시를 완성하거나 제거하세요.",+ "error_command_shell_syntax": "셸 파이프, 리디렉션, 제어 연산자는 지원되지 않습니다. 이런 동작이 필요하면 래퍼 스크립트를 사용하세요.",+ "error_command_shell_expansion": "셸 변수 및 명령 치환은 지원되지 않습니다. 절대 경로나 래퍼 스크립트를 사용하세요.",+ "command_preview_executable": "실행 파일:",+ "command_preview_args": "인수:","back": "뒤로","cancel": "취소","next": "다음",diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.jsonindex 4e5b435eab..465884a060 100644--- a/packages/views/locales/zh-Hans/runtimes.json+++ b/packages/views/locales/zh-Hans/runtimes.json@@ -259,6 +259,7 @@"badge_registering": "注册中","pending_health": "正在向守护进程注册","pending_health_warning": "等待守护进程同步",+ "pending_health_error": "注册错误","pending_cli_unknown": "等待中"},"profiles": {@@ -305,11 +306,17 @@"display_name_label": "显示名称","display_name_placeholder": "我的自定义 Claude","command_name_label": "命令",- "command_name_placeholder": "claude",+ "command_name_placeholder": "agent --model composer-2.5","description_label": "描述","description_placeholder": "可选 — 此运行时的用途","error_display_name_required": "显示名称为必填项。","error_command_required": "命令为必填项。",+ "error_command_unclosed_quote": "保存前请先闭合引号。",+ "error_command_trailing_escape": "保存前请补全或移除末尾的反斜杠。",+ "error_command_shell_syntax": "不支持 shell 管道、重定向和控制操作符。需要这些能力时请使用 wrapper 脚本。",+ "error_command_shell_expansion": "不支持 shell 变量或命令展开。请使用绝对路径或 wrapper 脚本。",+ "command_preview_executable": "可执行文件:",+ "command_preview_args": "参数:","back": "返回","cancel": "取消","next": "下一步",diff --git a/packages/views/runtimes/components/pending-runtime.ts b/packages/views/runtimes/components/pending-runtime.tsindex 9fd9eab07b..b87729c808 100644--- a/packages/views/runtimes/components/pending-runtime.ts+++ b/packages/views/runtimes/components/pending-runtime.ts@@ -29,6 +29,14 @@ export function pendingRuntimeCommandName(runtime: AgentRuntime): string | nullreturn typeof command === "string" && command.trim() ? command : null;}+export function customRuntimeRegistrationFailure(+ runtime: AgentRuntime,+): string | null {+ if (runtime.metadata?.runtime_profile_registration_error !== true) return null;+ const reason = runtime.metadata.runtime_profile_failure_reason;+ return typeof reason === "string" && reason.trim() ? reason : null;+}+export function isPendingCustomRuntimeWarning(runtime: AgentRuntime,now: number,diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsxindex 2bd554c680..5cdfe4e803 100644--- a/packages/views/runtimes/components/runtime-list.tsx+++ b/packages/views/runtimes/components/runtime-list.tsx@@ -59,6 +59,7 @@ import {} from "../utils";import { splitRuntimeName } from "./runtime-machines";import {+ customRuntimeRegistrationFailure,isPendingCustomRuntime,isPendingCustomRuntimeWarning,pendingRuntimeCommandName,@@ -269,6 +270,20 @@ function HealthCell({const { t } = useT("runtimes");const { t: tAgents } = useT("agents");const labelOf = useHealthLabel();+ const registrationFailure = customRuntimeRegistrationFailure(runtime);+ if (registrationFailure) {+ return (+ <ListGridCell className="gap-1.5">+ <AlertTriangle className="h-3.5 w-3.5 shrink-0 text-destructive" />+ <span+ className="block min-w-0 truncate text-xs text-destructive"+ title={registrationFailure}+ >+ {t(($) => $.list.pending_health_error)}+ </span>+ </ListGridCell>+ );+ }if (isPendingCustomRuntime(runtime)) {const warning = isPendingCustomRuntimeWarning(runtime, now);return (@@ -370,6 +385,25 @@ export function CostCell({ runtimeId }: { runtimeId: string }) {export function CliCell({ runtime }: { runtime: AgentRuntime }) {const { t } = useT("runtimes");+ const failure = customRuntimeRegistrationFailure(runtime);+ if (failure) {+ const command = pendingRuntimeCommandName(runtime);+ return (+ <div className="flex min-w-0 flex-col text-xs">+ {command && (+ <span+ className="truncate font-mono text-muted-foreground"+ title={command}+ >+ {command}+ </span>+ )}+ <span className="truncate text-destructive" title={failure}>+ {failure}+ </span>+ </div>+ );+ }if (isPendingCustomRuntime(runtime)) {const command = pendingRuntimeCommandName(runtime);if (!command) {diff --git a/packages/views/runtimes/components/runtime-profile-catalog.test.ts b/packages/views/runtimes/components/runtime-profile-catalog.test.tsindex 9fbe36a1d9..454e164432 100644--- a/packages/views/runtimes/components/runtime-profile-catalog.test.ts+++ b/packages/views/runtimes/components/runtime-profile-catalog.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from "vitest";import type { RuntimeProfile } from "@multica/core/types";-import { buildRuntimeCatalog, PROTOCOL_FAMILIES } from "./runtime-profile-catalog";+import {+ buildRuntimeCatalog,+ formatCommandLine,+ parseCommandLine,+ PROTOCOL_FAMILIES,+} from "./runtime-profile-catalog";function profile(id: string,@@ -60,3 +65,73 @@ describe("buildRuntimeCatalog", () => {]);});});++describe("parseCommandLine", () => {+ it("splits a pasted executable and fixed args", () => {+ expect(parseCommandLine("agent --model composer-2.5")).toEqual({+ ok: true,+ commandName: "agent",+ fixedArgs: ["--model", "composer-2.5"],+ });+ });++ it("preserves quoted whitespace and escaped characters", () => {+ expect(parseCommandLine(`agent --flag "a b c" path\\ with\\ spaces`)).toEqual({+ ok: true,+ commandName: "agent",+ fixedArgs: ["--flag", "a b c", "path with spaces"],+ });+ });++ it("rejects shell control syntax", () => {+ expect(parseCommandLine("agent && rm -rf /")).toEqual({+ ok: false,+ error: "shell_syntax",+ });+ expect(parseCommandLine("agent | tee out")).toEqual({+ ok: false,+ error: "shell_syntax",+ });+ });++ it("rejects shell expansion syntax", () => {+ expect(parseCommandLine("agent --path $HOME/bin")).toEqual({+ ok: false,+ error: "shell_expansion",+ });+ expect(parseCommandLine("agent --path $(which foo)")).toEqual({+ ok: false,+ error: "shell_expansion",+ });+ });++ it("allows literal shell-looking characters inside single quotes", () => {+ expect(parseCommandLine("agent --note '$5 reward `literal`'")).toEqual({+ ok: true,+ commandName: "agent",+ fixedArgs: ["--note", "$5 reward `literal`"],+ });+ });++ it("rejects unclosed quotes", () => {+ expect(parseCommandLine(`agent --flag "unterminated`)).toEqual({+ ok: false,+ error: "unclosed_quote",+ });+ });++ it("rejects a trailing escape", () => {+ expect(parseCommandLine("agent \\")).toEqual({+ ok: false,+ error: "trailing_escape",+ });+ });+});++describe("formatCommandLine", () => {+ it("quotes args that need shell escaping for display", () => {+ expect(formatCommandLine("agent", ["--flag", "a b c"])).toBe(+ 'agent --flag "a b c"',+ );+ });+});diff --git a/packages/views/runtimes/components/runtime-profile-catalog.ts b/packages/views/runtimes/components/runtime-profile-catalog.tsindex 3009ea3ef5..6076bf904f 100644--- a/packages/views/runtimes/components/runtime-profile-catalog.ts+++ b/packages/views/runtimes/components/runtime-profile-catalog.ts@@ -63,20 +63,120 @@ export function buildRuntimeCatalog(return { customs, builtins };}-// NOTE: `fixed_args` is intentionally NOT exposed in the v1 UI. The server-// still carries the column, but the daemon does not yet splice these args into-// the agent launch command, so surfacing an input/display here would promise-// admins a behavior that does not exist. Re-introduce the parse/format helpers-// and the form field only once the daemon actually passes them to the backend-// (proven by a test). See TODO(MUL-3284) in server/internal/daemon/daemon.go.-export interface ProfileFormValues {displayName: string;- commandName: string;+ commandLine: string;description: string;}-export type ProfileFormErrorField = "displayName" | "commandName";+export type ProfileFormErrorField = "displayName" | "commandLine";++export type CommandLineParseError =+ | "empty"+ | "unclosed_quote"+ | "trailing_escape"+ | "shell_syntax"+ | "shell_expansion";++export type ParsedCommandLine =+ | { ok: true; commandName: string; fixedArgs: string[] }+ | { ok: false; error: CommandLineParseError };++const SHELL_CONTROL_CHARS = new Set(["|", ">", "<", ";", "&"]);++export function parseCommandLine(input: string): ParsedCommandLine {+ const line = input.trim();+ if (!line) return { ok: false, error: "empty" };++ const tokens: string[] = [];+ let token = "";+ let quote: "'" | '"' | null = null;+ let tokenStarted = false;++ for (let i = 0; i < line.length; i += 1) {+ const ch = line[i] ?? "";+ const next = line[i + 1] ?? "";++ if (quote == null && /\s/.test(ch)) {+ if (tokenStarted) {+ tokens.push(token);+ token = "";+ tokenStarted = false;+ }+ continue;+ }++ if (quote == null) {+ if (ch === "`" || ch === "$") {+ return {+ ok: false,+ error: ch === "$" ? "shell_expansion" : "shell_syntax",+ };+ }+ if (SHELL_CONTROL_CHARS.has(ch)) {+ return { ok: false, error: "shell_syntax" };+ }+ if (ch === "\\" && next) {+ token += next;+ tokenStarted = true;+ i += 1;+ continue;+ }+ if (ch === "\\") {+ return { ok: false, error: "trailing_escape" };+ }+ if (ch === "'" || ch === '"') {+ quote = ch;+ tokenStarted = true;+ continue;+ }+ token += ch;+ tokenStarted = true;+ continue;+ }++ if (ch === quote) {+ quote = null;+ tokenStarted = true;+ continue;+ }+ if (quote === '"' && ch === "\\" && next) {+ token += next;+ tokenStarted = true;+ i += 1;+ continue;+ }+ if (quote === '"' && ch === "\\") {+ return { ok: false, error: "trailing_escape" };+ }+ if (quote !== "'" && (ch === "`" || ch === "$")) {+ return {+ ok: false,+ error: ch === "$" ? "shell_expansion" : "shell_syntax",+ };+ }+ token += ch;+ tokenStarted = true;+ }++ if (quote != null) return { ok: false, error: "unclosed_quote" };+ if (tokenStarted) tokens.push(token);+ if (tokens.length === 0 || !tokens[0]?.trim()) {+ return { ok: false, error: "empty" };+ }++ return { ok: true, commandName: tokens[0], fixedArgs: tokens.slice(1) };+}++export function formatCommandLine(commandName: string, fixedArgs: string[]): string {+ return [commandName, ...fixedArgs].filter(Boolean).map(quoteArg).join(" ");+}++function quoteArg(arg: string): string {+ if (arg === "") return '""';+ if (!/[\s"'\\|<>;&`$]/.test(arg)) return arg;+ return `"${arg.replace(/(["\\$`])/g, "\\$1")}"`;+}// Pure, synchronous validation for the create/edit form. Returns the set of// invalid fields (empty = valid). Display name and command name are the only@@ -86,7 +186,7 @@ export function validateProfileForm(): ProfileFormErrorField[] {const errors: ProfileFormErrorField[] = [];if (!values.displayName.trim()) errors.push("displayName");- if (!values.commandName.trim()) errors.push("commandName");+ if (!values.commandLine.trim()) errors.push("commandLine");return errors;}diff --git a/packages/views/runtimes/components/runtime-profiles-dialog.test.tsx b/packages/views/runtimes/components/runtime-profiles-dialog.test.tsxindex a783e2877c..743900f7a1 100644--- a/packages/views/runtimes/components/runtime-profiles-dialog.test.tsx+++ b/packages/views/runtimes/components/runtime-profiles-dialog.test.tsx@@ -1,7 +1,7 @@// @vitest-environment jsdomimport { describe, expect, it, beforeEach, vi } from "vitest";-import { fireEvent, render, screen } from "@testing-library/react";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";import { I18nProvider } from "@multica/core/i18n/react";import type { RuntimeProfile } from "@multica/core/types";import enCommon from "../../locales/en/common.json";@@ -11,6 +11,10 @@ const queryState = vi.hoisted(() => ({profiles: [] as RuntimeProfile[],isLoading: false,}));+const mutationState = vi.hoisted(() => ({+ createProfile: vi.fn(),+ updateProfile: vi.fn(),+}));vi.mock("@tanstack/react-query", async () => {const actual =@@ -30,6 +34,20 @@ vi.mock("sonner", () => ({toast: { error: vi.fn(), success: vi.fn() },}));+vi.mock("@multica/core/runtimes", () => ({+ runtimeProfileListOptions: vi.fn((wsId: string) => ({+ queryKey: ["runtime-profiles", wsId, "list"],+ })),+ useCreateRuntimeProfile: vi.fn(() => ({+ isPending: false,+ mutateAsync: mutationState.createProfile,+ })),+ useUpdateRuntimeProfile: vi.fn(() => ({+ isPending: false,+ mutateAsync: mutationState.updateProfile,+ })),+}));+vi.mock("./delete-runtime-profile-dialog", () => ({DeleteRuntimeProfileDialog: () => null,}));@@ -73,6 +91,13 @@ describe("RuntimeProfilesDialog", () => {queryState.profiles = [];queryState.isLoading = false;vi.clearAllMocks();+ mutationState.createProfile.mockResolvedValue(+ profile({+ command_name: "agent",+ fixed_args: ["--model", "composer-2.5"],+ }),+ );+ mutationState.updateProfile.mockResolvedValue(profile());});it("shows the custom empty state and keeps built-in protocols collapsed", () => {@@ -142,4 +167,37 @@ describe("RuntimeProfilesDialog", () => {screen.queryByText(/claude is a built-in protocol family/),).not.toBeInTheDocument();});++ it("parses a pasted command line into fixed_args on create", async () => {+ renderDialog();++ const newRuntimeButtons = screen.getAllByRole("button", {+ name: "New custom runtime",+ });+ expect(newRuntimeButtons[0]).toBeDefined();+ fireEvent.click(newRuntimeButtons[0]!);+ fireEvent.click(screen.getByRole("radio", { name: /codex/i }));+ fireEvent.change(screen.getByLabelText("Display name"), {+ target: { value: "Composer Agent" },+ });+ fireEvent.change(screen.getByLabelText("Command"), {+ target: { value: "agent --model composer-2.5" },+ });++ expect(screen.getByText("Executable:")).toBeInTheDocument();+ expect(screen.getByText("agent")).toBeInTheDocument();+ expect(screen.getByText("--model")).toBeInTheDocument();+ expect(screen.getByText("composer-2.5")).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Create runtime" }));++ await waitFor(() =>+ expect(mutationState.createProfile).toHaveBeenCalledWith({+ display_name: "Composer Agent",+ protocol_family: "codex",+ command_name: "agent",+ fixed_args: ["--model", "composer-2.5"],+ }),+ );+ });});diff --git a/packages/views/runtimes/components/runtime-profiles-dialog.tsx b/packages/views/runtimes/components/runtime-profiles-dialog.tsxindex 9a2cf68559..630641844f 100644--- a/packages/views/runtimes/components/runtime-profiles-dialog.tsx+++ b/packages/views/runtimes/components/runtime-profiles-dialog.tsx@@ -42,6 +42,8 @@ import { DeleteRuntimeProfileDialog } from "./delete-runtime-profile-dialog";import {PROTOCOL_FAMILIES,buildRuntimeCatalog,+ formatCommandLine,+ parseCommandLine,validateProfileForm,type ProfileFormErrorField,type ProfileFormValues,@@ -471,6 +473,10 @@ function DetailPanel({}const profile = entry.profile;+ const commandLine = formatCommandLine(+ profile.command_name,+ profile.fixed_args,+ );return (<div className="flex min-h-0 flex-1 flex-col">@@ -499,7 +505,7 @@ function DetailPanel({<span className="capitalize">{profile.protocol_family}</span></DetailRow><DetailRow label={t(($) => $.profiles.detail.command)}>- <span className="font-mono text-xs">{profile.command_name}</span>+ <span className="font-mono text-xs">{commandLine}</span></DetailRow><DetailRow label={t(($) => $.profiles.detail.description)}>{profile.description ? (@@ -673,7 +679,9 @@ function ProfileDetailsForm({const [values, setValues] = useState<ProfileFormValues>({displayName: profile?.display_name ?? "",- commandName: profile?.command_name ?? "",+ commandLine: profile+ ? formatCommandLine(profile.command_name, profile.fixed_args)+ : "",description: profile?.description ?? "",});const [errors, setErrors] = useState<ProfileFormErrorField[]>([]);@@ -687,22 +695,34 @@ function ProfileDetailsForm({setValues((prev) => ({ ...prev, [key]: value }));};+ const parsedCommand = useMemo(+ () => parseCommandLine(values.commandLine),+ [values.commandLine],+ );+const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {event.preventDefault();setFormError(null);setDuplicateName(false);const validationErrors = validateProfileForm(values);+ if (!validationErrors.includes("commandLine") && !parsedCommand.ok) {+ validationErrors.push("commandLine");+ }setErrors(validationErrors);if (validationErrors.length > 0) return;+ if (!parsedCommand.ok) return;const description = values.description.trim();+ const commandName = parsedCommand.commandName;+ const fixedArgs = parsedCommand.fixedArgs;try {if (mode === "create") {const created = await createProfile.mutateAsync({display_name: values.displayName.trim(),protocol_family: family,- command_name: values.commandName.trim(),+ command_name: commandName,+ fixed_args: fixedArgs,...(description ? { description } : {}),});toast.success(t(($) => $.profiles.form.toast_created));@@ -712,7 +732,8 @@ function ProfileDetailsForm({profileId: profile.id,patch: {display_name: values.displayName.trim(),- command_name: values.commandName.trim(),+ command_name: commandName,+ fixed_args: fixedArgs,description: description ? description : null,},});@@ -735,6 +756,22 @@ function ProfileDetailsForm({const formId = `${idPrefix}-form`;const hasError = (field: ProfileFormErrorField) => errors.includes(field);+ const parseErrorMessage =+ !parsedCommand.ok && parsedCommand.error === "unclosed_quote"+ ? t(($) => $.profiles.form.error_command_unclosed_quote)+ : !parsedCommand.ok && parsedCommand.error === "trailing_escape"+ ? t(($) => $.profiles.form.error_command_trailing_escape)+ : !parsedCommand.ok && parsedCommand.error === "shell_expansion"+ ? t(($) => $.profiles.form.error_command_shell_expansion)+ : !parsedCommand.ok && parsedCommand.error === "shell_syntax"+ ? t(($) => $.profiles.form.error_command_shell_syntax)+ : null;+ const commandError =+ hasError("commandLine") && !values.commandLine.trim()+ ? t(($) => $.profiles.form.error_command_required)+ : hasError("commandLine") && !parsedCommand.ok+ ? (parseErrorMessage ?? t(($) => $.profiles.form.error_command_required))+ : null;return (<div className="flex min-h-0 flex-1 flex-col">@@ -809,20 +846,43 @@ function ProfileDetailsForm({</Label><Inputid={`${idPrefix}-command`}- value={values.commandName}- onChange={(e) => setField("commandName", e.target.value)}+ value={values.commandLine}+ onChange={(e) => setField("commandLine", e.target.value)}placeholder={t(($) => $.profiles.form.command_name_placeholder)}- aria-invalid={hasError("commandName")}+ aria-invalid={hasError("commandLine")}aria-describedby={- hasError("commandName") ? `${idPrefix}-command-error` : undefined+ hasError("commandLine") ? `${idPrefix}-command-error` : undefined}className="h-9 font-mono text-sm"/>- {hasError("commandName") && (+ {commandError && (<p id={`${idPrefix}-command-error`} className="text-xs text-destructive">- {t(($) => $.profiles.form.error_command_required)}+ {commandError}</p>)}+ {parsedCommand.ok && (+ <div className="space-y-1 rounded-md border bg-muted/20 px-3 py-2 text-[11px] text-muted-foreground">+ <div className="flex min-w-0 gap-1">+ <span>{t(($) => $.profiles.form.command_preview_executable)}</span>+ <span className="truncate font-mono text-foreground">+ {parsedCommand.commandName}+ </span>+ </div>+ {parsedCommand.fixedArgs.length > 0 && (+ <div className="flex min-w-0 flex-wrap gap-1">+ <span>{t(($) => $.profiles.form.command_preview_args)}</span>+ {parsedCommand.fixedArgs.map((arg, index) => (+ <span+ key={`${arg}-${index}`}+ className="rounded bg-background px-1 font-mono text-foreground"+ >+ {arg}+ </span>+ ))}+ </div>+ )}+ </div>+ )}</div><div className="space-y-1.5">@@ -841,12 +901,6 @@ function ProfileDetailsForm({/></div>- {/* NOTE: a `fixed_args` input is intentionally omitted in v1 — the- daemon does not yet pass these args to the agent launch command, so- exposing the field would promise admins a no-op. Re-add only once- it's wired end-to-end. See TODO(MUL-3284) in- server/internal/daemon/daemon.go. */}-{/* NOTE: a visibility control is intentionally omitted in v1. Theserver forces every profile to 'workspace' because the read paths(list, daemon pull, register) do not yet enforce 'private', sodiff --git a/server/cmd/multica/cmd_runtime_profile.go b/server/cmd/multica/cmd_runtime_profile.goindex 14623a2399..5992057669 100644--- a/server/cmd/multica/cmd_runtime_profile.go+++ b/server/cmd/multica/cmd_runtime_profile.go@@ -100,11 +100,10 @@ func init() {runtimeProfileUpdateCmd.Flags().String("display-name", "", "New display name")runtimeProfileUpdateCmd.Flags().String("command-name", "", "New command name")runtimeProfileUpdateCmd.Flags().String("description", "", "New description")- // NOTE: a --fixed-arg flag is intentionally NOT exposed in v1. The server- // carries the fixed_args column, but the daemon does not yet pass these- // args to the agent launch command, so a CLI flag would promise admins a- // no-op. Re-add once it's wired end-to-end (TODO(MUL-3284), see- // server/internal/daemon/daemon.go).+ // NOTE: --fixed-arg remains out of the CLI create/update surface for now:+ // the product path parses command + args in the UI and stores them as+ // command_name + fixed_args. Keep this CLI shape narrow until we add an+ // argv-aware command-line parser here too.runtimeProfileUpdateCmd.Flags().Bool("enabled", true, "Enable or disable the profile")runtimeProfileUpdateCmd.Flags().String("output", "json", "Output format: table or json")diff --git a/server/cmd/multica/cmd_runtime_profile_test.go b/server/cmd/multica/cmd_runtime_profile_test.goindex 11a4b782b6..805535e7ae 100644--- a/server/cmd/multica/cmd_runtime_profile_test.go+++ b/server/cmd/multica/cmd_runtime_profile_test.go@@ -155,8 +155,8 @@ func TestRunRuntimeProfileCreate(t *testing.T) {if gotBody["protocol_family"] != "codex" || gotBody["command_name"] != "company-codex" || gotBody["display_name"] != "Company Codex" {t.Errorf("unexpected body: %#v", gotBody)}- // fixed_args is intentionally NOT exposed by the CLI in v1 (the daemon does- // not yet wire it into the launch command), so it must never be sent.+ // fixed_args is intentionally NOT exposed by the CLI create path yet; the+ // UI owns command-line parsing until this CLI grows an argv-aware parser.if _, present := gotBody["fixed_args"]; present {t.Errorf("fixed_args must not be sent by the CLI, got %#v", gotBody["fixed_args"])}diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex f052ef706b..7c329c85c2 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -293,8 +293,8 @@ type (func (c *Client) SendHeartbeat(ctx context.Context, runtimeID string) (*HeartbeatResponse, error) {var resp HeartbeatResponseif err := c.postJSON(ctx, "/api/daemon/heartbeat", map[string]any{- "runtime_id": runtimeID,- "supports_batch_import": true,+ "runtime_id": runtimeID,+ "supports_batch_import": true,}, &resp); err != nil {return nil, err}@@ -467,8 +467,7 @@ func (c *Client) GetWorkspaceRepos(ctx context.Context, workspaceID string) (*Wo// (MUL-3284). protocol_family is the provider used for task routing (it// selects the agent backend), while command_name is the actual executable// the daemon resolves on PATH and launches. fixed_args are launch arguments-// every agent on this runtime inherits — wiring them into the spawned command-// is best-effort and may not be plumbed yet (see the TODO in runTask).+// every agent on this runtime inherits.type RuntimeProfile struct {ID string `json:"id"`WorkspaceID string `json:"workspace_id"`diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 387fa81bf5..f253306ae6 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -149,14 +149,14 @@ type Daemon struct {mu sync.Mutexworkspaces map[string]*workspaceStateruntimeIndex map[string]Runtime // runtimeID -> Runtime for provider lookups- // profileCommandPaths maps a custom runtime profile_id -> the absolute- // executable path resolved on PATH for that profile's command_name+ // profileLaunchSpecs maps a custom runtime profile_id -> the absolute+ // executable path plus fixed launch args resolved for that profile// (MUL-3284). Populated in registerRuntimesForWorkspace when a profile's- // command resolves; read by runTask via customCommandPathForRuntime to- // launch the custom command for a claimed task. Guarded by mu.- profileCommandPaths map[string]string- reloading sync.Mutex // prevents concurrent workspace syncs- runtimeSet *runtimeSetWatcher // multi-subscriber pub/sub for runtime-set changes+ // command resolves; read by runTask to launch the custom command for a+ // claimed task. Guarded by mu.+ profileLaunchSpecs map[string]profileLaunchSpec+ reloading sync.Mutex // prevents concurrent workspace syncs+ runtimeSet *runtimeSetWatcher // multi-subscriber pub/sub for runtime-set changesversionsMu sync.RWMutex // guards agentVersionsagentVersions map[string]string // provider -> detected CLI version (set during registration)@@ -222,6 +222,11 @@ type Daemon struct {runUpdateFn func(targetVersion string) (string, error)}+type profileLaunchSpec struct {+ path string+ fixedArgs []string+}+// New creates a new Daemon instance.func New(cfg Config, logger *slog.Logger) *Daemon {cacheRoot := filepath.Join(cfg.WorkspacesRoot, ".repos")@@ -236,7 +241,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {logger: logger,workspaces: make(map[string]*workspaceState),runtimeIndex: make(map[string]Runtime),- profileCommandPaths: make(map[string]string),+ profileLaunchSpecs: make(map[string]profileLaunchSpec),runtimeSet: newRuntimeSetWatcher(),agentVersions: make(map[string]string),wsHBLastAck: make(map[string]time.Time),@@ -848,48 +853,51 @@ func (d *Daemon) findRuntime(id string) *Runtime {return nil}-// recordProfileCommandPath remembers the absolute executable path resolved-// for a custom runtime profile's command_name. Called from+// recordProfileLaunch remembers the absolute executable path and fixed launch+// args resolved for a custom runtime profile. Called from// registerRuntimesForWorkspace. Lazily initializes the map so test fixtures// that build a Daemon literal without seeding every map don't panic.-func (d *Daemon) recordProfileCommandPath(profileID, path string) {+func (d *Daemon) recordProfileLaunch(profileID, path string, fixedArgs []string) {if profileID == "" || path == "" {return}d.mu.Lock()defer d.mu.Unlock()- if d.profileCommandPaths == nil {- d.profileCommandPaths = make(map[string]string)+ if d.profileLaunchSpecs == nil {+ d.profileLaunchSpecs = make(map[string]profileLaunchSpec)+ }+ d.profileLaunchSpecs[profileID] = profileLaunchSpec{+ path: path,+ fixedArgs: append([]string(nil), fixedArgs...),}- d.profileCommandPaths[profileID] = path}-// customCommandPathForRuntime returns the resolved custom executable path for-// a claimed task's RuntimeID, and whether the runtime is a custom-profile-// runtime. It returns ("", false) for built-in runtimes (no profile) and for-// runtimes whose profile command was never resolved on this host. runTask-// uses this to override the launch path so a custom runtime can run even when-// the host has no built-in agent of the same provider installed.-func (d *Daemon) customCommandPathForRuntime(runtimeID string) (string, bool) {+// customProfileLaunchForRuntime returns the resolved custom executable path and+// fixed args for a claimed task's RuntimeID, and whether the runtime is a+// custom-profile runtime. It returns false for built-in runtimes (no profile)+// and for runtimes whose profile command was never resolved on this host.+func (d *Daemon) customProfileLaunchForRuntime(runtimeID string) (profileLaunchSpec, bool) {if runtimeID == "" {- return "", false+ return profileLaunchSpec{}, false}d.mu.Lock()defer d.mu.Unlock()rt, ok := d.runtimeIndex[runtimeID]if !ok || rt.ProfileID == "" {- return "", false+ return profileLaunchSpec{}, false}- path, ok := d.profileCommandPaths[rt.ProfileID]- if !ok || path == "" {- return "", false+ spec, ok := d.profileLaunchSpecs[rt.ProfileID]+ if !ok || spec.path == "" {+ return profileLaunchSpec{}, false}- return path, true+ spec.fixedArgs = append([]string(nil), spec.fixedArgs...)+ return spec, true}func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID string) (*RegisterResponse, string, error) {d.logger.Debug("registering runtimes for workspace", "workspace_id", workspaceID, "agent_count", len(d.cfg.Agents))var runtimes []map[string]string+ var failedProfiles []map[string]stringfor name, entry := range d.cfg.Agents {version, err := detectAgentVersion(ctx, entry.Path)if err != nil {@@ -925,9 +933,9 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s// between sync ticks without making an extra round trip on every tick// (MUL-3332). An empty string means the fetch failed and the caller must// keep whatever signature was previously cached on the workspaceState.- profileSig := d.appendProfileRuntimes(ctx, workspaceID, &runtimes)+ profileSig := d.appendProfileRuntimes(ctx, workspaceID, &runtimes, &failedProfiles)- if len(runtimes) == 0 {+ if len(runtimes) == 0 && len(failedProfiles) == 0 {// profileSig is still meaningful even when nothing resolves: the// drift-refresh path uses it to remember "we already converged on the// disabled-everywhere state" so the next sync tick is a no-op instead@@ -944,13 +952,14 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s"cli_version": d.cfg.CLIVersion,"launched_by": d.cfg.LaunchedBy,"runtimes": runtimes,+ "failed_profiles": failedProfiles,}resp, err := d.client.Register(ctx, req)if err != nil {return nil, "", fmt.Errorf("register runtimes: %w", err)}- if len(resp.Runtimes) == 0 {+ if len(resp.Runtimes) == 0 && len(failedProfiles) == 0 {return nil, "", fmt.Errorf("register runtimes: empty response")}d.logger.Debug("register response", "workspace_id", workspaceID, "runtimes", len(resp.Runtimes), "repos", len(resp.Repos), "repos_version", resp.ReposVersion)@@ -960,9 +969,9 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s// appendProfileRuntimes fetches the workspace's enabled custom runtime// profiles (MUL-3284) and appends a runtime registration entry for each one// whose command_name resolves on this host's PATH. For each resolved profile-// it records the absolute command path keyed by profile_id (via-// recordProfileCommandPath) so runTask can later launch the custom executable-// for a claimed task.+// it records the absolute command path and fixed args keyed by profile_id (via+// recordProfileLaunch) so runTask can later launch the custom executable for a+// claimed task.//// Best-effort by contract: any error fetching profiles (older server, network// blip) is logged and swallowed — registration proceeds with the built-in@@ -981,7 +990,7 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s// treat that as "unknown, do not overwrite a previously-stored signature"// (otherwise a transient 5xx would silently flip the daemon into thinking the// workspace has zero profiles).-func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string, runtimes *[]map[string]string) string {+func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string, runtimes *[]map[string]string, failedProfiles *[]map[string]string) string {resp, err := d.client.GetRuntimeProfiles(ctx, workspaceID)if err != nil {// Best-effort: never fail registration because profiles couldn't be@@ -1013,12 +1022,14 @@ func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string,// the override nor PATH resolves, the profile is skipped (existing// behavior).var resolved string+ var failureReason stringif override := strings.TrimSpace(d.cfg.ProfileCommandOverrides[profile.ID]); override != "" {if profilePathExecutable(override) {resolved = overrided.logger.Info("custom runtime profile: using per-machine command path override","workspace_id", workspaceID, "profile_id", profile.ID, "command_path", resolved)} else {+ failureReason = "Configured path override is not executable: " + overrided.logger.Warn("custom runtime profile: command path override not executable; falling back to PATH","workspace_id", workspaceID, "profile_id", profile.ID,"override_path", override, "command_name", profile.CommandName)@@ -1032,6 +1043,15 @@ func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string,d.logger.Info("skip custom runtime profile: command not found on PATH","workspace_id", workspaceID, "profile_id", profile.ID,"command_name", profile.CommandName, "error", err)+ if failureReason != "" {+ failureReason += "; "+ }+ failureReason += "command not found on PATH: " + profile.CommandName+ *failedProfiles = append(*failedProfiles, map[string]string{+ "profile_id": profile.ID,+ "command_name": profile.CommandName,+ "reason": failureReason,+ })continue}resolved = r@@ -1047,15 +1067,10 @@ func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string,if d.cfg.DeviceName != "" {displayName = fmt.Sprintf("%s (%s)", displayName, d.cfg.DeviceName)}- d.recordProfileCommandPath(profile.ID, resolved)+ d.recordProfileLaunch(profile.ID, resolved, profile.FixedArgs)d.logger.Info("registering custom runtime profile","workspace_id", workspaceID, "profile_id", profile.ID,"protocol_family", profile.ProtocolFamily, "command_path", resolved)- // NOTE: profile.FixedArgs are launch args every agent on this runtime- // inherits. Wiring them into the spawned command is intentionally not- // done here — it's an optional, best-effort enhancement (see MUL-3284- // PR2 task notes). TODO(MUL-3284): plumb FixedArgs into the agent- // launch command if/when the agent backend exposes a hook for it.*runtimes = append(*runtimes, map[string]string{"name": displayName,"type": profile.ProtocolFamily,@@ -3127,12 +3142,15 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// Critically, a custom runtime can live on a host that has NO built-in// agent of the same provider installed, so when the runtime is custom we// synthesize an AgentEntry instead of hard-failing on the !ok lookup.- if customPath, isCustom := d.customCommandPathForRuntime(task.RuntimeID); isCustom {- entry.Path = customPath+ var profileFixedArgs []string+ if customSpec, isCustom := d.customProfileLaunchForRuntime(task.RuntimeID); isCustom {+ entry.Path = customSpec.path+ profileFixedArgs = customSpec.fixedArgsok = trued.logger.Info("task uses custom runtime profile command","task_id", task.ID, "runtime_id", task.RuntimeID,- "provider", provider, "command_path", customPath)+ "provider", provider, "command_path", customSpec.path,+ "fixed_args", len(profileFixedArgs))}if !ok {return TaskResult{}, fmt.Errorf("no agent configured for provider %q", provider)@@ -3442,6 +3460,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ivar customArgs []stringextraArgs := defaultArgsForProvider(d.cfg, provider)+ if len(profileFixedArgs) > 0 {+ extraArgs = append(append([]string{}, profileFixedArgs...), extraArgs...)+ }var mcpConfig json.RawMessageif task.Agent != nil {customArgs = task.Agent.CustomArgsdiff --git a/server/internal/daemon/runtime_profile_drift_test.go b/server/internal/daemon/runtime_profile_drift_test.goindex cf7a672978..648e9f0c59 100644--- a/server/internal/daemon/runtime_profile_drift_test.go+++ b/server/internal/daemon/runtime_profile_drift_test.go@@ -198,7 +198,7 @@ func newDriftFixture(t *testing.T, initial []RuntimeProfile) *driftFixture {}))t.Cleanup(srv.Close)d := freshDaemon(srv.URL)- d.profileCommandPaths = make(map[string]string)+ d.profileLaunchSpecs = make(map[string]profileLaunchSpec)fx.daemon = dfx.server = srvreturn fx@@ -594,7 +594,7 @@ func TestRefreshWorkspaceRuntimeProfiles_FetchErrorIsBestEffort(t *testing.T) {}))t.Cleanup(srv.Close)d := freshDaemon(srv.URL)- d.profileCommandPaths = make(map[string]string)+ d.profileLaunchSpecs = make(map[string]profileLaunchSpec)knownSig := profileSetSignature(profiles)d.workspaces["ws-1"] = newWorkspaceState("ws-1", []string{"rt-1"}, "", nil, nil)d.workspaces["ws-1"].profileSetSig = knownSigdiff --git a/server/internal/daemon/runtime_profile_test.go b/server/internal/daemon/runtime_profile_test.goindex aaf8ab191c..12f3557763 100644--- a/server/internal/daemon/runtime_profile_test.go+++ b/server/internal/daemon/runtime_profile_test.go@@ -3,7 +3,6 @@ package daemonimport ("context""encoding/json"- "errors""net/http""net/http/httptest""strconv"@@ -94,6 +93,7 @@ type profileRegisterFixture struct {daemon *Daemonserver *httptest.ServersentRuntimes []map[string]any+ sentFailures []map[string]any}func newProfileRegisterFixture(t *testing.T, profiles []RuntimeProfile, profilesStatus int) *profileRegisterFixture {@@ -103,10 +103,12 @@ func newProfileRegisterFixture(t *testing.T, profiles []RuntimeProfile, profilesswitch {case r.URL.Path == "/api/daemon/register":var body struct {- Runtimes []map[string]any `json:"runtimes"`+ Runtimes []map[string]any `json:"runtimes"`+ FailedProfiles []map[string]any `json:"failed_profiles"`}_ = json.NewDecoder(r.Body).Decode(&body)fx.sentRuntimes = body.Runtimes+ fx.sentFailures = body.FailedProfiles// Echo back a Runtime row per requested runtime, threading// profile_id so the caller can populate runtimeIndex from it.var resp RegisterResponse@@ -140,7 +142,7 @@ func newProfileRegisterFixture(t *testing.T, profiles []RuntimeProfile, profiles}))t.Cleanup(srv.Close)d := freshDaemon(srv.URL)- d.profileCommandPaths = make(map[string]string)+ d.profileLaunchSpecs = make(map[string]profileLaunchSpec)fx.daemon = dfx.server = srvreturn fx@@ -161,6 +163,7 @@ func TestRegisterRuntimes_AppendsProfileRuntime(t *testing.T) {DisplayName: "Company Codex",ProtocolFamily: "codex",CommandName: "company-codex",+ FixedArgs: []string{"--model", "composer-2.5"},Visibility: "workspace",Enabled: true,}}@@ -190,8 +193,12 @@ func TestRegisterRuntimes_AppendsProfileRuntime(t *testing.T) {}// The resolved command path must be recorded keyed by profile_id.- if got := d.profileCommandPaths["prof-1"]; got != "/opt/bin/company-codex" {- t.Errorf("profileCommandPaths[prof-1] = %q, want /opt/bin/company-codex", got)+ got := d.profileLaunchSpecs["prof-1"]+ if got.path != "/opt/bin/company-codex" {+ t.Errorf("profileLaunchSpecs[prof-1].path = %q, want /opt/bin/company-codex", got.path)+ }+ if strings.Join(got.fixedArgs, " ") != "--model composer-2.5" {+ t.Errorf("profileLaunchSpecs[prof-1].fixedArgs = %v, want [--model composer-2.5]", got.fixedArgs)}// The response runtime carries the profile_id back.@@ -200,11 +207,9 @@ func TestRegisterRuntimes_AppendsProfileRuntime(t *testing.T) {}}-// TestRegisterRuntimes_SkipsProfileNotOnPath verifies a profile whose command-// is missing on this host is skipped, and that a host with no built-in agents-// and no resolvable profiles fails registration with the documented sentinel-// (the drift-refresh path keys off ErrNoRuntimesToRegister to take the-// convergence-to-zero branch instead of treating it as a hard error).+// TestRegisterRuntimes_ReportsProfileNotOnPath verifies a profile whose command+// is missing on this host is reported to the server as a failed profile so the+// UI can show an actionable registration error.func TestRegisterRuntimes_SkipsProfileNotOnPath(t *testing.T) {t.Cleanup(stubAgentVersion(t))stubLookPath(t, map[string]string{}) // nothing resolves@@ -222,14 +227,20 @@ func TestRegisterRuntimes_SkipsProfileNotOnPath(t *testing.T) {d.cfg.Agents = map[string]AgentEntry{}_, sig, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")- if !errors.Is(err, ErrNoRuntimesToRegister) {- t.Fatalf("expected ErrNoRuntimesToRegister, got %v", err)+ if err != nil {+ t.Fatalf("registerRuntimesForWorkspace: %v", err)}if sig == "" {t.Errorf("profileSig must still be returned even when registration short-circuits, so the drift path can cache the converged-empty signature")}- if _, ok := d.profileCommandPaths["prof-1"]; ok {- t.Errorf("profileCommandPaths should not record an unresolved profile")+ if _, ok := d.profileLaunchSpecs["prof-1"]; ok {+ t.Errorf("profileLaunchSpecs should not record an unresolved profile")+ }+ if len(fx.sentRuntimes) != 0 {+ t.Fatalf("sent runtimes = %+v, want none", fx.sentRuntimes)+ }+ if len(fx.sentFailures) != 1 || fx.sentFailures[0]["profile_id"] != "prof-1" {+ t.Fatalf("sent failures = %+v, want prof-1", fx.sentFailures)}}@@ -283,8 +294,8 @@ func TestRegisterRuntimes_PrefersCommandPathOverride(t *testing.T) {t.Fatalf("registerRuntimesForWorkspace: %v", err)}- if got := d.profileCommandPaths["prof-1"]; got != "/opt/custom/company-codex" {- t.Errorf("profileCommandPaths[prof-1] = %q, want the override /opt/custom/company-codex", got)+ if got := d.profileLaunchSpecs["prof-1"].path; got != "/opt/custom/company-codex" {+ t.Errorf("profileLaunchSpecs[prof-1].path = %q, want the override /opt/custom/company-codex", got)}if len(fx.sentRuntimes) != 1 || fx.sentRuntimes[0]["profile_id"] != "prof-1" {t.Fatalf("expected the profile runtime to register, got %+v", fx.sentRuntimes)@@ -317,8 +328,8 @@ func TestRegisterRuntimes_OverrideNotExecutableFallsBackToPath(t *testing.T) {t.Fatalf("registerRuntimesForWorkspace: %v", err)}- if got := d.profileCommandPaths["prof-1"]; got != "/usr/bin/company-codex" {- t.Errorf("profileCommandPaths[prof-1] = %q, want the PATH fallback /usr/bin/company-codex", got)+ if got := d.profileLaunchSpecs["prof-1"].path; got != "/usr/bin/company-codex" {+ t.Errorf("profileLaunchSpecs[prof-1].path = %q, want the PATH fallback /usr/bin/company-codex", got)}}@@ -331,29 +342,32 @@ func stubProfilePathExecutable(t *testing.T, executable map[string]bool) {profilePathExecutable = func(path string) bool { return executable[path] }t.Cleanup(func() { profilePathExecutable = orig })}+// bookkeeping that runTask relies on to override the launch path.func TestCustomCommandPathForRuntime(t *testing.T) {d := freshDaemon("")- d.profileCommandPaths = map[string]string{"prof-1": "/opt/bin/company-codex"}+ d.profileLaunchSpecs = map[string]profileLaunchSpec{+ "prof-1": {path: "/opt/bin/company-codex", fixedArgs: []string{"--model", "composer-2.5"}},+ }// rt-custom is a custom-profile runtime; rt-builtin is a normal one.d.runtimeIndex["rt-custom"] = Runtime{ID: "rt-custom", Provider: "codex", ProfileID: "prof-1"}d.runtimeIndex["rt-builtin"] = Runtime{ID: "rt-builtin", Provider: "claude"}- if path, ok := d.customCommandPathForRuntime("rt-custom"); !ok || path != "/opt/bin/company-codex" {- t.Errorf("custom runtime: got (%q, %v), want (/opt/bin/company-codex, true)", path, ok)+ if spec, ok := d.customProfileLaunchForRuntime("rt-custom"); !ok || spec.path != "/opt/bin/company-codex" || strings.Join(spec.fixedArgs, " ") != "--model composer-2.5" {+ t.Errorf("custom runtime: got (%+v, %v), want profile launch spec", spec, ok)}- if path, ok := d.customCommandPathForRuntime("rt-builtin"); ok || path != "" {- t.Errorf("built-in runtime: got (%q, %v), want (\"\", false)", path, ok)+ if spec, ok := d.customProfileLaunchForRuntime("rt-builtin"); ok || spec.path != "" {+ t.Errorf("built-in runtime: got (%+v, %v), want empty false", spec, ok)}- if path, ok := d.customCommandPathForRuntime("rt-unknown"); ok || path != "" {- t.Errorf("unknown runtime: got (%q, %v), want (\"\", false)", path, ok)+ if spec, ok := d.customProfileLaunchForRuntime("rt-unknown"); ok || spec.path != "" {+ t.Errorf("unknown runtime: got (%+v, %v), want empty false", spec, ok)}// A custom runtime whose profile path was never resolved on this host- // (profile_id not in profileCommandPaths) must report not-custom so+ // (profile_id not in profileLaunchSpecs) must report not-custom so// runTask falls back to its normal provider lookup rather than launching// an empty path.d.runtimeIndex["rt-unresolved"] = Runtime{ID: "rt-unresolved", Provider: "codex", ProfileID: "prof-missing"}- if path, ok := d.customCommandPathForRuntime("rt-unresolved"); ok || path != "" {- t.Errorf("unresolved profile: got (%q, %v), want (\"\", false)", path, ok)+ if spec, ok := d.customProfileLaunchForRuntime("rt-unresolved"); ok || spec.path != "" {+ t.Errorf("unresolved profile: got (%+v, %v), want empty false", spec, ok)}}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 540dc18eab..4c37bd854e 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -187,6 +187,11 @@ type DaemonRegisterRequest struct {// so task routing (agent.New) is unchanged.ProfileID string `json:"profile_id"`} `json:"runtimes"`+ FailedProfiles []struct {+ ProfileID string `json:"profile_id"`+ CommandName string `json:"command_name"`+ Reason string `json:"reason"`+ } `json:"failed_profiles"`}type daemonWorkspaceReposResponse struct {@@ -281,8 +286,8 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "workspace_id is required")return}- if len(req.Runtimes) == 0 {- writeError(w, http.StatusBadRequest, "at least one runtime is required")+ if len(req.Runtimes) == 0 && len(req.FailedProfiles) == 0 {+ writeError(w, http.StatusBadRequest, "at least one runtime or failed profile is required")return}wsUUID, ok := parseUUIDOrBadRequest(w, req.WorkspaceID, "workspace_id")@@ -502,6 +507,60 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {resp = append(resp, runtimeToResponse(registered))}+ for _, failed := range req.FailedProfiles {+ profileID := strings.TrimSpace(failed.ProfileID)+ if profileID == "" {+ continue+ }+ profileUUID, pok := parseUUIDOrBadRequest(w, profileID, "profile_id")+ if !pok {+ return+ }+ profile, perr := h.Queries.GetRuntimeProfileForWorkspace(r.Context(), db.GetRuntimeProfileForWorkspaceParams{+ ID: profileUUID,+ WorkspaceID: wsUUID,+ })+ if perr != nil || !profile.Enabled {+ continue+ }+ name := profile.DisplayName+ if req.DeviceName != "" {+ name = fmt.Sprintf("%s (%s)", name, req.DeviceName)+ }+ deviceInfo := strings.TrimSpace(req.DeviceName)+ reason := strings.TrimSpace(failed.Reason)+ if reason == "" {+ reason = "custom runtime command could not be resolved"+ }+ commandName := strings.TrimSpace(failed.CommandName)+ if commandName == "" {+ commandName = profile.CommandName+ }+ metadata, _ := json.Marshal(map[string]any{+ "version": "",+ "cli_version": req.CLIVersion,+ "launched_by": req.LaunchedBy,+ "runtime_profile_registration_error": true,+ "runtime_profile_failure_reason": reason,+ "command_name": commandName,+ })+ if _, err := h.Queries.UpsertAgentRuntimeWithProfile(r.Context(), db.UpsertAgentRuntimeWithProfileParams{+ WorkspaceID: wsUUID,+ DaemonID: strToText(req.DaemonID),+ Name: name,+ RuntimeMode: "local",+ Provider: profile.ProtocolFamily,+ Status: "offline",+ DeviceInfo: deviceInfo,+ Metadata: metadata,+ OwnerID: ownerID,+ ProfileID: profileUUID,+ }); err != nil {+ slog.Warn("failed to record runtime profile registration failure",+ "workspace_id", req.WorkspaceID, "daemon_id", req.DaemonID,+ "profile_id", profileID, "error", err)+ }+ }slog.Info("daemon registered", "workspace_id", req.WorkspaceID, "daemon_id", req.DaemonID, "runtimes_count", len(resp))diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 8e5ffa58c9..2746cf3c2f 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -526,6 +526,58 @@ func TestDaemonRegister_WithDaemonToken(t *testing.T) {testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)}+func TestDaemonRegister_RecordsRuntimeProfileRegistrationFailure(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ profileID := insertRuntimeProfileFixture(t, ctx, "Missing Custom Codex", "codex", "missing-codex")++ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{+ "workspace_id": testWorkspaceID,+ "daemon_id": "test-daemon-profile-failure",+ "device_name": "test-device",+ "failed_profiles": []map[string]any{+ {+ "profile_id": profileID,+ "command_name": "missing-codex",+ "reason": "command not found on PATH: missing-codex",+ },+ },+ }, testWorkspaceID, "test-daemon-profile-failure")++ testHandler.DaemonRegister(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("DaemonRegister: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE profile_id = $1`, profileID)+ })++ var status string+ var metadata []byte+ if err := testPool.QueryRow(ctx, `+ SELECT status, metadata FROM agent_runtime+ WHERE workspace_id = $1 AND daemon_id = $2 AND profile_id = $3+ `, testWorkspaceID, "test-daemon-profile-failure", profileID).Scan(&status, &metadata); err != nil {+ t.Fatalf("read failed profile runtime row: %v", err)+ }+ if status != "offline" {+ t.Fatalf("status = %q, want offline", status)+ }+ var meta map[string]any+ if err := json.Unmarshal(metadata, &meta); err != nil {+ t.Fatalf("unmarshal metadata: %v", err)+ }+ if meta["runtime_profile_registration_error"] != true {+ t.Fatalf("registration error metadata missing: %#v", meta)+ }+ if meta["runtime_profile_failure_reason"] != "command not found on PATH: missing-codex" {+ t.Fatalf("failure reason metadata = %#v", meta["runtime_profile_failure_reason"])+ }+}+func TestDaemonRegister_WithDaemonToken_WorkspaceMismatch(t *testing.T) {if testHandler == nil {t.Skip("database not available")diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.goindex a2e3e5c3c1..4335e6efde 100644--- a/server/internal/handler/runtime_profile.go+++ b/server/internal/handler/runtime_profile.go@@ -92,11 +92,27 @@ func marshalFixedArgs(args []string) ([]byte, error) {if strings.TrimSpace(a) == "" {return nil, errors.New("fixed_args entries must be non-empty")}+ if strings.ContainsRune(a, '\x00') {+ return nil, errors.New("fixed_args entries cannot contain NUL bytes")+ }clean = append(clean, a)}return json.Marshal(clean)}+func validateRuntimeProfileCommandName(commandName string) error {+ if commandName == "" {+ return errors.New("command_name is required")+ }+ if strings.ContainsAny(commandName, " \t\r\n") {+ return errors.New("command_name must be a single executable token; put arguments in fixed_args")+ }+ if strings.ContainsRune(commandName, '\x00') {+ return errors.New("command_name cannot contain NUL bytes")+ }+ return nil+}+type createRuntimeProfileRequest struct {DisplayName string `json:"display_name"`ProtocolFamily string `json:"protocol_family"`@@ -141,6 +157,10 @@ func (h *Handler) CreateRuntimeProfile(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "command_name is required")return}+ if err := validateRuntimeProfileCommandName(req.CommandName); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }fixedArgs, err := marshalFixedArgs(req.FixedArgs)if err != nil {writeError(w, http.StatusBadRequest, err.Error())@@ -274,8 +294,8 @@ func (h *Handler) UpdateRuntimeProfile(w http.ResponseWriter, r *http.Request) {}if req.CommandName != nil {cmd := strings.TrimSpace(*req.CommandName)- if cmd == "" {- writeError(w, http.StatusBadRequest, "command_name cannot be empty")+ if err := validateRuntimeProfileCommandName(cmd); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())return}params.CommandName = strToText(cmd)diff --git a/server/internal/handler/runtime_profile_handler_test.go b/server/internal/handler/runtime_profile_handler_test.goindex 77e7fb0777..b6850a0d99 100644--- a/server/internal/handler/runtime_profile_handler_test.go+++ b/server/internal/handler/runtime_profile_handler_test.go@@ -5,6 +5,7 @@ import ("encoding/json""net/http""net/http/httptest"+ "strings""testing")@@ -137,7 +138,6 @@ func TestDeleteRuntimeProfile_ActiveAgentBlocks(t *testing.T) {}}-// TestCreateRuntimeProfile_ForcesWorkspaceVisibility is the regression guard// for the visibility leak: visibility=private is not user-settable in v1// because the read paths don't enforce it. A client that POSTs@@ -183,3 +183,61 @@ func TestCreateRuntimeProfile_ForcesWorkspaceVisibility(t *testing.T) {t.Fatalf("stored visibility = %q, want workspace", dbVis)}}++func TestCreateRuntimeProfile_ValidatesCommandAndFixedArgs(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ cases := []struct {+ name string+ commandName string+ fixedArgs []string+ wantStatus int+ }{+ {+ name: "split command and args accepted",+ commandName: "agent",+ fixedArgs: []string{"--model", "composer-2.5"},+ wantStatus: http.StatusCreated,+ },+ {+ name: "command line rejected",+ commandName: "agent --model composer-2.5",+ wantStatus: http.StatusBadRequest,+ },+ {+ name: "nul arg rejected",+ commandName: "agent",+ fixedArgs: []string{"bad\x00arg"},+ wantStatus: http.StatusBadRequest,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles", map[string]any{+ "display_name": "Validation " + tc.name,+ "protocol_family": "codex",+ "command_name": tc.commandName,+ "fixed_args": tc.fixedArgs,+ })+ req = withURLParam(req, "id", testWorkspaceID)+ testHandler.CreateRuntimeProfile(w, req)+ if w.Code != tc.wantStatus {+ t.Fatalf("status = %d, want %d: %s", w.Code, tc.wantStatus, w.Body.String())+ }+ if w.Code == http.StatusCreated {+ var resp RuntimeProfileResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM runtime_profile WHERE id = $1`, resp.ID)+ })+ if got := strings.Join(resp.FixedArgs, " "); got != strings.Join(tc.fixedArgs, " ") {+ t.Fatalf("fixed_args = %v, want %v", resp.FixedArgs, tc.fixedArgs)+ }+ }+ })+ }+}