Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(runtimes): custom runtime names + searchable machine-grouped picker (MUL-4217) (#5070)
Bohan Jiangfd58e13bec52
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 76aaa1b422..2566187b90 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1152,7 +1152,17 @@ export class ApiClient {async updateRuntime(runtimeId: string,- patch: { visibility?: "private" | "public" },+ patch: {+ visibility?: "private" | "public";+ /**+ * Custom display name. Pass an empty string to clear it (the server+ * reverts to the default name). Omit to leave it unchanged — a JSON+ * `null` is treated as "unchanged", not "clear". See MUL-4217.+ */+ custom_name?: string;+ /** Apply custom_name to every runtime on the same machine. */+ apply_to_machine?: boolean;+ },): Promise<AgentRuntime> {return this.fetch(`/api/runtimes/${runtimeId}`, {method: "PATCH",diff --git a/packages/core/runtimes/display.test.ts b/packages/core/runtimes/display.test.tsnew file mode 100644index 0000000000..0492060824--- /dev/null+++ b/packages/core/runtimes/display.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { runtimeDisplayName } from "./display";++describe("runtimeDisplayName", () => {+ it("prefers a custom name when set", () => {+ expect(+ runtimeDisplayName({ name: "Claude (host)", custom_name: "Prod Box" }),+ ).toBe("Prod Box");+ });++ it("trims the custom name", () => {+ expect(+ runtimeDisplayName({ name: "Claude (host)", custom_name: " Prod Box " }),+ ).toBe("Prod Box");+ });++ it("falls back to the default name when custom is empty, whitespace, null, or missing", () => {+ expect(runtimeDisplayName({ name: "Claude (host)", custom_name: "" })).toBe(+ "Claude (host)",+ );+ expect(+ runtimeDisplayName({ name: "Claude (host)", custom_name: " " }),+ ).toBe("Claude (host)");+ expect(+ runtimeDisplayName({ name: "Claude (host)", custom_name: null }),+ ).toBe("Claude (host)");+ expect(runtimeDisplayName({ name: "Claude (host)" })).toBe("Claude (host)");+ });+});diff --git a/packages/core/runtimes/display.ts b/packages/core/runtimes/display.tsnew file mode 100644index 0000000000..903a125249--- /dev/null+++ b/packages/core/runtimes/display.ts@@ -0,0 +1,13 @@+import type { AgentRuntime } from "../types";++/**+ * The name to show for a runtime (MUL-4217): the user's custom override when+ * set, otherwise the daemon-proposed default. Defends against older backends+ * that omit custom_name and against whitespace-only overrides.+ */+export function runtimeDisplayName(+ runtime: Pick<AgentRuntime, "name" | "custom_name">,+): string {+ const custom = runtime.custom_name?.trim();+ return custom ? custom : runtime.name;+}diff --git a/packages/core/runtimes/index.ts b/packages/core/runtimes/index.tsindex a2da49c575..1287d6ac18 100644--- a/packages/core/runtimes/index.ts+++ b/packages/core/runtimes/index.ts@@ -6,6 +6,7 @@ export * from "./models";export * from "./local-skills";export * from "./types";export * from "./derive-health";+export * from "./display";export * from "./use-runtime-health";export * from "./cli-version";export * from "./custom-pricing-store";diff --git a/packages/core/runtimes/mutations.ts b/packages/core/runtimes/mutations.tsindex 2c41777c88..0711cab275 100644--- a/packages/core/runtimes/mutations.ts+++ b/packages/core/runtimes/mutations.ts@@ -42,8 +42,9 @@ export function useArchiveAgentsAndDeleteRuntime(wsId: string) {});}-// useUpdateRuntime patches editable fields on a runtime (visibility).-// Invalidates the runtime list so the picker disabled-state recomputes.+// useUpdateRuntime patches editable fields on a runtime (visibility, custom+// name). Invalidates the runtime list so the picker disabled-state and+// display names recompute.export function useUpdateRuntime(wsId: string) {const qc = useQueryClient();return useMutation({@@ -52,7 +53,12 @@ export function useUpdateRuntime(wsId: string) {patch,}: {runtimeId: string;- patch: { visibility?: "private" | "public" };+ patch: {+ visibility?: "private" | "public";+ // Empty string clears the custom name; omit to leave unchanged.+ custom_name?: string;+ apply_to_machine?: boolean;+ };}) => api.updateRuntime(runtimeId, patch),onSettled: () => {qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex f749924958..7dde88a439 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -58,6 +58,13 @@ export interface RuntimeDevice {workspace_id: string;daemon_id: string | null;name: string;+ /**+ * Optional user-set display name override (MUL-4217). Overrides `name` for+ * display; the daemon never writes it, so it survives heartbeats. Older+ * backends omit the field — consumers must treat missing / empty as "use+ * name" (see runtimeDisplayName).+ */+ custom_name?: string | null;runtime_mode: AgentRuntimeMode;provider: string;launch_header: string;diff --git a/packages/views/agents/components/inspector/runtime-picker.tsx b/packages/views/agents/components/inspector/runtime-picker.tsxindex c517828f3c..a3c6a612ff 100644--- a/packages/views/agents/components/inspector/runtime-picker.tsx+++ b/packages/views/agents/components/inspector/runtime-picker.tsx@@ -3,6 +3,7 @@import { useMemo, useState } from "react";import { Cloud, Lock, Monitor } from "lucide-react";import type { AgentRuntime, MemberWithUser } from "@multica/core/types";+import { runtimeDisplayName } from "@multica/core/runtimes";import { ActorAvatar } from "../../../common/actor-avatar";import {PickerItem,@@ -75,7 +76,7 @@ export function RuntimePicker({<span className="inline-flex min-w-0 items-center gap-1.5 px-1.5 py-0.5 text-xs text-muted-foreground"><Icon className="h-3 w-3 shrink-0" /><span className="min-w-0 truncate font-mono">- {selected?.name ?? t(($) => $.pickers.runtime_none)}+ {selected ? runtimeDisplayName(selected) : t(($) => $.pickers.runtime_none)}</span>{selected && (<span@@ -92,11 +93,13 @@ export function RuntimePicker({// deliberately do NOT append `device_info` to the tooltip — that string// also leads with the host and would just repeat what's already in name,// producing the "Claude (host) (host · 2.1.121 (Claude Code))" mess.- const triggerLabel = selected?.name ?? t(($) => $.pickers.runtime_none);+ const triggerLabel = selected+ ? runtimeDisplayName(selected)+ : t(($) => $.pickers.runtime_none);const isOnline = selected?.status === "online";const triggerTitle = selected? t(($) => $.pickers.runtime_tooltip, {- name: selected.name,+ name: runtimeDisplayName(selected),status: isOnline ? t(($) => $.pickers.runtime_online) : t(($) => $.pickers.runtime_offline),}): t(($) => $.pickers.runtime_tooltip_none);@@ -169,7 +172,7 @@ export function RuntimePicker({const rtOnline = rt.status === "online";const locked = isDisabled(rt);const tooltip = [- rt.name,+ runtimeDisplayName(rt),owner ? t(($) => $.pickers.runtime_owned_by, { name: owner.name }) : null,rtOnline ? t(($) => $.pickers.runtime_online) : t(($) => $.pickers.runtime_offline),locked ? t(($) => $.create_dialog.runtime_private_locked_tooltip) : null,@@ -194,7 +197,7 @@ export function RuntimePicker({<div className="min-w-0 flex-1"><div className="flex items-center gap-1.5"><span className="truncate text-sm font-medium">- {rt.name}+ {runtimeDisplayName(rt)}</span>{rt.runtime_mode === "cloud" && (<span className="shrink-0 rounded bg-info/10 px-1 text-[10px] font-medium text-info">diff --git a/packages/views/agents/components/runtime-picker.tsx b/packages/views/agents/components/runtime-picker.tsxindex 2b5da71dbd..0bba620768 100644--- a/packages/views/agents/components/runtime-picker.tsx+++ b/packages/views/agents/components/runtime-picker.tsx@@ -1,9 +1,10 @@"use client";import { useEffect, useMemo, useState } from "react";-import { ChevronDown, Cloud, Loader2, Lock } from "lucide-react";+import { ChevronDown, Cloud, Loader2, Lock, Search } from "lucide-react";import { ProviderLogo } from "../../runtimes/components/provider-logo";import { ActorAvatar } from "../../common/actor-avatar";+import { runtimeDisplayName } from "@multica/core/runtimes";import type { MemberWithUser, RuntimeDevice } from "@multica/core/types";import {Popover,@@ -12,9 +13,19 @@ import {} from "@multica/ui/components/ui/popover";import { Label } from "@multica/ui/components/ui/label";import { useT } from "../../i18n";+import {+ buildRuntimeMachines,+ filterRuntimeMachines,+ splitRuntimeName,+} from "../../runtimes/components/runtime-machines";export type RuntimeFilter = "mine" | "all";+// Above this many runtimes the flat list becomes hard to scan, so we surface+// a search box. Machine grouping kicks in independently whenever more than one+// machine is present.+const SEARCH_THRESHOLD = 6;+export function RuntimePicker({runtimes,runtimesLoading,@@ -33,6 +44,7 @@ export function RuntimePicker({const { t } = useT("agents");const [open, setOpen] = useState(false);const [filter, setFilter] = useState<RuntimeFilter>("mine");+ const [search, setSearch] = useState("");const getOwnerMember = (ownerId: string | null) => {if (!ownerId) return null;@@ -41,11 +53,27 @@ export function RuntimePicker({const hasOtherRuntimes = runtimes.some((r) => r.owner_id !== currentUserId);+ // Base list honours the mine/all toggle and drives auto-selection; it is+ // intentionally independent of the search box so typing never changes the+ // seeded selection.const filteredRuntimes = useMemo(() => computeFilteredRuntimes(runtimes, filter, currentUserId),[runtimes, filter, currentUserId],);+ // Group the (searched) base list by machine so 20+ runtimes read as a+ // handful of named machines, online-first, current machine first.+ const machines = useMemo(() => {+ const all = buildRuntimeMachines(filteredRuntimes, {+ now: Date.now(),+ currentUserId,+ });+ return filterRuntimeMachines(all, search, "all");+ }, [filteredRuntimes, search, currentUserId]);++ const showSearch = runtimes.length > SEARCH_THRESHOLD;+ const showGroupHeaders = machines.length > 1;+const selectedRuntime =runtimes.find((d) => d.id === selectedRuntimeId) ?? null;@@ -108,7 +136,13 @@ export function RuntimePicker({</div>)}</div>- <Popover open={open} onOpenChange={setOpen}>+ <Popover+ open={open}+ onOpenChange={(next) => {+ setOpen(next);+ if (!next) setSearch("");+ }}+ ><PopoverTriggerdisabled={runtimes.length === 0 && !runtimesLoading}className="flex w-full min-w-0 items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 mt-1.5 text-left text-sm transition-colors hover:bg-muted disabled:pointer-events-none disabled:opacity-50"@@ -128,8 +162,9 @@ export function RuntimePicker({<span className="truncate font-medium">{runtimesLoading? t(($) => $.create_dialog.runtime_loading)- : (selectedRuntime?.name ??- t(($) => $.create_dialog.runtime_none))}+ : selectedRuntime+ ? runtimeDisplayName(selectedRuntime)+ : t(($) => $.create_dialog.runtime_none)}</span>{selectedRuntime?.runtime_mode === "cloud" && (<span className="shrink-0 rounded bg-info/10 px-1.5 py-0.5 text-xs font-medium text-info">@@ -152,83 +187,139 @@ export function RuntimePicker({</PopoverTrigger><PopoverContentalign="start"- className="w-[var(--anchor-width)] p-1 max-h-60 overflow-y-auto"+ className="w-[var(--anchor-width)] p-1 flex flex-col max-h-72">- {filteredRuntimes.map((device) => {- const ownerMember = getOwnerMember(device.owner_id);- const disabled = !isRuntimeUsableForUser(device, currentUserId);- const disabledTitle = disabled- ? t(($) => $.create_dialog.runtime_private_locked_tooltip)- : undefined;- return (- <button- key={device.id}- type="button"- disabled={disabled}- title={disabledTitle}- onClick={() => {- if (disabled) return;- onSelect(device.id);- setOpen(false);- }}- className={`flex w-full items-center gap-3 rounded-md px-3 py-2.5 text-left text-sm transition-colors ${- disabled- ? "cursor-not-allowed opacity-50"- : device.id === selectedRuntimeId- ? "bg-accent"- : "hover:bg-accent/50"- }`}- >- <ProviderLogo- provider={device.provider}- className="h-4 w-4 shrink-0"- />- <div className="min-w-0 flex-1">- <div className="flex items-center gap-2">- <span className="truncate font-medium">{device.name}</span>- {device.runtime_mode === "cloud" && (- <span className="shrink-0 rounded bg-info/10 px-1.5 py-0.5 text-xs font-medium text-info">- {t(($) => $.create_dialog.runtime_cloud_badge)}- </span>- )}- {disabled && (- <span className="shrink-0 inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">- <Lock className="h-3 w-3" />- {t(($) => $.create_dialog.runtime_private_badge)}+ {showSearch && (+ <div className="relative mb-1 shrink-0">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />+ <input+ type="text"+ autoFocus+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder={t(($) => $.create_dialog.runtime_search_placeholder)}+ className="w-full rounded-md border border-border bg-background py-1.5 pl-8 pr-2 text-sm outline-none focus:ring-1 focus:ring-ring"+ />+ </div>+ )}+ <div className="min-h-0 flex-1 overflow-y-auto">+ {machines.length === 0 ? (+ <div className="px-3 py-6 text-center text-xs text-muted-foreground">+ {t(($) => $.create_dialog.runtime_no_results)}+ </div>+ ) : (+ machines.map((machine) => (+ <div key={machine.id}>+ {showGroupHeaders && (+ <div className="flex items-center justify-between gap-2 px-2 pb-0.5 pt-2 text-[11px] font-medium text-muted-foreground">+ <span className="truncate">{machine.title}</span>+ <span className="shrink-0 tabular-nums">+ {t(($) => $.create_dialog.runtime_group_online, {+ online: machine.onlineCount,+ total: machine.runtimes.length,+ })}</span>- )}- </div>- <div className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">- {ownerMember ? (- <>- <ActorAvatar- actorType="member"- actorId={ownerMember.user_id}- size={14}+ </div>+ )}+ {machine.runtimes.map((device) => {+ const ownerMember = getOwnerMember(device.owner_id);+ const disabled = !isRuntimeUsableForUser(+ device,+ currentUserId,+ );+ const disabledTitle = disabled+ ? t(($) => $.create_dialog.runtime_private_locked_tooltip)+ : undefined;+ return (+ <button+ key={device.id}+ type="button"+ disabled={disabled}+ title={disabledTitle}+ onClick={() => {+ if (disabled) return;+ onSelect(device.id);+ setOpen(false);+ }}+ className={`flex w-full items-center gap-3 rounded-md px-3 py-2.5 text-left text-sm transition-colors ${+ disabled+ ? "cursor-not-allowed opacity-50"+ : device.id === selectedRuntimeId+ ? "bg-accent"+ : "hover:bg-accent/50"+ }`}+ >+ <ProviderLogo+ provider={device.provider}+ className="h-4 w-4 shrink-0"+ />+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="truncate font-medium">+ {runtimeRowLabel(device, machine.title)}+ </span>+ {device.runtime_mode === "cloud" && (+ <span className="shrink-0 rounded bg-info/10 px-1.5 py-0.5 text-xs font-medium text-info">+ {t(($) => $.create_dialog.runtime_cloud_badge)}+ </span>+ )}+ {disabled && (+ <span className="shrink-0 inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">+ <Lock className="h-3 w-3" />+ {t(($) => $.create_dialog.runtime_private_badge)}+ </span>+ )}+ </div>+ <div className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">+ {ownerMember ? (+ <>+ <ActorAvatar+ actorType="member"+ actorId={ownerMember.user_id}+ size={14}+ />+ <span className="truncate">+ {ownerMember.name}+ </span>+ </>+ ) : (+ <span className="truncate">+ {device.device_info}+ </span>+ )}+ </div>+ </div>+ <span+ className={`h-2 w-2 shrink-0 rounded-full ${+ device.status === "online"+ ? "bg-success"+ : "bg-muted-foreground/40"+ }`}/>- <span className="truncate">{ownerMember.name}</span>- </>- ) : (- <span className="truncate">{device.device_info}</span>- )}- </div>+ </button>+ );+ })}</div>- <span- className={`h-2 w-2 shrink-0 rounded-full ${- device.status === "online"- ? "bg-success"- : "bg-muted-foreground/40"- }`}- />- </button>- );- })}+ ))+ )}+ </div></PopoverContent></Popover></div>);}+// The per-row label inside a machine group. When the machine already carries a+// name (its own custom name or device name in the header), repeating it on+// every row is noise — so a row shows its provider base (e.g. "Claude"). An+// individual per-runtime rename that differs from the machine name is shown+// verbatim so it stays visible.+function runtimeRowLabel(runtime: RuntimeDevice, machineTitle: string): string {+ const custom = runtime.custom_name?.trim();+ if (custom && custom !== machineTitle) return custom;+ return splitRuntimeName(runtime.name).base;+}+// Visibility gate exposed so the parent can defend Create against a locked// selection (e.g. duplicate of an agent whose runtime is now private).export function isRuntimeUsableForUser(diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex c9df85798e..0173b03b35 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -255,6 +255,9 @@"runtime_cloud_badge": "Cloud","runtime_private_badge": "Private","runtime_private_locked_tooltip": "Private runtime — only its owner or a workspace admin can create agents on it. Ask the owner to switch it to Public to share.",+ "runtime_search_placeholder": "Search runtimes…",+ "runtime_no_results": "No matching runtimes",+ "runtime_group_online": "{{online}}/{{total}} online","duplicate_copy_suffix": " (Copy)","create": "Create","creating": "Creating...",diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.jsonindex e1fd1247c0..d60965bd48 100644--- a/packages/views/locales/en/runtimes.json+++ b/packages/views/locales/en/runtimes.json@@ -86,6 +86,7 @@"all_runtimes": "All runtimes","read_only": "Read-only","delete_button": "Delete runtime",+ "rename_button": "Rename","last_seen": "last seen {{when}}","fact_owner": "Owner","fact_device": "Device",@@ -110,6 +111,18 @@},"visibility_toast_updated": "Visibility set to {{visibility}}","visibility_toast_failed": "Failed to update visibility",+ "rename_dialog": {+ "title": "Rename runtime",+ "description": "Give this runtime a custom name so it's easier to find when creating agents.",+ "hint": "Leave empty to use the default name.",+ "apply_to_machine": "Apply to every runtime on this machine",+ "cancel": "Cancel",+ "save": "Save",+ "saving": "Saving...",+ "toast_saved": "Runtime renamed",+ "toast_cleared": "Custom name cleared",+ "toast_failed": "Failed to rename runtime"+ },"delete_dialog": {"self_heal_notice": "This runtime is managed by a running local daemon. Deleting it will succeed, but the daemon will re-register a fresh runtime within seconds — stop the daemon process first to remove it permanently.","profile_backed_notice": "This runtime was registered from a custom runtime profile. Deleting it removes only the current runtime instance; a running daemon can register it again while the profile remains. Delete the custom runtime profile from Custom runtimes to remove it permanently.",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 097be48bdc..0ae45dde7c 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -239,6 +239,9 @@"runtime_cloud_badge": "クラウド","runtime_private_badge": "非公開","runtime_private_locked_tooltip": "非公開ランタイムです。オーナーまたはワークスペースの admin のみがこのランタイム上にエージェントを作成できます。共有するには、オーナーに公開へ切り替えるよう依頼してください。",+ "runtime_search_placeholder": "ランタイムを検索…",+ "runtime_no_results": "一致するランタイムがありません",+ "runtime_group_online": "{{online}}/{{total}} オンライン","duplicate_copy_suffix": " (コピー)","create": "作成","creating": "作成中...",diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.jsonindex 90043fcab8..993fb408e1 100644--- a/packages/views/locales/ja/runtimes.json+++ b/packages/views/locales/ja/runtimes.json@@ -82,6 +82,7 @@"all_runtimes": "すべてのランタイム","read_only": "読み取り専用","delete_button": "ランタイムを削除",+ "rename_button": "名前を変更","last_seen": "最終確認 {{when}}","fact_owner": "所有者","fact_device": "デバイス",@@ -105,6 +106,18 @@},"visibility_toast_updated": "公開範囲を {{visibility}} に設定しました","visibility_toast_failed": "公開範囲を更新できませんでした",+ "rename_dialog": {+ "title": "ランタイムの名前を変更",+ "description": "エージェント作成時に見つけやすいよう、このランタイムにカスタム名を付けます。",+ "hint": "空欄にするとデフォルト名を使用します。",+ "apply_to_machine": "このマシン上のすべてのランタイムに適用",+ "cancel": "キャンセル",+ "save": "保存",+ "saving": "保存中...",+ "toast_saved": "ランタイムの名前を変更しました",+ "toast_cleared": "カスタム名をクリアしました",+ "toast_failed": "ランタイムの名前変更に失敗しました"+ },"delete_dialog": {"self_heal_notice": "このランタイムは実行中のローカルデーモンに管理されています。削除自体は成功しますが、デーモンプロセスを停止しない限り、数秒以内に新しいランタイムとして再登録されます。完全に削除するには先にデーモンを停止してください。","profile_backed_notice": "このランタイムはカスタムランタイムプロファイルから登録されています。ここで削除しても現在のランタイムインスタンスだけが削除され、プロファイルが残っている間は実行中のデーモンが再登録できます。完全に削除するには、Custom runtimes からカスタムランタイムプロファイルを削除してください。",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex 3fe206f177..dc23e36b04 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -247,6 +247,9 @@"runtime_cloud_badge": "클라우드","runtime_private_badge": "비공개","runtime_private_locked_tooltip": "비공개 런타임입니다. 소유자 또는 워크스페이스 관리자만 이 런타임에 에이전트를 만들 수 있습니다. 공유하려면 소유자에게 공개로 전환해 달라고 요청하세요.",+ "runtime_search_placeholder": "런타임 검색…",+ "runtime_no_results": "일치하는 런타임이 없습니다",+ "runtime_group_online": "{{online}}/{{total}} 온라인","duplicate_copy_suffix": " (사본)","create": "만들기","creating": "만드는 중...",diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.jsonindex 1f5f5954fb..88b0f46c96 100644--- a/packages/views/locales/ko/runtimes.json+++ b/packages/views/locales/ko/runtimes.json@@ -82,6 +82,7 @@"all_runtimes": "모든 런타임","read_only": "읽기 전용","delete_button": "런타임 삭제",+ "rename_button": "이름 변경","last_seen": "마지막 확인 {{when}}","fact_owner": "소유자","fact_device": "기기",@@ -105,6 +106,18 @@},"visibility_toast_updated": "공개 범위를 {{visibility}}(으)로 설정했습니다","visibility_toast_failed": "공개 범위를 업데이트하지 못했습니다",+ "rename_dialog": {+ "title": "런타임 이름 변경",+ "description": "에이전트를 만들 때 쉽게 찾을 수 있도록 이 런타임에 사용자 지정 이름을 지정합니다.",+ "hint": "비워 두면 기본 이름을 사용합니다.",+ "apply_to_machine": "이 컴퓨터의 모든 런타임에 적용",+ "cancel": "취소",+ "save": "저장",+ "saving": "저장 중...",+ "toast_saved": "런타임 이름을 변경했습니다",+ "toast_cleared": "사용자 지정 이름을 지웠습니다",+ "toast_failed": "런타임 이름 변경에 실패했습니다"+ },"delete_dialog": {"self_heal_notice": "이 런타임은 실행 중인 로컬 데몬이 관리합니다. 삭제는 성공하지만, 데몬 프로세스를 멈추지 않으면 몇 초 안에 새 런타임이 다시 등록됩니다. 완전히 제거하려면 먼저 데몬을 중지하세요.","profile_backed_notice": "이 런타임은 사용자 지정 런타임 프로필에서 등록되었습니다. 여기서 삭제하면 현재 런타임 인스턴스만 제거되며, 프로필이 남아 있는 동안 실행 중인 데몬이 다시 등록할 수 있습니다. 완전히 제거하려면 Custom runtimes에서 사용자 지정 런타임 프로필을 삭제하세요.",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex 603ba4699a..55434da251 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -247,6 +247,9 @@"runtime_cloud_badge": "云端","runtime_private_badge": "私有","runtime_private_locked_tooltip": "私有运行时——只有 runtime 所有者或工作区管理员可在其上创建智能体。如果需要共享,请联系所有者切换为「公开」。",+ "runtime_search_placeholder": "搜索运行时…",+ "runtime_no_results": "没有匹配的运行时",+ "runtime_group_online": "{{online}}/{{total}} 在线","duplicate_copy_suffix": "(副本)","create": "创建","creating": "创建中...",diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.jsonindex 465884a060..cb261b9252 100644--- a/packages/views/locales/zh-Hans/runtimes.json+++ b/packages/views/locales/zh-Hans/runtimes.json@@ -82,6 +82,7 @@"all_runtimes": "全部运行时","read_only": "只读","delete_button": "删除运行时",+ "rename_button": "重命名","last_seen": "最后活跃 {{when}}","fact_owner": "所有者","fact_device": "设备",@@ -105,6 +106,18 @@},"visibility_toast_updated": "可见性已设为「{{visibility}}」","visibility_toast_failed": "更新可见性失败",+ "rename_dialog": {+ "title": "重命名运行时",+ "description": "为该运行时设置一个自定义名称,方便在创建 agent 时查找。",+ "hint": "留空则使用默认名称。",+ "apply_to_machine": "应用到这台机器上的所有运行时",+ "cancel": "取消",+ "save": "保存",+ "saving": "保存中...",+ "toast_saved": "已重命名运行时",+ "toast_cleared": "已清除自定义名称",+ "toast_failed": "重命名运行时失败"+ },"delete_dialog": {"self_heal_notice": "该运行时由正在运行的本地守护进程托管。删除会成功,但守护进程会在数秒内重新注册一个新的运行时——若想彻底移除,请先停止守护进程。","profile_backed_notice": "该运行时来自自定义运行时配置。删除它只会移除当前运行时实例;只要配置仍存在,运行中的守护进程就可以再次注册它。若要彻底移除,请在“自定义运行时”中删除对应配置。",diff --git a/packages/views/runtimes/components/rename-runtime-dialog.tsx b/packages/views/runtimes/components/rename-runtime-dialog.tsxnew file mode 100644index 0000000000..692284e24f--- /dev/null+++ b/packages/views/runtimes/components/rename-runtime-dialog.tsx@@ -0,0 +1,166 @@+"use client";++import { useEffect, useState } from "react";+import { toast } from "sonner";+import type { AgentRuntime } from "@multica/core/types";+import { useUpdateRuntime } from "@multica/core/runtimes/mutations";+import {+ AlertDialog,+ AlertDialogContent,+} from "@multica/ui/components/ui/alert-dialog";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import { useT } from "../../i18n";++// RenameRuntimeDialog lets a runtime owner (or workspace admin) set a custom+// display name (MUL-4217). The name overrides the daemon-proposed default for+// display everywhere; clearing it reverts to the default. When the runtime is+// a local/remote daemon (has a daemon_id), it can host one runtime per+// provider, so the dialog offers to apply the name to the whole machine — the+// common intent behind "name my machine".+export interface RenameRuntimeDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ runtime: AgentRuntime;+ wsId: string;+}++export function RenameRuntimeDialog({+ open,+ onOpenChange,+ runtime,+ wsId,+}: RenameRuntimeDialogProps) {+ const { t } = useT("runtimes");+ const updateRuntime = useUpdateRuntime(wsId);++ // Machine-level naming only makes sense for daemon-backed runtimes; cloud+ // workers have no shared host to fan out across.+ const canApplyToMachine =+ !!runtime.daemon_id && runtime.runtime_mode !== "cloud";++ const [value, setValue] = useState(runtime.custom_name ?? "");+ const [applyToMachine, setApplyToMachine] = useState(canApplyToMachine);+ const submitting = updateRuntime.isPending;++ // Reset the form each time the dialog opens so a cancelled edit doesn't+ // leak into the next one.+ useEffect(() => {+ if (open) {+ setValue(runtime.custom_name ?? "");+ setApplyToMachine(canApplyToMachine);+ }+ }, [open, runtime.custom_name, canApplyToMachine]);++ const handleOpenChange = (next: boolean) => {+ if (submitting) return;+ onOpenChange(next);+ };++ const handleSave = () => {+ const trimmed = value.trim();+ updateRuntime.mutate(+ {+ runtimeId: runtime.id,+ // Empty string clears the override server-side.+ patch: {+ custom_name: trimmed,+ ...(canApplyToMachine && applyToMachine+ ? { apply_to_machine: true }+ : {}),+ },+ },+ {+ onSuccess: () => {+ toast.success(+ trimmed+ ? t(($) => $.detail.rename_dialog.toast_saved)+ : t(($) => $.detail.rename_dialog.toast_cleared),+ );+ onOpenChange(false);+ },+ onError: (err) =>+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.detail.rename_dialog.toast_failed),+ ),+ },+ );+ };++ return (+ <AlertDialog open={open} onOpenChange={handleOpenChange}>+ <AlertDialogContent+ className="w-[calc(100vw-2rem)] !max-w-[440px] gap-0 overflow-hidden rounded-lg p-0"+ onClick={(e) => e.stopPropagation()}+ >+ <div className="px-5 pb-4 pt-5">+ <h2 className="text-base font-semibold">+ {t(($) => $.detail.rename_dialog.title)}+ </h2>+ <p className="mt-1 text-sm leading-5 text-muted-foreground">+ {t(($) => $.detail.rename_dialog.description)}+ </p>++ <Input+ className="mt-3"+ autoFocus+ value={value}+ maxLength={100}+ placeholder={runtime.name}+ onChange={(e) => setValue(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !submitting) {+ e.preventDefault();+ handleSave();+ }+ }}+ />+ <p className="mt-1.5 text-xs text-muted-foreground">+ {t(($) => $.detail.rename_dialog.hint)}+ </p>++ {canApplyToMachine && (+ <label className="mt-3 flex cursor-pointer items-start gap-2 text-sm text-foreground">+ <Checkbox+ className="mt-0.5"+ checked={applyToMachine}+ onCheckedChange={(next) => setApplyToMachine(next === true)}+ disabled={submitting}+ />+ <span className="leading-5">+ {t(($) => $.detail.rename_dialog.apply_to_machine)}+ </span>+ </label>+ )}+ </div>++ <div className="border-t bg-muted/25 px-5 py-3">+ <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">+ <Button+ type="button"+ variant="outline"+ className="w-full sm:w-auto"+ onClick={() => handleOpenChange(false)}+ disabled={submitting}+ >+ {t(($) => $.detail.rename_dialog.cancel)}+ </Button>+ <Button+ type="button"+ className="w-full sm:w-auto"+ onClick={handleSave}+ disabled={submitting}+ >+ {submitting+ ? t(($) => $.detail.rename_dialog.saving)+ : t(($) => $.detail.rename_dialog.save)}+ </Button>+ </div>+ </div>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx b/packages/views/runtimes/components/runtime-detail-visibility.test.tsxindex 48fcdcdaad..d38b201ff8 100644--- a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx+++ b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx@@ -75,6 +75,8 @@ vi.mock("@multica/core/auth", () => ({vi.mock("@multica/core/runtimes", () => ({deriveRuntimeHealth: () => "online",+ runtimeDisplayName: (rt: { name: string; custom_name?: string | null }) =>+ rt.custom_name?.trim() || rt.name,runtimeProfileListOptions: (wsId: string) => ({queryKey: ["runtime-profiles", wsId],}),diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsxindex 2bd2a6aa39..098e6542ba 100644--- a/packages/views/runtimes/components/runtime-detail.tsx+++ b/packages/views/runtimes/components/runtime-detail.tsx@@ -7,6 +7,7 @@ import {Cpu,Globe,Lock,+ Pencil,} from "lucide-react";import { toast } from "sonner";import { useQuery } from "@tanstack/react-query";@@ -22,6 +23,7 @@ import { memberListOptions, agentListOptions } from "@multica/core/workspace/queimport { useUpdateRuntime } from "@multica/core/runtimes/mutations";import {deriveRuntimeHealth,+ runtimeDisplayName,runtimeProfileListOptions,} from "@multica/core/runtimes";import {@@ -46,6 +48,7 @@ import { UpdateSection } from "./update-section";import { UsageSection } from "./usage-section";import { DeleteRuntimeDialog } from "./delete-runtime-dialog";import { DeleteRuntimeProfileDialog } from "./delete-runtime-profile-dialog";+import { RenameRuntimeDialog } from "./rename-runtime-dialog";import { useT } from "../../i18n";function getCliVersion(metadata: Record<string, unknown>): string | null {@@ -108,6 +111,7 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {const now = useNowTick();const [deleteOpen, setDeleteOpen] = useState(false);+ const [renameOpen, setRenameOpen] = useState(false);const health = deriveRuntimeHealth(runtime, now);const ownerMember = runtime.owner_id@@ -157,7 +161,7 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {segments={[{ href: paths.runtimes(), label: t(($) => $.page.title) }]}leaf={<span className="truncate font-mono text-xs text-foreground">- {runtime.name}+ {runtimeDisplayName(runtime)}</span>}actions={@@ -185,6 +189,8 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {ownerMember={ownerMember}cliVersion={cliVersion}daemonShort={daemonShort}+ canEdit={!!canEditRuntime}+ onRename={() => setRenameOpen(true)}/><UsageSection runtime={runtime} /></div>@@ -225,6 +231,15 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {onDeleted={handleRuntimeDeleted}/>)}++ {canEditRuntime && (+ <RenameRuntimeDialog+ open={renameOpen}+ onOpenChange={setRenameOpen}+ runtime={runtime}+ wsId={wsId}+ />+ )}</div>);}@@ -250,6 +265,8 @@ function HeroCard({ownerMember,cliVersion,daemonShort,+ canEdit,+ onRename,}: {runtime: AgentRuntime;health: ReturnType<typeof deriveRuntimeHealth>;@@ -257,6 +274,8 @@ function HeroCard({ownerMember: MemberWithUser | null;cliVersion: string | null;daemonShort: string | null;+ canEdit: boolean;+ onRename: () => void;}) {const { t } = useT("runtimes");const [showDetails, setShowDetails] = useState(false);@@ -273,8 +292,27 @@ function HeroCard({<div className="min-w-0 flex-1"><div className="flex flex-wrap items-center gap-x-3 gap-y-1"><h2 className="truncate text-base font-semibold tracking-tight">- {runtime.name}+ {runtimeDisplayName(runtime)}</h2>+ {canEdit && (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ onClick={onRename}+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ aria-label={t(($) => $.detail.rename_button)}+ >+ <Pencil className="h-3.5 w-3.5" />+ </button>+ }+ />+ <TooltipContent>+ {t(($) => $.detail.rename_button)}+ </TooltipContent>+ </Tooltip>+ )}<HealthBadge health={health} /><span className="text-xs text-muted-foreground">{t(($) => $.detail.last_seen, { when: lastSeen })}diff --git a/packages/views/runtimes/components/runtime-machines.test.ts b/packages/views/runtimes/components/runtime-machines.test.tsindex 027a4446af..0218822222 100644--- a/packages/views/runtimes/components/runtime-machines.test.ts+++ b/packages/views/runtimes/components/runtime-machines.test.ts@@ -52,6 +52,33 @@ describe("runtime machine grouping", () => {});});+ it("uses a machine-wide custom name as the machine title, over the local name", () => {+ const machines = buildRuntimeMachines(+ [+ makeRuntime({ id: "rt-claude", provider: "claude", custom_name: "Bohan's MacBook" }),+ makeRuntime({ id: "rt-codex", provider: "codex", custom_name: "Bohan's MacBook" }),+ ],+ { now: NOW, localDaemonId: "daemon-1", localMachineName: "dev-machine.local" },+ );++ expect(machines).toHaveLength(1);+ expect(machines[0]?.title).toBe("Bohan's MacBook");+ });++ it("ignores a one-off per-runtime custom name for the machine title", () => {+ const machines = buildRuntimeMachines(+ [+ makeRuntime({ id: "rt-claude", provider: "claude", custom_name: "just this one" }),+ makeRuntime({ id: "rt-codex", provider: "codex" }),+ ],+ { now: NOW, localDaemonId: "daemon-1" },+ );++ // Not shared across all runtimes on the machine, so it must not stand in+ // for the whole machine's name — the device name wins instead.+ expect(machines[0]?.title).toBe("dev-machine.local");+ });+it("counts machines with any offline runtime as issues", () => {const machines = buildRuntimeMachines([diff --git a/packages/views/runtimes/components/runtime-machines.ts b/packages/views/runtimes/components/runtime-machines.tsindex ae00d0dcd2..dcc1cc2463 100644--- a/packages/views/runtimes/components/runtime-machines.ts+++ b/packages/views/runtimes/components/runtime-machines.ts@@ -151,6 +151,7 @@ export function filterRuntimeMachines(machine.daemonId,machine.providerNames.join(" "),machine.runtimes.map((runtime) => runtime.name).join(" "),+ machine.runtimes.map((runtime) => runtime.custom_name ?? "").join(" "),].filter(Boolean).join(" ")@@ -268,10 +269,28 @@ function runtimeDeviceName(runtime: AgentRuntime): string | null {return raw.split(" · ")[0]?.trim() || null;}+// The custom name shared by every runtime on a machine (MUL-4217). A+// machine-level rename writes the same custom_name to all runtimes on the+// daemon, so a name shared by all of them is the machine's label. A one-off+// per-runtime rename (not shared) is deliberately ignored here so it can't+// masquerade as the whole machine's name.+function sharedCustomName(runtimes: AgentRuntime[]): string | null {+ if (runtimes.length === 0) return null;+ const names = runtimes.map((r) => r.custom_name?.trim() ?? "");+ const first = names[0];+ if (!first) return null;+ return names.every((n) => n === first) ? first : null;+}+function machineTitle(runtimes: AgentRuntime[],options: { isCurrent: boolean; localMachineName?: string | null },): string {+ // An explicit user-set machine name wins over everything, including the+ // OS-reported local machine name.+ const shared = sharedCustomName(runtimes);+ if (shared) return shared;+if (options.isCurrent && options.localMachineName) {return options.localMachineName;}diff --git a/server/cmd/multica/cmd_runtime.go b/server/cmd/multica/cmd_runtime.goindex ecd7e4b377..5bc0f127c9 100644--- a/server/cmd/multica/cmd_runtime.go+++ b/server/cmd/multica/cmd_runtime.go@@ -47,6 +47,16 @@ var runtimeUpdateCmd = &cobra.Command{RunE: runRuntimeUpdate,}+var runtimeRenameCmd = &cobra.Command{+ Use: "rename <runtime-id> <name>",+ Short: "Set a custom display name for a runtime",+ Long: "Set (or clear) a runtime's custom display name.\n\n" ++ "Pass an empty name (\"\") to clear the custom name and fall back to the default. " ++ "Use --machine to apply the name to every runtime on the same machine.",+ Args: exactArgs(2),+ RunE: runRuntimeRename,+}+var runtimeDeleteCmd = &cobra.Command{Use: "delete <runtime-id>",Short: "Delete a runtime from the workspace",@@ -62,6 +72,7 @@ func init() {runtimeCmd.AddCommand(runtimeUsageCmd)runtimeCmd.AddCommand(runtimeActivityCmd)runtimeCmd.AddCommand(runtimeUpdateCmd)+ runtimeCmd.AddCommand(runtimeRenameCmd)runtimeCmd.AddCommand(runtimeDeleteCmd)// runtime list@@ -79,6 +90,10 @@ func init() {runtimeUpdateCmd.Flags().String("output", "json", "Output format: table or json")runtimeUpdateCmd.Flags().Bool("wait", false, "Wait for update to complete (poll until done)")+ // runtime rename+ runtimeRenameCmd.Flags().Bool("machine", false, "Apply the name to every runtime on the same machine")+ runtimeRenameCmd.Flags().String("output", "table", "Output format: table or json")+// runtime deleteruntimeDeleteCmd.Flags().Bool("cascade", false, "Archive active agents bound to the runtime, cancel their tasks, then delete the runtime")runtimeDeleteCmd.Flags().String("output", "table", "Output format: table or json")@@ -239,6 +254,39 @@ func runRuntimeDelete(cmd *cobra.Command, args []string) error {return printRuntimeDeleteResult(cmd, result)}+func runRuntimeRename(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ machine, _ := cmd.Flags().GetBool("machine")+ body := map[string]any{"custom_name": args[1]}+ if machine {+ body["apply_to_machine"] = true+ }++ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var rt map[string]any+ if err := client.PatchJSON(ctx, "/api/runtimes/"+args[0], body, &rt); err != nil {+ return fmt.Errorf("rename runtime: %w", err)+ }++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, rt)+ }++ if strings.TrimSpace(args[1]) == "" {+ fmt.Fprintf(os.Stderr, "Custom name cleared; runtime is now %q.\n", strVal(rt, "name"))+ } else {+ fmt.Fprintf(os.Stderr, "Runtime renamed to %q.\n", strVal(rt, "custom_name"))+ }+ return nil+}+func runRuntimeUpdate(cmd *cobra.Command, args []string) error {client, err := newAPIClient(cmd)if err != nil {diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 631f2b7e98..63483c15b9 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -269,6 +269,70 @@ func normalizeProvider(s string) string {return strings.ToLower(strings.TrimSpace(s))}+// inheritMachineCustomName gives a freshly-inserted runtime the machine's+// shared custom name (MUL-4217) when the machine is already named, so adding a+// provider — or recording a failed custom-runtime profile — on a named machine+// doesn't leave a custom_name = NULL row that makes the machine title revert to+// its hostname. Both the normal runtime path and the failed-profile path write+// daemon_id-scoped rows that show up in the machine grouping, so both call this.+//+// Only fresh inserts with no name of their own and a daemon_id participate;+// existing rows keep whatever they already have. A lookup/update error is+// non-fatal — registration must still succeed — so the input row is returned+// unchanged on any failure.+func (h *Handler) inheritMachineCustomName(ctx context.Context, rt db.AgentRuntime, inserted bool) db.AgentRuntime {+ if !inserted || rt.CustomName.Valid || !rt.DaemonID.Valid {+ return rt+ }+ names, err := h.Queries.ListDaemonCustomNames(ctx, db.ListDaemonCustomNamesParams{+ WorkspaceID: rt.WorkspaceID,+ DaemonID: rt.DaemonID,+ ExcludeID: rt.ID,+ })+ if err != nil {+ return rt+ }+ shared, ok := sharedDaemonCustomName(names)+ if !ok {+ return rt+ }+ updated, err := h.Queries.UpdateAgentRuntimeCustomName(ctx, db.UpdateAgentRuntimeCustomNameParams{+ CustomName: pgtype.Text{String: shared, Valid: true},+ ID: rt.ID,+ })+ if err != nil {+ return rt+ }+ return updated+}++// sharedDaemonCustomName returns the machine-level name shared by all of a+// daemon's runtimes — the same rule the frontend's sharedCustomName applies:+// every runtime must carry the identical non-empty custom_name. Returns+// ("", false) when the set is empty, any runtime is unnamed, or the names+// disagree (i.e. there is no single machine name to inherit).+func sharedDaemonCustomName(names []pgtype.Text) (string, bool) {+ if len(names) == 0 {+ return "", false+ }+ var first string+ for i, n := range names {+ if !n.Valid {+ return "", false+ }+ v := strings.TrimSpace(n.String)+ if v == "" {+ return "", false+ }+ if i == 0 {+ first = v+ } else if v != first {+ return "", false+ }+ }+ return first, true+}+func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {var req DaemonRegisterRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {@@ -409,6 +473,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {WorkspaceID: prow.WorkspaceID,DaemonID: prow.DaemonID,Name: prow.Name,+ CustomName: prow.CustomName,RuntimeMode: prow.RuntimeMode,Provider: prow.Provider,Status: prow.Status,@@ -453,6 +518,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {WorkspaceID: row.WorkspaceID,DaemonID: row.DaemonID,Name: row.Name,+ CustomName: row.CustomName,RuntimeMode: row.RuntimeMode,Provider: row.Provider,Status: row.Status,@@ -468,6 +534,11 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {}}+ // A brand-new runtime on an already-named machine inherits the machine's+ // shared custom name so the machine title stays stable as providers come+ // and go (MUL-4217). Shared with the failed-profile path below.+ registered = h.inheritMachineCustomName(r.Context(), registered, inserted)+// Inserted is false for normal daemon reconnects/upserts, so// runtime_ready is a first-ready-per-runtime-row signal.if inserted {@@ -546,7 +617,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {"runtime_profile_failure_reason": reason,"command_name": commandName,})- if _, err := h.Queries.UpsertAgentRuntimeWithProfile(r.Context(), db.UpsertAgentRuntimeWithProfileParams{+ prow, err := h.Queries.UpsertAgentRuntimeWithProfile(r.Context(), db.UpsertAgentRuntimeWithProfileParams{WorkspaceID: wsUUID,DaemonID: strToText(req.DaemonID),Name: name,@@ -557,11 +628,21 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {Metadata: metadata,OwnerID: ownerID,ProfileID: profileUUID,- }); err != nil {+ })+ if err != nil {slog.Warn("failed to record runtime profile registration failure","workspace_id", req.WorkspaceID, "daemon_id", req.DaemonID,"profile_id", profileID, "error", err)+ continue}+ // Keep the failed-profile row consistent with the machine's name so it+ // doesn't drag the machine title back to the hostname (MUL-4217).+ h.inheritMachineCustomName(r.Context(), db.AgentRuntime{+ ID: prow.ID,+ WorkspaceID: prow.WorkspaceID,+ DaemonID: prow.DaemonID,+ CustomName: prow.CustomName,+ }, prow.Inserted)}slog.Info("daemon registered", "workspace_id", req.WorkspaceID, "daemon_id", req.DaemonID, "runtimes_count", len(resp))diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 88f996278e..6e569d523a 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -24,6 +24,10 @@ type AgentRuntimeResponse struct {WorkspaceID string `json:"workspace_id"`DaemonID *string `json:"daemon_id"`Name string `json:"name"`+ // CustomName is the user-set display override (MUL-4217); null when the+ // runtime still uses its daemon-proposed Name. Clients show+ // CustomName ?? Name and seed the rename field from this raw value.+ CustomName *string `json:"custom_name"`RuntimeMode string `json:"runtime_mode"`Provider string `json:"provider"`LaunchHeader string `json:"launch_header"`@@ -57,6 +61,7 @@ func runtimeToResponse(rt db.AgentRuntime) AgentRuntimeResponse {WorkspaceID: uuidToString(rt.WorkspaceID),DaemonID: textToPtr(rt.DaemonID),Name: rt.Name,+ CustomName: textToPtr(rt.CustomName),RuntimeMode: rt.RuntimeMode,Provider: rt.Provider,LaunchHeader: agent.LaunchHeader(rt.Provider),@@ -408,8 +413,22 @@ type UpdateAgentRuntimeRequest struct {// or workspace admins can bind agents) and "public" (any workspace// member can). Owner / workspace admin only, gated by canEditRuntime.Visibility *string `json:"visibility,omitempty"`+ // CustomName sets or clears a user-facing display override (MUL-4217).+ // An empty / whitespace-only string clears it (revert to the+ // daemon-proposed name). Owner / workspace admin only.+ CustomName *string `json:"custom_name,omitempty"`+ // ApplyToMachine, when true alongside CustomName, applies the name to+ // every runtime sharing this runtime's daemon_id (a machine hosts one+ // runtime per provider) instead of just this one. Ignored when the+ // runtime has no daemon_id.+ ApplyToMachine bool `json:"apply_to_machine,omitempty"`}+// maxRuntimeCustomNameLen caps a runtime's custom name. Default names are+// short (e.g. "Claude (host.local)"); 100 chars is generous headroom while+// keeping the picker rows and machine headers from overflowing.+const maxRuntimeCustomNameLen = 100+// UpdateAgentRuntime handles PATCH /api/runtimes/:id. Currently visibility// is editable; the request shape is open-ended so future fields (display// name, description) can be added without a route change.@@ -442,6 +461,8 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {return}+ // Validate every field before any mutation so a bad value in one field+ // can't leave a partially-applied PATCH.var (newVisibility stringneedVisibility bool@@ -458,6 +479,15 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {}}+ if req.CustomName != nil {+ if len([]rune(strings.TrimSpace(*req.CustomName))) > maxRuntimeCustomNameLen {+ writeError(w, http.StatusBadRequest, "custom name is too long")+ return+ }+ }++ changed := false+if needVisibility {updated, err := h.Queries.UpdateAgentRuntimeVisibility(r.Context(), db.UpdateAgentRuntimeVisibilityParams{ID: runtimeUUID,@@ -469,6 +499,59 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {return}rt = updated+ changed = true+ }++ if req.CustomName != nil {+ // An empty / whitespace-only name clears the override (NULL), so the+ // runtime falls back to its daemon-proposed Name.+ trimmed := strings.TrimSpace(*req.CustomName)+ customName := pgtype.Text{String: trimmed, Valid: trimmed != ""}++ if req.ApplyToMachine && rt.DaemonID.Valid {+ // Non-admins may only relabel their own runtimes on the machine;+ // owners/admins rename every runtime sharing the daemon_id. A NULL+ // owner filter means "all runtimes on this machine".+ var ownerFilter pgtype.UUID+ if !roleAllowed(member.Role, "owner", "admin") {+ ownerFilter = member.UserID+ }+ rows, err := h.Queries.UpdateAgentRuntimeCustomNameByDaemon(r.Context(), db.UpdateAgentRuntimeCustomNameByDaemonParams{+ CustomName: customName,+ WorkspaceID: rt.WorkspaceID,+ DaemonID: rt.DaemonID,+ OwnerID: ownerFilter,+ })+ if err != nil {+ slog.Error("UpdateAgentRuntimeCustomNameByDaemon failed", "error", err, "runtime_id", runtimeID)+ writeError(w, http.StatusInternalServerError, "failed to update runtime")+ return+ }+ // The actor always owns (or admins) the runtime addressed by :id,+ // so it is among the updated rows — surface it in the response.+ for _, row := range rows {+ if uuidToString(row.ID) == uuidToString(runtimeUUID) {+ rt = row+ break+ }+ }+ changed = true+ } else {+ updated, err := h.Queries.UpdateAgentRuntimeCustomName(r.Context(), db.UpdateAgentRuntimeCustomNameParams{+ CustomName: customName,+ ID: runtimeUUID,+ })+ if err != nil {+ slog.Error("UpdateAgentRuntimeCustomName failed", "error", err, "runtime_id", runtimeID)+ writeError(w, http.StatusInternalServerError, "failed to update runtime")+ return+ }+ rt = updated+ changed = true+ }+ }++ if changed {// Notify connected clients that runtime metadata changed so the// list/detail pages refresh — matches the pattern used by// DeleteAgentRuntime.diff --git a/server/internal/handler/runtime_custom_name_test.go b/server/internal/handler/runtime_custom_name_test.gonew file mode 100644index 0000000000..32377f3845--- /dev/null+++ b/server/internal/handler/runtime_custom_name_test.go@@ -0,0 +1,270 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++// patchRuntimeCustomName is a small helper that PATCHes /api/runtimes/:id with+// a custom_name body as the given actor and returns the recorder.+func patchRuntimeCustomName(actorID, runtimeID string, body map[string]any) *httptest.ResponseRecorder {+ w := httptest.NewRecorder()+ req := newRequestAs(actorID, http.MethodPatch, "/api/runtimes/"+runtimeID, body)+ req = withURLParam(req, "runtimeId", runtimeID)+ testHandler.UpdateAgentRuntime(w, req)+ return w+}++// TestUpdateAgentRuntime_CustomNamePatchApplies covers the single-runtime+// rename path (MUL-4217): a PATCH carrying custom_name sets it, an empty+// string clears it back to NULL, and an over-long value is rejected with 400.+func TestUpdateAgentRuntime_CustomNamePatchApplies(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ runtimeID, runtimeOwnerID, plainMemberID := runtimeVisibilityFixture(t)++ // Owner sets a custom name.+ w := patchRuntimeCustomName(runtimeOwnerID, runtimeID, map[string]any{"custom_name": " Prod Box "})+ if w.Code != http.StatusOK {+ t.Fatalf("PATCH custom_name: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp AgentRuntimeResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.CustomName == nil || *resp.CustomName != "Prod Box" {+ t.Fatalf("custom_name: got %v, want trimmed \"Prod Box\"", resp.CustomName)+ }+ // The raw daemon name is preserved alongside the override.+ if resp.Name != "Visibility Test Runtime" {+ t.Fatalf("name should be untouched by rename: got %q", resp.Name)+ }++ // Empty string clears the override back to NULL.+ w = patchRuntimeCustomName(runtimeOwnerID, runtimeID, map[string]any{"custom_name": " "})+ if w.Code != http.StatusOK {+ t.Fatalf("PATCH clear custom_name: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ resp = AgentRuntimeResponse{}+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.CustomName != nil {+ t.Fatalf("custom_name should be cleared to null, got %q", *resp.CustomName)+ }++ // Over-long name is rejected before any mutation.+ w = patchRuntimeCustomName(runtimeOwnerID, runtimeID, map[string]any{"custom_name": strings.Repeat("x", maxRuntimeCustomNameLen+1)})+ if w.Code != http.StatusBadRequest {+ t.Fatalf("PATCH over-long custom_name: expected 400, got %d: %s", w.Code, w.Body.String())+ }++ // Plain member cannot rename someone else's runtime.+ w = patchRuntimeCustomName(plainMemberID, runtimeID, map[string]any{"custom_name": "hijack"})+ if w.Code != http.StatusForbidden {+ t.Fatalf("PATCH custom_name as plain member: expected 403, got %d: %s", w.Code, w.Body.String())+ }+}++// TestUpdateAgentRuntime_CustomNameMachineFanout verifies that+// apply_to_machine renames every runtime sharing a daemon_id, so a machine+// hosting several provider runtimes can be labelled in one action.+func TestUpdateAgentRuntime_CustomNameMachineFanout(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ _, runtimeOwnerID, _ := runtimeVisibilityFixture(t)+ ctx := context.Background()++ const daemonID = "custom-name-test-daemon"+ makeRuntime := func(provider string) string {+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_runtime (+ workspace_id, daemon_id, name, runtime_mode, provider, status,+ device_info, metadata, owner_id, visibility, last_seen_at+ )+ VALUES ($1, $2, $3, 'local', $4, 'online', 'host', '{}'::jsonb, $5, 'private', now())+ RETURNING id+ `, testWorkspaceID, daemonID, provider+" (host)", provider, runtimeOwnerID).Scan(&id); err != nil {+ t.Fatalf("create runtime %s: %v", provider, err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, id)+ })+ return id+ }++ idA := makeRuntime("ccn_a")+ idB := makeRuntime("ccn_b")++ w := patchRuntimeCustomName(runtimeOwnerID, idA, map[string]any{+ "custom_name": "Bohan's MacBook",+ "apply_to_machine": true,+ })+ if w.Code != http.StatusOK {+ t.Fatalf("PATCH machine rename: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ // Both runtimes on the daemon must now carry the name.+ for _, id := range []string{idA, idB} {+ var name *string+ if err := testPool.QueryRow(ctx, `SELECT custom_name FROM agent_runtime WHERE id = $1`, id).Scan(&name); err != nil {+ t.Fatalf("read custom_name for %s: %v", id, err)+ }+ if name == nil || *name != "Bohan's MacBook" {+ t.Fatalf("runtime %s custom_name = %v, want machine name applied", id, name)+ }+ }+}++// registerRuntimeOnDaemon registers a single built-in runtime for a daemon via+// the daemon-token path and returns the first runtime object from the response.+func registerRuntimeOnDaemon(t *testing.T, daemonID, provider string) map[string]any {+ t.Helper()+ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{+ "workspace_id": testWorkspaceID,+ "daemon_id": daemonID,+ "device_name": "host",+ "runtimes": []map[string]any{+ {"name": provider + " (host)", "type": provider, "version": "1.0.0", "status": "online"},+ },+ }, testWorkspaceID, daemonID)+ testHandler.DaemonRegister(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("register %s: expected 200, got %d: %s", provider, w.Code, w.Body.String())+ }+ var resp map[string]any+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode register response: %v", err)+ }+ runtimes, ok := resp["runtimes"].([]any)+ if !ok || len(runtimes) == 0 {+ t.Fatalf("register %s: no runtimes in response: %v", provider, resp)+ }+ return runtimes[0].(map[string]any)+}++// TestDaemonRegister_PreservesCustomNameInResponse guards Elon's finding that+// the register handler reconstructed the response row by hand and dropped+// custom_name, so a re-registering (heartbeat/reconnect) runtime that already+// had a custom name came back as custom_name: null — inconsistent with+// list/get/update.+func TestDaemonRegister_PreservesCustomNameInResponse(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ const daemonID = "custom-name-register-preserve"+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE daemon_id = $1`, daemonID)+ })++ first := registerRuntimeOnDaemon(t, daemonID, "claude")+ runtimeID := first["id"].(string)++ // Simulate a rename, then re-register (the upsert preserves custom_name).+ if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET custom_name = 'Prod Box' WHERE id = $1`, runtimeID); err != nil {+ t.Fatalf("set custom_name: %v", err)+ }++ again := registerRuntimeOnDaemon(t, daemonID, "claude")+ if again["custom_name"] != "Prod Box" {+ t.Fatalf("register response custom_name = %v, want \"Prod Box\" (must not be dropped)", again["custom_name"])+ }+}++// TestDaemonRegister_NewRuntimeInheritsMachineName guards Elon's finding that a+// machine's custom name looked "lost" once a new provider registered on it:+// the new runtime landed with custom_name = null. It should instead inherit+// the machine's shared name so the machine title stays stable.+func TestDaemonRegister_NewRuntimeInheritsMachineName(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ const daemonID = "custom-name-register-inherit"+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE daemon_id = $1`, daemonID)+ })++ // Provider A registers, then the whole machine is named.+ first := registerRuntimeOnDaemon(t, daemonID, "claude")+ idA := first["id"].(string)+ if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET custom_name = 'Bohan MacBook' WHERE id = $1`, idA); err != nil {+ t.Fatalf("name machine: %v", err)+ }++ // A brand-new provider on the same machine must inherit the machine name —+ // both in the response and persisted.+ second := registerRuntimeOnDaemon(t, daemonID, "codex")+ if second["custom_name"] != "Bohan MacBook" {+ t.Fatalf("new runtime response custom_name = %v, want inherited \"Bohan MacBook\"", second["custom_name"])+ }+ var persisted *string+ if err := testPool.QueryRow(ctx, `SELECT custom_name FROM agent_runtime WHERE id = $1`, second["id"].(string)).Scan(&persisted); err != nil {+ t.Fatalf("read persisted custom_name: %v", err)+ }+ if persisted == nil || *persisted != "Bohan MacBook" {+ t.Fatalf("persisted custom_name = %v, want inherited \"Bohan MacBook\"", persisted)+ }+}++// TestDaemonRegister_FailedProfileInheritsMachineName guards the same-class+// gap Elon flagged on re-review: the failed-custom-profile branch also writes a+// daemon_id-scoped agent_runtime row, so it must inherit the machine name too —+// otherwise enabling a custom runtime that can't resolve on a named machine+// lands a custom_name=NULL row and drags the machine title back to the hostname.+func TestDaemonRegister_FailedProfileInheritsMachineName(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ const daemonID = "custom-name-register-failed-profile"+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE daemon_id = $1`, daemonID)+ })++ // A named machine: register a normal runtime, then name the whole machine.+ first := registerRuntimeOnDaemon(t, daemonID, "claude")+ if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET custom_name = 'Bohan MacBook' WHERE id = $1`, first["id"].(string)); err != nil {+ t.Fatalf("name machine: %v", err)+ }++ // A custom runtime profile fails to resolve on this machine.+ profileID := insertRuntimeProfileFixture(t, ctx, "Custom Codex", "codex", "missing-codex")++ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{+ "workspace_id": testWorkspaceID,+ "daemon_id": daemonID,+ "device_name": "host",+ "failed_profiles": []map[string]any{+ {"profile_id": profileID, "command_name": "missing-codex", "reason": "command not found on PATH"},+ },+ }, testWorkspaceID, daemonID)+ testHandler.DaemonRegister(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("register failed profile: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ // The failed-profile row must have inherited the machine name.+ var name *string+ if err := testPool.QueryRow(ctx, `+ SELECT custom_name FROM agent_runtime+ WHERE workspace_id = $1 AND daemon_id = $2 AND profile_id = $3+ `, testWorkspaceID, daemonID, profileID).Scan(&name); err != nil {+ t.Fatalf("read failed-profile custom_name: %v", err)+ }+ if name == nil || *name != "Bohan MacBook" {+ t.Fatalf("failed-profile custom_name = %v, want inherited \"Bohan MacBook\"", name)+ }+}diff --git a/server/migrations/145_agent_runtime_custom_name.down.sql b/server/migrations/145_agent_runtime_custom_name.down.sqlnew file mode 100644index 0000000000..168d1922b4--- /dev/null+++ b/server/migrations/145_agent_runtime_custom_name.down.sql@@ -0,0 +1 @@+ALTER TABLE agent_runtime DROP COLUMN IF EXISTS custom_name;diff --git a/server/migrations/145_agent_runtime_custom_name.up.sql b/server/migrations/145_agent_runtime_custom_name.up.sqlnew file mode 100644index 0000000000..f085ae8981--- /dev/null+++ b/server/migrations/145_agent_runtime_custom_name.up.sql@@ -0,0 +1,10 @@+-- Adds an optional user-facing custom name for a runtime (MUL-4217).+-- custom_name overrides the daemon-proposed `name` for display only; NULL+-- falls back to `name`. Deliberately NOT written by the registration /+-- heartbeat upserts (which do name = EXCLUDED.name on every beat), so a+-- user's custom name is never clobbered by the daemon.+--+-- No index: the column is only ever read as part of a full-row runtime fetch+-- and never appears in a WHERE / ORDER BY, so it needs none. Adding a+-- nullable column with no default is a fast catalog-only change.+ALTER TABLE agent_runtime ADD COLUMN custom_name TEXT;diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 6a3d700a5b..5ff5a463ea 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -77,6 +77,7 @@ type AgentRuntime struct {LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`Visibility string `json:"visibility"`ProfileID pgtype.UUID `json:"profile_id"`+ CustomName pgtype.Text `json:"custom_name"`}type AgentSkill struct {diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 9902af0149..219acbeea0 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -265,7 +265,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ}const findLegacyRuntimesByDaemonID = `-- name: FindLegacyRuntimesByDaemonID :many-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name FROM agent_runtimeWHERE workspace_id = $1AND provider = $2AND LOWER(daemon_id) = LOWER($3)@@ -318,6 +318,7 @@ func (q *Queries) FindLegacyRuntimesByDaemonID(ctx context.Context, arg FindLega&i.LegacyDaemonID,&i.Visibility,&i.ProfileID,+ &i.CustomName,); err != nil {return nil, err}@@ -377,7 +378,7 @@ func (q *Queries) ForceOfflineRuntimesByIDs(ctx context.Context, runtimeIds []pg}const getAgentRuntime = `-- name: GetAgentRuntime :one-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name FROM agent_runtimeWHERE id = $1`@@ -401,12 +402,13 @@ func (q *Queries) GetAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRun&i.LegacyDaemonID,&i.Visibility,&i.ProfileID,+ &i.CustomName,)return i, err}const getAgentRuntimeForWorkspace = `-- name: GetAgentRuntimeForWorkspace :one-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name FROM agent_runtimeWHERE id = $1 AND workspace_id = $2`@@ -435,12 +437,13 @@ func (q *Queries) GetAgentRuntimeForWorkspace(ctx context.Context, arg GetAgentR&i.LegacyDaemonID,&i.Visibility,&i.ProfileID,+ &i.CustomName,)return i, err}const listAgentRuntimes = `-- name: ListAgentRuntimes :many-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name FROM agent_runtimeWHERE workspace_id = $1ORDER BY created_at ASC`@@ -471,6 +474,7 @@ func (q *Queries) ListAgentRuntimes(ctx context.Context, workspaceID pgtype.UUID&i.LegacyDaemonID,&i.Visibility,&i.ProfileID,+ &i.CustomName,); err != nil {return nil, err}@@ -483,7 +487,7 @@ func (q *Queries) ListAgentRuntimes(ctx context.Context, workspaceID pgtype.UUID}const listAgentRuntimesByOwner = `-- name: ListAgentRuntimesByOwner :many-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name FROM agent_runtimeWHERE workspace_id = $1 AND owner_id = $2ORDER BY created_at ASC`@@ -519,6 +523,7 @@ func (q *Queries) ListAgentRuntimesByOwner(ctx context.Context, arg ListAgentRun&i.LegacyDaemonID,&i.Visibility,&i.ProfileID,+ &i.CustomName,); err != nil {return nil, err}@@ -557,8 +562,48 @@ func (q *Queries) ListArchivedAgentIDsByRuntime(ctx context.Context, runtimeID preturn items, nil}+const listDaemonCustomNames = `-- name: ListDaemonCustomNames :many+SELECT custom_name FROM agent_runtime+WHERE workspace_id = $1+ AND daemon_id = $2+ AND id <> $3+`++type ListDaemonCustomNamesParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ DaemonID pgtype.Text `json:"daemon_id"`+ ExcludeID pgtype.UUID `json:"exclude_id"`+}++// Lists the custom_name of every OTHER runtime on (workspace_id, daemon_id)+// (MUL-4217). @exclude_id drops the just-registered row. The caller derives+// the machine-level name in Go — the same "all runtimes share one non-null+// name" rule the frontend applies in sharedCustomName — so a freshly-added+// runtime on an already-named machine can inherit that name and keep the+// machine's display name stable. A daemon hosts only a handful of runtimes+// (one per provider), so this is a tiny read.+func (q *Queries) ListDaemonCustomNames(ctx context.Context, arg ListDaemonCustomNamesParams) ([]pgtype.Text, error) {+ rows, err := q.db.Query(ctx, listDaemonCustomNames, arg.WorkspaceID, arg.DaemonID, arg.ExcludeID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.Text{}+ for rows.Next() {+ var custom_name pgtype.Text+ if err := rows.Scan(&custom_name); err != nil {+ return nil, err+ }+ items = append(items, custom_name)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const lockAgentRuntime = `-- name: LockAgentRuntime :one-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name FROM agent_runtimeWHERE id = $1FOR UPDATE`@@ -597,6 +642,7 @@ func (q *Queries) LockAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRu&i.LegacyDaemonID,&i.Visibility,&i.ProfileID,+ &i.CustomName,)return i, err}@@ -605,7 +651,7 @@ const markAgentRuntimeOnline = `-- name: MarkAgentRuntimeOnline :oneUPDATE agent_runtimeSET status = 'online', last_seen_at = now(), updated_at = now()WHERE id = $1-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name`// Used on the offline→online transition (and on first heartbeat after@@ -631,6 +677,7 @@ func (q *Queries) MarkAgentRuntimeOnline(ctx context.Context, id pgtype.UUID) (A&i.LegacyDaemonID,&i.Visibility,&i.ProfileID,+ &i.CustomName,)return i, err}@@ -879,11 +926,118 @@ func (q *Queries) TouchAgentRuntimesLastSeenBatch(ctx context.Context, ids []pgtreturn result.RowsAffected(), nil}+const updateAgentRuntimeCustomName = `-- name: UpdateAgentRuntimeCustomName :one+UPDATE agent_runtime+SET custom_name = $1, updated_at = now()+WHERE id = $2+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name+`++type UpdateAgentRuntimeCustomNameParams struct {+ CustomName pgtype.Text `json:"custom_name"`+ ID pgtype.UUID `json:"id"`+}++// Sets or clears a runtime's user-facing custom name (MUL-4217). custom_name+// overrides the daemon-proposed `name` for display; passing NULL reverts to+// the default. Kept separate from the registration upserts above (which do+// name = EXCLUDED.name on every heartbeat) so a custom name is never+// clobbered by the daemon. Gated at the handler to owner / workspace admin.+func (q *Queries) UpdateAgentRuntimeCustomName(ctx context.Context, arg UpdateAgentRuntimeCustomNameParams) (AgentRuntime, error) {+ row := q.db.QueryRow(ctx, updateAgentRuntimeCustomName, arg.CustomName, arg.ID)+ var i AgentRuntime+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DaemonID,+ &i.Name,+ &i.RuntimeMode,+ &i.Provider,+ &i.Status,+ &i.DeviceInfo,+ &i.Metadata,+ &i.LastSeenAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.OwnerID,+ &i.LegacyDaemonID,+ &i.Visibility,+ &i.ProfileID,+ &i.CustomName,+ )+ return i, err+}++const updateAgentRuntimeCustomNameByDaemon = `-- name: UpdateAgentRuntimeCustomNameByDaemon :many+UPDATE agent_runtime+SET custom_name = $1, updated_at = now()+WHERE workspace_id = $2+ AND daemon_id = $3+ AND ($4::uuid IS NULL OR owner_id = $4)+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name+`++type UpdateAgentRuntimeCustomNameByDaemonParams struct {+ CustomName pgtype.Text `json:"custom_name"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ DaemonID pgtype.Text `json:"daemon_id"`+ OwnerID pgtype.UUID `json:"owner_id"`+}++// Machine-level rename (MUL-4217): applies one custom name to every runtime+// sharing a daemon_id in the workspace, since a single machine hosts one+// runtime per provider. @owner_id is NULL for workspace owners/admins (rename+// the whole machine) or the actor's user id otherwise (only their own+// runtimes on that machine), so a member cannot relabel someone else's+// runtime that happens to share the host.+func (q *Queries) UpdateAgentRuntimeCustomNameByDaemon(ctx context.Context, arg UpdateAgentRuntimeCustomNameByDaemonParams) ([]AgentRuntime, error) {+ rows, err := q.db.Query(ctx, updateAgentRuntimeCustomNameByDaemon,+ arg.CustomName,+ arg.WorkspaceID,+ arg.DaemonID,+ arg.OwnerID,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentRuntime{}+ for rows.Next() {+ var i AgentRuntime+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DaemonID,+ &i.Name,+ &i.RuntimeMode,+ &i.Provider,+ &i.Status,+ &i.DeviceInfo,+ &i.Metadata,+ &i.LastSeenAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.OwnerID,+ &i.LegacyDaemonID,+ &i.Visibility,+ &i.ProfileID,+ &i.CustomName,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const updateAgentRuntimeVisibility = `-- name: UpdateAgentRuntimeVisibility :oneUPDATE agent_runtimeSET visibility = $1, updated_at = now()WHERE id = $2-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name`type UpdateAgentRuntimeVisibilityParams struct {@@ -915,6 +1069,7 @@ func (q *Queries) UpdateAgentRuntimeVisibility(ctx context.Context, arg UpdateAg&i.LegacyDaemonID,&i.Visibility,&i.ProfileID,+ &i.CustomName,)return i, err}@@ -942,7 +1097,7 @@ DO UPDATE SETowner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),last_seen_at = now(),updated_at = now()-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, (xmax = 0) AS inserted+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, (xmax = 0) AS inserted`type UpsertAgentRuntimeParams struct {@@ -974,6 +1129,7 @@ type UpsertAgentRuntimeRow struct {LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`Visibility string `json:"visibility"`ProfileID pgtype.UUID `json:"profile_id"`+ CustomName pgtype.Text `json:"custom_name"`Inserted bool `json:"inserted"`}@@ -1014,6 +1170,7 @@ func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntime&i.LegacyDaemonID,&i.Visibility,&i.ProfileID,+ &i.CustomName,&i.Inserted,)return i, err@@ -1044,7 +1201,7 @@ DO UPDATE SETowner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),last_seen_at = now(),updated_at = now()-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, (xmax = 0) AS inserted+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, (xmax = 0) AS inserted`type UpsertAgentRuntimeWithProfileParams struct {@@ -1077,6 +1234,7 @@ type UpsertAgentRuntimeWithProfileRow struct {LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`Visibility string `json:"visibility"`ProfileID pgtype.UUID `json:"profile_id"`+ CustomName pgtype.Text `json:"custom_name"`Inserted bool `json:"inserted"`}@@ -1118,6 +1276,7 @@ func (q *Queries) UpsertAgentRuntimeWithProfile(ctx context.Context, arg UpsertA&i.LegacyDaemonID,&i.Visibility,&i.ProfileID,+ &i.CustomName,&i.Inserted,)return i, errdiff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex efe4cc522d..90eca2a2e8 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -105,6 +105,44 @@ SET visibility = @visibility, updated_at = now()WHERE id = @idRETURNING *;+-- name: UpdateAgentRuntimeCustomName :one+-- Sets or clears a runtime's user-facing custom name (MUL-4217). custom_name+-- overrides the daemon-proposed `name` for display; passing NULL reverts to+-- the default. Kept separate from the registration upserts above (which do+-- name = EXCLUDED.name on every heartbeat) so a custom name is never+-- clobbered by the daemon. Gated at the handler to owner / workspace admin.+UPDATE agent_runtime+SET custom_name = @custom_name, updated_at = now()+WHERE id = @id+RETURNING *;++-- name: UpdateAgentRuntimeCustomNameByDaemon :many+-- Machine-level rename (MUL-4217): applies one custom name to every runtime+-- sharing a daemon_id in the workspace, since a single machine hosts one+-- runtime per provider. @owner_id is NULL for workspace owners/admins (rename+-- the whole machine) or the actor's user id otherwise (only their own+-- runtimes on that machine), so a member cannot relabel someone else's+-- runtime that happens to share the host.+UPDATE agent_runtime+SET custom_name = @custom_name, updated_at = now()+WHERE workspace_id = @workspace_id+ AND daemon_id = @daemon_id+ AND (@owner_id::uuid IS NULL OR owner_id = @owner_id)+RETURNING *;++-- name: ListDaemonCustomNames :many+-- Lists the custom_name of every OTHER runtime on (workspace_id, daemon_id)+-- (MUL-4217). @exclude_id drops the just-registered row. The caller derives+-- the machine-level name in Go — the same "all runtimes share one non-null+-- name" rule the frontend applies in sharedCustomName — so a freshly-added+-- runtime on an already-named machine can inherit that name and keep the+-- machine's display name stable. A daemon hosts only a handful of runtimes+-- (one per provider), so this is a tiny read.+SELECT custom_name FROM agent_runtime+WHERE workspace_id = @workspace_id+ AND daemon_id = @daemon_id+ AND id <> @exclude_id;+-- name: TouchAgentRuntimeLastSeen :execrows-- Bumps last_seen_at on an already-online runtime. Deliberately does NOT