Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
Make custom runtimes appear immediately (#4234)
LinYushen77ac17ef498c
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.jsonindex 8f3a085c2d..e785692ae7 100644--- a/packages/views/locales/en/runtimes.json+++ b/packages/views/locales/en/runtimes.json@@ -39,6 +39,7 @@"section_cloud": "Cloud","this_machine": "This device","local_badge": "Local · this machine",+ "pending_custom_runtimes": "Pending custom runtimes","runtime_count_one": "{{count}} runtime","runtime_count_other": "{{count}} runtimes","busy_count_one": "{{count}} busy",@@ -265,12 +266,17 @@"delete_permission_hint": "Only the runtime owner and workspace admins can delete this runtime","delete_admin_hint": "Only the runtime owner and workspace admins can delete a runtime.","badge_builtin": "Built-in",- "badge_custom": "Custom"+ "badge_custom": "Custom",+ "badge_registering": "Registering",+ "pending_health": "Registering with daemon",+ "pending_health_warning": "Waiting for daemon sync",+ "pending_cli_unknown": "waiting"},"profiles": {"cta": "Add runtime","dialog_title": "Custom runtimes","dialog_description": "Create and manage custom runtime backends based on supported protocol families.",+ "close": "Close","add_new": "New custom runtime","list_title": "Runtime backends","custom_section_title": "Custom runtimes ({{count}})",diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.jsonindex 1c4814b499..1722216065 100644--- a/packages/views/locales/ja/runtimes.json+++ b/packages/views/locales/ja/runtimes.json@@ -39,6 +39,7 @@"section_cloud": "クラウド","this_machine": "このデバイス","local_badge": "ローカル · このマシン",+ "pending_custom_runtimes": "登録待ちのカスタムランタイム","runtime_count_other": "ランタイム {{count}} 個","busy_count_other": "使用中 {{count}} 個","no_matches_title": "マシンなし",@@ -253,12 +254,17 @@"delete_permission_hint": "ランタイムの所有者とワークスペース管理者のみが、このランタイムを削除できます","delete_admin_hint": "ランタイムの所有者とワークスペース管理者のみが、ランタイムを削除できます。","badge_builtin": "組み込み",- "badge_custom": "カスタム"+ "badge_custom": "カスタム",+ "badge_registering": "登録中",+ "pending_health": "Daemon に登録中",+ "pending_health_warning": "Daemon 同期待ち",+ "pending_cli_unknown": "待機中"},"profiles": {"cta": "ランタイムを追加","dialog_title": "カスタムランタイム","dialog_description": "サポートされているプロトコルファミリーを基に、エージェント用のカスタムランタイムバックエンドを作成・管理します。",+ "close": "閉じる","add_new": "新しいカスタムランタイム","list_title": "ランタイムバックエンド","custom_section_title": "カスタムランタイム({{count}})",diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.jsonindex a2c2f980eb..efa1378a7e 100644--- a/packages/views/locales/ko/runtimes.json+++ b/packages/views/locales/ko/runtimes.json@@ -39,6 +39,7 @@"section_cloud": "클라우드","this_machine": "이 Mac","local_badge": "로컬 · 이 기기",+ "pending_custom_runtimes": "등록 대기 중인 사용자 지정 런타임","runtime_count_one": "런타임 {{count}}개","runtime_count_other": "런타임 {{count}}개","busy_count_one": "사용 중 {{count}}개",@@ -265,12 +266,17 @@"delete_permission_hint": "런타임 소유자와 워크스페이스 관리자만 이 런타임을 삭제할 수 있습니다","delete_admin_hint": "런타임 소유자와 워크스페이스 관리자만 런타임을 삭제할 수 있습니다.","badge_builtin": "기본 제공",- "badge_custom": "사용자 지정"+ "badge_custom": "사용자 지정",+ "badge_registering": "등록 중",+ "pending_health": "Daemon에 등록 중",+ "pending_health_warning": "Daemon 동기화 대기 중",+ "pending_cli_unknown": "대기 중"},"profiles": {"cta": "런타임 추가","dialog_title": "사용자 지정 런타임","dialog_description": "지원되는 프로토콜 제품군을 기반으로 에이전트가 사용할 사용자 지정 런타임 백엔드를 만들고 관리합니다.",+ "close": "닫기","add_new": "새 사용자 지정 런타임","list_title": "런타임 백엔드","custom_section_title": "사용자 지정 런타임({{count}})",diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.jsonindex c85d258110..b02965dc83 100644--- a/packages/views/locales/zh-Hans/runtimes.json+++ b/packages/views/locales/zh-Hans/runtimes.json@@ -39,6 +39,7 @@"section_cloud": "云端","this_machine": "本机","local_badge": "本地 · 这台机器",+ "pending_custom_runtimes": "待注册自定义运行时","runtime_count_other": "{{count}} 个运行时","busy_count_other": "{{count}} 个忙碌","no_matches_title": "没有机器",@@ -253,12 +254,17 @@"delete_permission_hint": "只有运行时所有者和工作区管理员可以删除这个运行时","delete_admin_hint": "只有运行时所有者和工作区管理员可以删除运行时。","badge_builtin": "内置",- "badge_custom": "自定义"+ "badge_custom": "自定义",+ "badge_registering": "注册中",+ "pending_health": "正在向守护进程注册",+ "pending_health_warning": "等待守护进程同步",+ "pending_cli_unknown": "等待中"},"profiles": {"cta": "添加运行时","dialog_title": "自定义运行时","dialog_description": "基于支持的协议族,创建和管理智能体可使用的自定义运行时后端。",+ "close": "关闭","add_new": "新建自定义运行时","list_title": "运行时后端","custom_section_title": "自定义运行时({{count}})",diff --git a/packages/views/runtimes/components/pending-runtime.test.ts b/packages/views/runtimes/components/pending-runtime.test.tsnew file mode 100644index 0000000000..8c1bd1b387--- /dev/null+++ b/packages/views/runtimes/components/pending-runtime.test.ts@@ -0,0 +1,123 @@+import { describe, expect, it } from "vitest";+import type { AgentRuntime, RuntimeProfile } from "@multica/core/types";+import {+ PENDING_RUNTIME_WARNING_MS,+ isPendingCustomRuntime,+ isPendingCustomRuntimeWarning,+ pendingRuntimeCommandName,+ pendingRuntimeFromProfile,+ pendingRuntimeId,+ pendingRuntimesForProfiles,+} from "./pending-runtime";++function profile(overrides: Partial<RuntimeProfile> = {}): RuntimeProfile {+ return {+ id: "profile-1",+ workspace_id: "ws-1",+ display_name: "Team Codex",+ protocol_family: "codex",+ command_name: "team-codex",+ description: null,+ fixed_args: [],+ visibility: "workspace",+ created_by: "user-1",+ enabled: true,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-02T00:00:00Z",+ ...overrides,+ };+}++function runtime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {+ return {+ id: "runtime-1",+ workspace_id: "ws-1",+ daemon_id: "daemon-1",+ name: "Codex (MacBook)",+ runtime_mode: "local",+ provider: "codex",+ launch_header: "codex",+ status: "online",+ device_info: "MacBook",+ metadata: {},+ owner_id: "user-1",+ visibility: "private",+ profile_id: null,+ last_seen_at: "2026-01-01T00:00:00Z",+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ ...overrides,+ };+}++describe("pending custom runtime rows", () => {+ it("builds a pending runtime from the newly created profile", () => {+ const createdAt = Date.parse("2026-01-01T00:00:00Z");+ const pending = pendingRuntimeFromProfile({+ profile: profile(),+ createdAt,+ ownerId: "user-1",+ localDaemonId: "daemon-1",+ localMachineName: "MacBook",+ });++ expect(pending.id).toBe(pendingRuntimeId("profile-1"));+ expect(pending.name).toBe("Team Codex (MacBook)");+ expect(pending.daemon_id).toBe("daemon-1");+ expect(pending.profile_id).toBe("profile-1");+ expect(pending.provider).toBe("codex");+ expect(isPendingCustomRuntime(pending)).toBe(true);+ expect(pendingRuntimeCommandName(pending)).toBe("team-codex");+ });++ it("drops the pending row once a real runtime registers for the profile", () => {+ const createdAt = Date.parse("2026-01-01T00:00:00Z");+ const prof = profile();+ const baseRuntime = runtime();+ const registeredRuntime = runtime({+ id: "runtime-custom",+ profile_id: prof.id,+ });++ expect(+ pendingRuntimesForProfiles({+ pendingProfiles: [{ profile: prof, createdAt }],+ runtimes: [baseRuntime],+ ownerId: "user-1",+ localDaemonId: "daemon-1",+ localMachineName: "MacBook",+ }).map((item) => item.id),+ ).toEqual(["runtime-1", pendingRuntimeId(prof.id)]);++ expect(+ pendingRuntimesForProfiles({+ pendingProfiles: [{ profile: prof, createdAt }],+ runtimes: [baseRuntime, registeredRuntime],+ ownerId: "user-1",+ localDaemonId: "daemon-1",+ localMachineName: "MacBook",+ }).map((item) => item.id),+ ).toEqual(["runtime-1", "runtime-custom"]);+ });++ it("marks pending runtimes as waiting after the grace window", () => {+ const createdAt = Date.parse("2026-01-01T00:00:00Z");+ const pending = pendingRuntimeFromProfile({+ profile: profile(),+ createdAt,+ });++ expect(+ isPendingCustomRuntimeWarning(+ pending,+ createdAt + PENDING_RUNTIME_WARNING_MS - 1,+ ),+ ).toBe(false);+ expect(+ isPendingCustomRuntimeWarning(+ pending,+ createdAt + PENDING_RUNTIME_WARNING_MS,+ ),+ ).toBe(true);+ });+});diff --git a/packages/views/runtimes/components/pending-runtime.ts b/packages/views/runtimes/components/pending-runtime.tsnew file mode 100644index 0000000000..9fd9eab07b--- /dev/null+++ b/packages/views/runtimes/components/pending-runtime.ts@@ -0,0 +1,125 @@+import type { AgentRuntime, RuntimeProfile } from "@multica/core/types";++export const PENDING_RUNTIME_WARNING_MS = 45_000;++const PENDING_RUNTIME_ID_PREFIX = "pending-runtime-profile:";++interface PendingRuntimeMetadata extends Record<string, unknown> {+ pending_custom_runtime: true;+ runtime_profile_id: string;+ command_name: string;+ pending_since: string;+}++export interface PendingRuntimeProfile {+ profile: RuntimeProfile;+ createdAt: number;+}++export function pendingRuntimeId(profileId: string): string {+ return `${PENDING_RUNTIME_ID_PREFIX}${profileId}`;+}++export function isPendingCustomRuntime(runtime: AgentRuntime): boolean {+ return runtime.metadata?.pending_custom_runtime === true;+}++export function pendingRuntimeCommandName(runtime: AgentRuntime): string | null {+ const command = runtime.metadata?.command_name;+ return typeof command === "string" && command.trim() ? command : null;+}++export function isPendingCustomRuntimeWarning(+ runtime: AgentRuntime,+ now: number,+): boolean {+ if (!isPendingCustomRuntime(runtime)) return false;+ const pendingSince = runtime.metadata?.pending_since;+ if (typeof pendingSince !== "string") return false;+ const startedAt = new Date(pendingSince).getTime();+ if (!Number.isFinite(startedAt)) return false;+ return now - startedAt >= PENDING_RUNTIME_WARNING_MS;+}++export function pendingRuntimeFromProfile({+ profile,+ createdAt,+ ownerId,+ localDaemonId,+ localMachineName,+ fallbackMachineName,+}: {+ profile: RuntimeProfile;+ createdAt: number;+ ownerId?: string | null;+ localDaemonId?: string | null;+ localMachineName?: string | null;+ fallbackMachineName?: string | null;+}): AgentRuntime {+ const pendingSince = new Date(createdAt).toISOString();+ const machineName =+ localMachineName?.trim() ||+ fallbackMachineName?.trim() ||+ "Pending custom runtimes";+ const metadata: PendingRuntimeMetadata = {+ pending_custom_runtime: true,+ runtime_profile_id: profile.id,+ command_name: profile.command_name,+ pending_since: pendingSince,+ };++ return {+ id: pendingRuntimeId(profile.id),+ workspace_id: profile.workspace_id,+ daemon_id: localDaemonId ?? null,+ name: `${profile.display_name} (${machineName})`,+ runtime_mode: "local",+ provider: profile.protocol_family,+ launch_header: profile.protocol_family,+ status: "offline",+ device_info: machineName,+ metadata,+ owner_id: ownerId ?? null,+ visibility: "private",+ profile_id: profile.id,+ last_seen_at: pendingSince,+ created_at: pendingSince,+ updated_at: pendingSince,+ };+}++export function pendingRuntimesForProfiles({+ pendingProfiles,+ runtimes,+ ownerId,+ localDaemonId,+ localMachineName,+ fallbackMachineName,+}: {+ pendingProfiles: PendingRuntimeProfile[];+ runtimes: AgentRuntime[];+ ownerId?: string | null;+ localDaemonId?: string | null;+ localMachineName?: string | null;+ fallbackMachineName?: string | null;+}): AgentRuntime[] {+ if (pendingProfiles.length === 0) return runtimes;+ const registeredProfileIds = new Set(+ runtimes+ .map((runtime) => runtime.profile_id)+ .filter((profileId): profileId is string => !!profileId),+ );+ const pendingRuntimes = pendingProfiles+ .filter(({ profile }) => !registeredProfileIds.has(profile.id))+ .map(({ profile, createdAt }) =>+ pendingRuntimeFromProfile({+ profile,+ createdAt,+ ownerId,+ localDaemonId,+ localMachineName,+ fallbackMachineName,+ }),+ );+ return [...runtimes, ...pendingRuntimes];+}diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsxindex 429b62d55e..2bd554c680 100644--- a/packages/views/runtimes/components/runtime-list.tsx+++ b/packages/views/runtimes/components/runtime-list.tsx@@ -1,7 +1,13 @@"use client";import { useMemo, useState } from "react";-import { Globe, MoreHorizontal, Trash2 } from "lucide-react";+import {+ AlertTriangle,+ Globe,+ Loader2,+ MoreHorizontal,+ Trash2,+} from "lucide-react";import { toast } from "sonner";import { useQuery } from "@tanstack/react-query";import type {@@ -52,6 +58,11 @@ import {pctChange,} from "../utils";import { splitRuntimeName } from "./runtime-machines";+import {+ isPendingCustomRuntime,+ isPendingCustomRuntimeWarning,+ pendingRuntimeCommandName,+} from "./pending-runtime";import { useT } from "../../i18n";// The machine detail's runtimes table on the shared ListGrid. Paradigm@@ -178,6 +189,7 @@ function RuntimeNameCell({ runtime }: { runtime: AgentRuntime }) {{baseName}</span><RuntimeKindBadge runtime={runtime} />+ <PendingRuntimeBadge runtime={runtime} /><VisibilityBadge runtime={runtime} /></div></ListGridCell>@@ -206,6 +218,16 @@ function RuntimeKindBadge({ runtime }: { runtime: AgentRuntime }) {);}+function PendingRuntimeBadge({ runtime }: { runtime: AgentRuntime }) {+ const { t } = useT("runtimes");+ if (!isPendingCustomRuntime(runtime)) return null;+ return (+ <span className="inline-flex shrink-0 items-center rounded bg-warning/10 px-1 text-[10px] font-medium text-warning">+ {t(($) => $.list.badge_registering)}+ </span>+ );+}+// Only public is worth a badge — private is the default and rendering a// `🔒 Private` chip on every row turns the whole column into noise.function VisibilityBadge({ runtime }: { runtime: AgentRuntime }) {@@ -244,8 +266,27 @@ function HealthCell({workload: RuntimeWorkload;now: number;}) {+ const { t } = useT("runtimes");const { t: tAgents } = useT("agents");const labelOf = useHealthLabel();+ if (isPendingCustomRuntime(runtime)) {+ const warning = isPendingCustomRuntimeWarning(runtime, now);+ return (+ <ListGridCell className="gap-1.5">+ {warning ? (+ <AlertTriangle className="h-3.5 w-3.5 shrink-0 text-warning" />+ ) : (+ <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-info" />+ )}+ <span className="block min-w-0 truncate text-xs">+ {warning+ ? t(($) => $.list.pending_health_warning)+ : t(($) => $.list.pending_health)}+ </span>+ </ListGridCell>+ );+ }+const health = deriveRuntimeHealth(runtime, now);const offline = health === "offline" || health === "about_to_gc";const lastSeen = formatLastSeen(runtime.last_seen_at);@@ -328,6 +369,28 @@ export function CostCell({ runtimeId }: { runtimeId: string }) {}export function CliCell({ runtime }: { runtime: AgentRuntime }) {+ const { t } = useT("runtimes");+ if (isPendingCustomRuntime(runtime)) {+ const command = pendingRuntimeCommandName(runtime);+ if (!command) {+ return (+ <span className="text-xs text-muted-foreground/50">+ {t(($) => $.list.pending_cli_unknown)}+ </span>+ );+ }+ return (+ <div className="flex min-w-0 items-center text-xs">+ <span+ className="truncate font-mono text-muted-foreground"+ title={command}+ >+ {command}+ </span>+ </div>+ );+ }+if (runtime.runtime_mode === "cloud") {return <span className="text-xs text-muted-foreground/50">—</span>;}@@ -516,7 +579,9 @@ export function RuntimeList({? memberById.get(runtime.owner_id) ?? null: null,workload: workloadIndex.get(runtime.id) ?? EMPTY_WORKLOAD,- canDelete: isAdmin || (!!user && runtime.owner_id === user.id),+ canDelete:+ !isPendingCustomRuntime(runtime) &&+ (isAdmin || (!!user && runtime.owner_id === user.id)),}));}, [runtimes, memberById, workloadIndex, isAdmin, user]);@@ -553,61 +618,72 @@ export function RuntimeList({</ListGridHeaderCell><span aria-hidden="true" /></ListGridHeader>- {rows.map((row) => (- <ListGridRow- key={row.runtime.id}- className="cursor-pointer"- {...rowLink(wsPaths.runtimeDetail(row.runtime.id))}- >- <RuntimeNameCell runtime={row.runtime} />- <HealthCell- runtime={row.runtime}- workload={row.workload}- now={now}- />- {showOwner ? (- <ListGridCell className="hidden gap-1.5 @2xl:flex">- {row.ownerMember ? (- <>- <ActorAvatar- actorType="member"- actorId={row.ownerMember.user_id}- size={18}- />- <span className="min-w-0 truncate text-xs text-muted-foreground">- {row.ownerMember.name}- </span>- </>+ {rows.map((row) => {+ const pending = isPendingCustomRuntime(row.runtime);+ return (+ <ListGridRow+ key={row.runtime.id}+ className={pending ? "cursor-default" : "cursor-pointer"}+ {...(!pending+ ? rowLink(wsPaths.runtimeDetail(row.runtime.id))+ : {})}+ >+ <RuntimeNameCell runtime={row.runtime} />+ <HealthCell+ runtime={row.runtime}+ workload={row.workload}+ now={now}+ />+ {showOwner ? (+ <ListGridCell className="hidden gap-1.5 @2xl:flex">+ {row.ownerMember ? (+ <>+ <ActorAvatar+ actorType="member"+ actorId={row.ownerMember.user_id}+ size={18}+ />+ <span className="min-w-0 truncate text-xs text-muted-foreground">+ {row.ownerMember.name}+ </span>+ </>+ ) : (+ <span className="text-xs text-muted-foreground/50">—</span>+ )}+ </ListGridCell>+ ) : (+ <ListGridCell className="hidden px-0 @2xl:flex" />+ )}+ <ListGridCell className="hidden @2xl:flex">+ <AgentStack agentIds={row.workload.agentIds} />+ </ListGridCell>+ <ListGridCell className="hidden @2xl:flex">+ {pending ? (+ <div className="w-full text-right">+ <span className="text-xs text-muted-foreground/50">—</span>+ </div>) : (- <span className="text-xs text-muted-foreground/50">—</span>+ <CostCell runtimeId={row.runtime.id} />)}</ListGridCell>- ) : (- <ListGridCell className="hidden px-0 @2xl:flex" />- )}- <ListGridCell className="hidden @2xl:flex">- <AgentStack agentIds={row.workload.agentIds} />- </ListGridCell>- <ListGridCell className="hidden @2xl:flex">- <CostCell runtimeId={row.runtime.id} />- </ListGridCell>- <ListGridCell className="hidden @2xl:flex">- <CliCell runtime={row.runtime} />- </ListGridCell>- <ListGridCell className="justify-end px-0">- <span- onClick={(e) => e.stopPropagation()}- className="flex items-center"- >- <RuntimeRowMenu- runtime={row.runtime}- wsId={wsId}- canDelete={row.canDelete}- />- </span>- </ListGridCell>- </ListGridRow>- ))}+ <ListGridCell className="hidden @2xl:flex">+ <CliCell runtime={row.runtime} />+ </ListGridCell>+ <ListGridCell className="justify-end px-0">+ <span+ onClick={(e) => e.stopPropagation()}+ className="flex items-center"+ >+ <RuntimeRowMenu+ runtime={row.runtime}+ wsId={wsId}+ canDelete={row.canDelete}+ />+ </span>+ </ListGridCell>+ </ListGridRow>+ );+ })}</ListGrid></div>);diff --git a/packages/views/runtimes/components/runtime-profiles-dialog.tsx b/packages/views/runtimes/components/runtime-profiles-dialog.tsxindex 83a9ca3e75..a5ec5b131e 100644--- a/packages/views/runtimes/components/runtime-profiles-dialog.tsx+++ b/packages/views/runtimes/components/runtime-profiles-dialog.tsx@@ -10,6 +10,7 @@ import {Plus,Server,Trash2,+ X,} from "lucide-react";import { toast } from "sonner";import { useQuery } from "@tanstack/react-query";@@ -26,6 +27,7 @@ import {import { Button } from "@multica/ui/components/ui/button";import {Dialog,+ DialogClose,DialogContent,DialogDescription,DialogHeader,@@ -58,9 +60,11 @@ type DialogState =export function RuntimeProfilesDialog({wsId,+ onProfileCreated,onClose,}: {wsId: string;+ onProfileCreated?: (profile: RuntimeProfile) => void;onClose: () => void;}) {const { t } = useT("runtimes");@@ -86,24 +90,43 @@ export function RuntimeProfilesDialog({return (<Dialog open onOpenChange={(open) => !open && onClose()}>- <DialogContent className="flex max-h-[88vh] flex-col gap-0 p-0 sm:max-w-3xl">+ <DialogContent+ className="flex max-h-[88vh] flex-col gap-0 p-0 sm:max-w-3xl"+ showCloseButton={false}+ ><DialogHeader className="border-b px-6 py-5"><div className="flex items-start justify-between gap-3"><DialogTitle className="flex min-w-0 items-center gap-2 text-base"><Server className="h-4 w-4 shrink-0 text-muted-foreground" /><span className="truncate">{t(($) => $.profiles.dialog_title)}</span></DialogTitle>- {state.surface === "browse" && (- <Button- type="button"- size="sm"- className="h-8 shrink-0 px-2.5"- onClick={openCreateForm}+ <div className="flex shrink-0 items-center gap-2">+ {state.surface === "browse" && (+ <Button+ type="button"+ size="sm"+ className="h-8 px-2.5"+ onClick={openCreateForm}+ >+ <Plus className="h-3.5 w-3.5" />+ {t(($) => $.profiles.add_new)}+ </Button>+ )}+ <DialogClose+ render={+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ className="shrink-0"+ aria-label={t(($) => $.profiles.close)}+ />+ }>- <Plus className="h-3.5 w-3.5" />- {t(($) => $.profiles.add_new)}- </Button>- )}+ <X className="h-4 w-4" />+ <span className="sr-only">{t(($) => $.profiles.close)}</span>+ </DialogClose>+ </div></div><DialogDescription className="text-xs">{t(($) => $.profiles.dialog_description)}@@ -132,6 +155,9 @@ export function RuntimeProfilesDialog({}}onCancel={() => setState({ surface: "browse" })}onSaved={(profile) => {+ if (state.surface === "form" && state.mode === "create") {+ onProfileCreated?.(profile);+ }setSelectedId(profile.id);setState({ surface: "browse" });}}diff --git a/packages/views/runtimes/components/runtimes-page.tsx b/packages/views/runtimes/components/runtimes-page.tsxindex 9fe54fd3d6..e215ef3165 100644--- a/packages/views/runtimes/components/runtimes-page.tsx+++ b/packages/views/runtimes/components/runtimes-page.tsx@@ -34,6 +34,10 @@ import { CloudRuntimeDialog } from "./cloud-runtime-dialog";import { RuntimeProfilesDialog } from "./runtime-profiles-dialog";import { ProviderLogo } from "./provider-logo";import { RuntimeList, buildWorkloadIndex } from "./runtime-list";+import {+ pendingRuntimesForProfiles,+ type PendingRuntimeProfile,+} from "./pending-runtime";import {buildRuntimeMachines,filterRuntimeMachines,@@ -92,6 +96,8 @@ export function RuntimesPage({cloudRuntimeEnabled = false,}: RuntimesPageProps = {}) {const isLoading = useAuthStore((s) => s.isLoading);+ const { t } = useT("runtimes");+ const pendingMachineName = t(($) => $.machine.pending_custom_runtimes);const currentUserId = useAuthStore((s) => s.user?.id);const wsId = useWorkspaceId();const qc = useQueryClient();@@ -111,6 +117,9 @@ export function RuntimesPage({}, []);const [showConnectDialog, setShowConnectDialog] = useState(false);const [showCloudRuntimeDialog, setShowCloudRuntimeDialog] = useState(false);+ const [pendingProfiles, setPendingProfiles] = useState<PendingRuntimeProfile[]>(+ [],+ );const { defaultLayout, onLayoutChanged } = useDefaultLayout({id: "multica_runtimes_layout",});@@ -140,6 +149,42 @@ export function RuntimesPage({const updatableIds = useUpdatableRuntimeIds(wsId);const now = useNowTick();+ useEffect(() => {+ if (pendingProfiles.length === 0) return;+ const registeredProfileIds = new Set(+ runtimes+ .map((runtime) => runtime.profile_id)+ .filter((profileId): profileId is string => !!profileId),+ );+ if (registeredProfileIds.size === 0) return;+ setPendingProfiles((current) => {+ const next = current.filter(+ ({ profile }) => !registeredProfileIds.has(profile.id),+ );+ return next.length === current.length ? current : next;+ });+ }, [pendingProfiles.length, runtimes]);++ const visibleRuntimes = useMemo(+ () =>+ pendingRuntimesForProfiles({+ pendingProfiles,+ runtimes,+ ownerId: currentUserId,+ localDaemonId,+ localMachineName,+ fallbackMachineName: pendingMachineName,+ }),+ [+ pendingProfiles,+ runtimes,+ currentUserId,+ localDaemonId,+ localMachineName,+ pendingMachineName,+ ],+ );+const workloadIndex = useMemo(() => buildWorkloadIndex(agents, snapshot),[agents, snapshot],@@ -147,7 +192,7 @@ export function RuntimesPage({const machines = useMemo(() =>- buildRuntimeMachines(runtimes, {+ buildRuntimeMachines(visibleRuntimes, {now,localDaemonId,localMachineName,@@ -156,7 +201,7 @@ export function RuntimesPage({ensureLocalMachine: hasLocalMachine,}),[- runtimes,+ visibleRuntimes,now,localDaemonId,localMachineName,@@ -197,7 +242,7 @@ export function RuntimesPage({if (isLoading || fetching) return <RuntimesPageSkeleton />;- const totalCount = runtimes.length;+ const totalCount = visibleRuntimes.length;// Desktop always has a synthesized local machine row, so the// "register a runtime" empty state would hide the Start button.const showEmpty = totalCount === 0 && !bootstrapping && !hasLocalMachine;@@ -293,6 +338,12 @@ export function RuntimesPage({{canManageProfiles && showProfilesDialog && (<RuntimeProfilesDialogwsId={wsId}+ onProfileCreated={(profile) =>+ setPendingProfiles((current) => [+ ...current.filter((item) => item.profile.id !== profile.id),+ { profile, createdAt: Date.now() },+ ])+ }onClose={() => setShowProfilesDialog(false)}/>)}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 99d0e6c62b..3ba8cb455a 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -168,6 +168,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus}if opts.DaemonWakeup != nil {h.TaskService.Wakeup = opts.DaemonWakeup+ if notifier, ok := opts.DaemonWakeup.(handler.RuntimeProfileRefreshNotifier); ok {+ h.DaemonProfileRefresh = notifier+ }}if rdb != nil {h.UpdateStore = handler.NewRedisUpdateStore(rdb)diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.goindex 21dbbd9707..ea2d374274 100644--- a/server/internal/daemon/wakeup.go+++ b/server/internal/daemon/wakeup.go@@ -284,6 +284,17 @@ func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<-d.logger.Debug("task wakeup received", "runtime_id", payload.RuntimeID, "task_id", payload.TaskID)}signalTaskWakeup(taskWakeups, payload.RuntimeID)+ case protocol.EventDaemonRuntimeProfilesChanged:+ var payload protocol.RuntimeProfilesChangedPayload+ if err := json.Unmarshal(msg.Payload, &payload); err != nil {+ d.logger.Debug("runtime profile refresh websocket invalid payload", "error", err)+ continue+ }+ if payload.WorkspaceID == "" {+ d.logger.Debug("runtime profile refresh websocket missing workspace_id")+ continue+ }+ go d.handleRuntimeProfilesChanged(payload)case protocol.EventDaemonHeartbeatAck:var ack HeartbeatResponseif err := json.Unmarshal(msg.Payload, &ack); err != nil {@@ -295,6 +306,18 @@ func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<-}}+func (d *Daemon) handleRuntimeProfilesChanged(payload protocol.RuntimeProfilesChangedPayload) {+ if payload.WorkspaceID == "" {+ return+ }+ if err := d.refreshWorkspaceRuntimeProfiles(d.recoveryContext(), payload.WorkspaceID); err != nil {+ d.logger.Debug("runtime profile refresh websocket hint failed",+ "workspace_id", payload.WorkspaceID,+ "runtime_profile_id", payload.RuntimeProfileID,+ "error", err)+ }+}+func signalTaskWakeup(taskWakeups chan<- taskWakeup, runtimeID string) {select {case taskWakeups <- taskWakeup{runtimeID: runtimeID}:diff --git a/server/internal/daemonws/hub.go b/server/internal/daemonws/hub.goindex 0c639c22c4..6e240bb84e 100644--- a/server/internal/daemonws/hub.go+++ b/server/internal/daemonws/hub.go@@ -21,13 +21,67 @@ const (// ClientIdentity captures the already-authenticated daemon connection scope.type ClientIdentity struct {- DaemonID string- UserID string+ DaemonID string+ UserID string+ // WorkspaceID is the legacy single-workspace scope used by older callers+ // and daemon-token auth. New code should populate WorkspaceIDs from the+ // runtime rows authorized for this connection.WorkspaceID string+ WorkspaceIDs []stringRuntimeIDs []stringClientVersion string}+// AuthorizedWorkspaceIDs returns the connection's workspace scope in stable+// order, preferring the multi-workspace field and falling back to WorkspaceID+// for older tests/callers.+func (i ClientIdentity) AuthorizedWorkspaceIDs() []string {+ seen := make(map[string]struct{}, len(i.WorkspaceIDs)+1)+ out := make([]string, 0, len(i.WorkspaceIDs)+1)+ add := func(id string) {+ id = strings.TrimSpace(id)+ if id == "" {+ return+ }+ if _, ok := seen[id]; ok {+ return+ }+ seen[id] = struct{}{}+ out = append(out, id)+ }+ for _, id := range i.WorkspaceIDs {+ add(id)+ }+ if len(out) == 0 {+ add(i.WorkspaceID)+ }+ return out+}++func (i ClientIdentity) PrimaryWorkspaceID() string {+ ids := i.AuthorizedWorkspaceIDs()+ if len(ids) == 0 {+ return ""+ }+ return ids[0]+}++// AllowsWorkspace reports whether workspaceID is within the connection scope.+// An empty scope remains permissive for legacy unit tests that construct+// ClientIdentity directly without workspace data.+func (i ClientIdentity) AllowsWorkspace(workspaceID string) bool {+ ids := i.AuthorizedWorkspaceIDs()+ if len(ids) == 0 {+ return true+ }+ for _, id := range ids {+ if id == workspaceID {+ return true+ }+ }+ return false+}+type client struct {hub *Hubconn *websocket.Conn@@ -85,9 +139,10 @@ type MessageKindRecorder interface {type Hub struct {upgrader websocket.Upgrader- mu sync.RWMutex- clients map[*client]bool- byRuntime map[string]map[*client]bool+ mu sync.RWMutex+ clients map[*client]bool+ byRuntime map[string]map[*client]bool+ byWorkspace map[string]map[*client]boolhbMu sync.RWMutexonHeartbeat HeartbeatHandler@@ -106,8 +161,9 @@ func NewHub() *Hub {// grows cookie fallback.CheckOrigin: func(r *http.Request) bool { return true },},- clients: make(map[*client]bool),- byRuntime: make(map[string]map[*client]bool),+ clients: make(map[*client]bool),+ byRuntime: make(map[string]map[*client]bool),+ byWorkspace: make(map[string]map[*client]bool),}}@@ -194,6 +250,12 @@ func (h *Hub) NotifyTaskAvailable(runtimeID, taskID string) {h.notifyTaskAvailable(runtimeID, taskID, "")}+// NotifyRuntimeProfilesChanged asks connected daemons in workspaceID to pull+// runtime profiles now instead of waiting for their periodic sync loop.+func (h *Hub) NotifyRuntimeProfilesChanged(workspaceID, profileID string) {+ h.notifyRuntimeProfilesChanged(workspaceID, profileID, "")+}+func (h *Hub) notifyTaskAvailable(runtimeID, taskID, eventID string) {if h == nil || runtimeID == "" {return@@ -210,6 +272,17 @@ func (h *Hub) notifyTaskAvailable(runtimeID, taskID, eventID string) {}}+func (h *Hub) notifyRuntimeProfilesChanged(workspaceID, profileID, eventID string) {+ if h == nil || workspaceID == "" {+ return+ }+ data, err := runtimeProfilesChangedFrame(workspaceID, profileID)+ if err != nil {+ return+ }+ h.notifyWorkspaceFrame(workspaceID, data, eventID)+}+func (h *Hub) DeliverDaemonRuntime(scopeID string, frame []byte, eventID string) {if h == nil {return@@ -221,22 +294,37 @@ func (h *Hub) DeliverDaemonRuntime(scopeID string, frame []byte, eventID string)M.WakeupDeliveredMiss.Add(1)return}- if msg.Type != protocol.EventDaemonTaskAvailable {- M.WakeupDeliveredMiss.Add(1)- return- }- var payload protocol.TaskAvailablePayload- if err := json.Unmarshal(msg.Payload, &payload); err != nil || payload.RuntimeID == "" {- slog.Debug("daemon websocket relay: invalid task_available payload", "error", err, "scope_id", scopeID, "event_id", eventID)+ switch msg.Type {+ case protocol.EventDaemonTaskAvailable:+ var payload protocol.TaskAvailablePayload+ if err := json.Unmarshal(msg.Payload, &payload); err != nil || payload.RuntimeID == "" {+ slog.Debug("daemon websocket relay: invalid task_available payload", "error", err, "scope_id", scopeID, "event_id", eventID)+ M.WakeupDeliveredMiss.Add(1)+ return+ }+ delivered, deduped := h.notifyFrame(payload.RuntimeID, frame, eventID)+ if delivered {+ M.WakeupDeliveredHit.Add(1)+ } else if !deduped {+ M.WakeupDeliveredMiss.Add(1)+ }+ case protocol.EventDaemonRuntimeProfilesChanged:+ var payload protocol.RuntimeProfilesChangedPayload+ if err := json.Unmarshal(msg.Payload, &payload); err != nil || payload.WorkspaceID == "" {+ slog.Debug("daemon websocket relay: invalid runtime_profiles_changed payload", "error", err, "scope_id", scopeID, "event_id", eventID)+ M.WakeupDeliveredMiss.Add(1)+ return+ }+ delivered, deduped := h.notifyWorkspaceFrame(payload.WorkspaceID, frame, eventID)+ if delivered {+ M.WakeupDeliveredHit.Add(1)+ } else if !deduped {+ M.WakeupDeliveredMiss.Add(1)+ }+ default:M.WakeupDeliveredMiss.Add(1)return}- delivered, deduped := h.notifyFrame(payload.RuntimeID, frame, eventID)- if delivered {- M.WakeupDeliveredHit.Add(1)- } else if !deduped {- M.WakeupDeliveredMiss.Add(1)- }}func (h *Hub) notifyFrame(runtimeID string, data []byte, eventID string) (delivered bool, deduped bool) {@@ -267,6 +355,34 @@ func (h *Hub) notifyFrame(runtimeID string, data []byte, eventID string) (delivereturn delivered, deduped}+func (h *Hub) notifyWorkspaceFrame(workspaceID string, data []byte, eventID string) (delivered bool, deduped bool) {+ h.mu.RLock()+ clients := h.byWorkspace[workspaceID]+ slow := make([]*client, 0)+ for c := range clients {+ if !c.markSeen(eventID) {+ deduped = true+ continue+ }+ select {+ case c.send <- data:+ delivered = true+ default:+ slow = append(slow, c)+ }+ }+ h.mu.RUnlock()++ for _, c := range slow {+ h.unregister(c)+ c.conn.Close()+ }+ if len(slow) > 0 {+ M.SlowEvictionsTotal.Add(int64(len(slow)))+ }+ return delivered, deduped+}+func taskAvailableFrame(runtimeID, taskID string) ([]byte, error) {return json.Marshal(protocol.Message{Type: protocol.EventDaemonTaskAvailable,@@ -277,6 +393,16 @@ func taskAvailableFrame(runtimeID, taskID string) ([]byte, error) {})}+func runtimeProfilesChangedFrame(workspaceID, profileID string) ([]byte, error) {+ return json.Marshal(protocol.Message{+ Type: protocol.EventDaemonRuntimeProfilesChanged,+ Payload: mustMarshalRaw(protocol.RuntimeProfilesChangedPayload{+ WorkspaceID: workspaceID,+ RuntimeProfileID: profileID,+ }),+ })+}+func mustMarshalRaw(v any) json.RawMessage {data, err := json.Marshal(v)if err != nil {@@ -291,6 +417,12 @@ func (h *Hub) RuntimeConnectionCount(runtimeID string) int {return len(h.byRuntime[runtimeID])}+func (h *Hub) WorkspaceConnectionCount(workspaceID string) int {+ h.mu.RLock()+ defer h.mu.RUnlock()+ return len(h.byWorkspace[workspaceID])+}+func (h *Hub) register(c *client) {h.mu.Lock()h.clients[c] = true@@ -302,6 +434,15 @@ func (h *Hub) register(c *client) {}conns[c] = true}+ workspaceIDs := c.identity.AuthorizedWorkspaceIDs()+ for _, workspaceID := range workspaceIDs {+ conns := h.byWorkspace[workspaceID]+ if conns == nil {+ conns = make(map[*client]bool)+ h.byWorkspace[workspaceID] = conns+ }+ conns[c] = true+ }total := len(h.clients)h.mu.Unlock()@@ -310,7 +451,8 @@ func (h *Hub) register(c *client) {slog.Info("daemon websocket connected","daemon_id", c.identity.DaemonID,"user_id", c.identity.UserID,- "workspace_id", c.identity.WorkspaceID,+ "workspace_id", c.identity.PrimaryWorkspaceID(),+ "workspace_ids", workspaceIDs,"runtimes", len(c.runtimes),"client_version", c.identity.ClientVersion,"total_clients", total,@@ -332,6 +474,15 @@ func (h *Hub) unregister(c *client) {}}}+ workspaceIDs := c.identity.AuthorizedWorkspaceIDs()+ for _, workspaceID := range workspaceIDs {+ if conns := h.byWorkspace[workspaceID]; conns != nil {+ delete(conns, c)+ if len(conns) == 0 {+ delete(h.byWorkspace, workspaceID)+ }+ }+ }close(c.send)total := len(h.clients)h.mu.Unlock()@@ -341,7 +492,8 @@ func (h *Hub) unregister(c *client) {slog.Info("daemon websocket disconnected","daemon_id", c.identity.DaemonID,"user_id", c.identity.UserID,- "workspace_id", c.identity.WorkspaceID,+ "workspace_id", c.identity.PrimaryWorkspaceID(),+ "workspace_ids", workspaceIDs,"runtimes", len(c.runtimes),"total_clients", total,)diff --git a/server/internal/daemonws/hub_test.go b/server/internal/daemonws/hub_test.goindex e4075359e5..a9160f92c1 100644--- a/server/internal/daemonws/hub_test.go+++ b/server/internal/daemonws/hub_test.go@@ -67,6 +67,124 @@ func TestNotifyTaskAvailable(t *testing.T) {}}+func TestNotifyRuntimeProfilesChanged(t *testing.T) {+ M.Reset()+ defer M.Reset()++ hub := NewHub()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hub.HandleWebSocket(w, r, ClientIdentity{+ WorkspaceID: "ws-1",+ RuntimeIDs: []string{"runtime-1"},+ })+ }))+ defer server.Close()++ wsURL := "ws" + strings.TrimPrefix(server.URL, "http")+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)+ if err != nil {+ t.Fatalf("Dial: %v", err)+ }+ defer conn.Close()++ deadline := time.Now().Add(time.Second)+ for hub.WorkspaceConnectionCount("ws-1") == 0 {+ if time.Now().After(deadline) {+ t.Fatal("workspace connection was not registered")+ }+ time.Sleep(10 * time.Millisecond)+ }++ hub.NotifyRuntimeProfilesChanged("ws-1", "profile-1")++ if err := conn.SetReadDeadline(time.Now().Add(time.Second)); err != nil {+ t.Fatalf("SetReadDeadline: %v", err)+ }+ _, raw, err := conn.ReadMessage()+ if err != nil {+ t.Fatalf("ReadMessage: %v", err)+ }++ var msg protocol.Message+ if err := json.Unmarshal(raw, &msg); err != nil {+ t.Fatalf("unmarshal message: %v", err)+ }+ if msg.Type != protocol.EventDaemonRuntimeProfilesChanged {+ t.Fatalf("message type = %q, want %q", msg.Type, protocol.EventDaemonRuntimeProfilesChanged)+ }++ var payload protocol.RuntimeProfilesChangedPayload+ if err := json.Unmarshal(msg.Payload, &payload); err != nil {+ t.Fatalf("unmarshal payload: %v", err)+ }+ if payload.WorkspaceID != "ws-1" || payload.RuntimeProfileID != "profile-1" {+ t.Fatalf("payload = %+v, want workspace/profile IDs", payload)+ }+}++func TestNotifyRuntimeProfilesChangedIndexesAllAuthorizedWorkspaces(t *testing.T) {+ M.Reset()+ defer M.Reset()++ hub := NewHub()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hub.HandleWebSocket(w, r, ClientIdentity{+ WorkspaceIDs: []string{"ws-1", "ws-2"},+ RuntimeIDs: []string{"runtime-1", "runtime-2"},+ })+ }))+ defer server.Close()++ wsURL := "ws" + strings.TrimPrefix(server.URL, "http")+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)+ if err != nil {+ t.Fatalf("Dial: %v", err)+ }+ defer conn.Close()++ deadline := time.Now().Add(time.Second)+ for hub.WorkspaceConnectionCount("ws-1") == 0 || hub.WorkspaceConnectionCount("ws-2") == 0 {+ if time.Now().After(deadline) {+ t.Fatalf("workspace connections not registered: ws-1=%d ws-2=%d",+ hub.WorkspaceConnectionCount("ws-1"),+ hub.WorkspaceConnectionCount("ws-2"))+ }+ time.Sleep(10 * time.Millisecond)+ }+ if got := hub.WorkspaceConnectionCount("ws-3"); got != 0 {+ t.Fatalf("workspace ws-3 connection count = %d, want 0", got)+ }++ hub.NotifyRuntimeProfilesChanged("ws-1", "profile-1")+ hub.NotifyRuntimeProfilesChanged("ws-2", "profile-2")++ got := map[string]string{}+ if err := conn.SetReadDeadline(time.Now().Add(time.Second)); err != nil {+ t.Fatalf("SetReadDeadline: %v", err)+ }+ for len(got) < 2 {+ _, raw, err := conn.ReadMessage()+ if err != nil {+ t.Fatalf("ReadMessage: %v", err)+ }+ var msg protocol.Message+ if err := json.Unmarshal(raw, &msg); err != nil {+ t.Fatalf("unmarshal message: %v", err)+ }+ if msg.Type != protocol.EventDaemonRuntimeProfilesChanged {+ t.Fatalf("message type = %q, want %q", msg.Type, protocol.EventDaemonRuntimeProfilesChanged)+ }+ var payload protocol.RuntimeProfilesChangedPayload+ if err := json.Unmarshal(msg.Payload, &payload); err != nil {+ t.Fatalf("unmarshal payload: %v", err)+ }+ got[payload.WorkspaceID] = payload.RuntimeProfileID+ }+ if got["ws-1"] != "profile-1" || got["ws-2"] != "profile-2" {+ t.Fatalf("profile refresh payloads = %+v, want ws-1/profile-1 and ws-2/profile-2", got)+ }+}+func TestRelayNotifierPublishesDaemonRuntimeScope(t *testing.T) {M.Reset()defer M.Reset()@@ -105,6 +223,44 @@ func TestRelayNotifierPublishesDaemonRuntimeScope(t *testing.T) {}}+func TestRelayNotifierPublishesRuntimeProfilesChanged(t *testing.T) {+ M.Reset()+ defer M.Reset()++ relay := &recordingRelayPublisher{}+ notifier := NewRelayNotifier(nil, relay)++ notifier.NotifyRuntimeProfilesChanged("ws-1", "profile-1")++ if relay.scopeType != realtime.ScopeDaemonRuntime {+ t.Fatalf("scopeType = %q, want %q", relay.scopeType, realtime.ScopeDaemonRuntime)+ }+ if relay.scopeID != "ws-1" {+ t.Fatalf("scopeID = %q, want workspace shard key", relay.scopeID)+ }+ if relay.eventID == "" {+ t.Fatal("expected event id")+ }+ if M.WakeupPublishedTotal.Load() != 1 {+ t.Fatalf("published metric = %d, want 1", M.WakeupPublishedTotal.Load())+ }++ var msg protocol.Message+ if err := json.Unmarshal(relay.frame, &msg); err != nil {+ t.Fatalf("unmarshal frame: %v", err)+ }+ if msg.Type != protocol.EventDaemonRuntimeProfilesChanged {+ t.Fatalf("message type = %q, want %q", msg.Type, protocol.EventDaemonRuntimeProfilesChanged)+ }+ var payload protocol.RuntimeProfilesChangedPayload+ if err := json.Unmarshal(msg.Payload, &payload); err != nil {+ t.Fatalf("unmarshal payload: %v", err)+ }+ if payload.WorkspaceID != "ws-1" || payload.RuntimeProfileID != "profile-1" {+ t.Fatalf("payload = %+v, want workspace/profile IDs", payload)+ }+}+func TestRelayNotifierDedupsLocalRedisLoopback(t *testing.T) {M.Reset()defer M.Reset()@@ -141,6 +297,42 @@ func TestRelayNotifierDedupsLocalRedisLoopback(t *testing.T) {}}+func TestRelayNotifierDedupsRuntimeProfilesChangedLoopback(t *testing.T) {+ M.Reset()+ defer M.Reset()++ hub := NewHub()+ client := attachDaemonWorkspaceTestClient(hub, "ws-1")+ relay := &localFirstDaemonRelayPublisher{t: t, client: client}+ notifier := NewRelayNotifier(hub, relay)++ notifier.NotifyRuntimeProfilesChanged("ws-1", "profile-1")++ if !relay.called {+ t.Fatal("expected relay publish to be invoked")+ }+ if relay.eventID == "" {+ t.Fatal("expected event id")+ }+ if M.WakeupDeliveredHit.Load() != 0 {+ t.Fatalf("delivered hit metric = %d, want 0 before redis relay delivery", M.WakeupDeliveredHit.Load())+ }++ hub.DeliverDaemonRuntime(relay.scopeID, relay.frame, relay.eventID)++ select {+ case duplicate := <-client.send:+ t.Fatalf("expected redis loopback to be deduped, got duplicate %s", duplicate)+ case <-time.After(20 * time.Millisecond):+ }+ if M.WakeupDeliveredHit.Load() != 0 {+ t.Fatalf("delivered hit metric after loopback = %d, want 0", M.WakeupDeliveredHit.Load())+ }+ if M.WakeupDeliveredMiss.Load() != 0 {+ t.Fatalf("delivered miss metric after dedup = %d, want 0", M.WakeupDeliveredMiss.Load())+ }+}+// TestHeartbeatRoundTrip pins the WS heartbeat contract: a daemon:heartbeat// frame invokes the registered HeartbeatHandler with the runtime ID, and the// hub serializes the returned ack as a daemon:heartbeat_ack on the wire.@@ -346,6 +538,21 @@ func attachDaemonTestClient(hub *Hub, runtimeID string) *client {return c}+func attachDaemonWorkspaceTestClient(hub *Hub, workspaceID string) *client {+ c := &client{+ send: make(chan []byte, 2),+ identity: ClientIdentity{WorkspaceIDs: []string{workspaceID}},+ runtimes: map[string]struct{}{},+ }++ hub.mu.Lock()+ hub.clients[c] = true+ hub.byWorkspace[workspaceID] = map[*client]bool{c: true}+ hub.mu.Unlock()++ return c+}+type recordingRelayPublisher struct {scopeType stringscopeID stringdiff --git a/server/internal/daemonws/notifier.go b/server/internal/daemonws/notifier.goindex c1d1f51cdb..f66f4b623d 100644--- a/server/internal/daemonws/notifier.go+++ b/server/internal/daemonws/notifier.go@@ -8,9 +8,9 @@ import ("github.com/multica-ai/multica/server/internal/realtime")-// RelayNotifier sends task wakeups to the local daemon hub and, when Redis is-// configured, publishes the same wakeup through the shared realtime relay so-// every API node can attempt local delivery.+// RelayNotifier sends daemon wakeup hints to the local daemon hub and, when+// Redis is configured, publishes the same hint through the shared realtime+// relay so every API node can attempt local delivery.type RelayNotifier struct {local *Hubrelay realtime.RelayPublisher@@ -47,3 +47,27 @@ func (n *RelayNotifier) NotifyTaskAvailable(runtimeID, taskID string) {}M.WakeupPublishedTotal.Add(1)}++func (n *RelayNotifier) NotifyRuntimeProfilesChanged(workspaceID, profileID string) {+ if workspaceID == "" {+ return+ }+ eventID := ulid.Make().String()+ if n.local != nil {+ n.local.notifyRuntimeProfilesChanged(workspaceID, profileID, eventID)+ }+ if n.relay == nil {+ return+ }+ frame, err := runtimeProfilesChangedFrame(workspaceID, profileID)+ if err != nil {+ M.WakeupPublishErrors.Add(1)+ return+ }+ if err := n.relay.PublishWithID(realtime.ScopeDaemonRuntime, workspaceID, "", frame, eventID); err != nil {+ M.WakeupPublishErrors.Add(1)+ slog.Warn("daemon websocket profile refresh publish failed", "error", err, "workspace_id", workspaceID, "runtime_profile_id", profileID)+ return+ }+ M.WakeupPublishedTotal.Add(1)+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 0a9bcd6a1a..95c89f8268 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -874,7 +874,7 @@ func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonws}return nil, fmt.Errorf("get agent runtime: %w", err)}- if identity.WorkspaceID != "" && identity.WorkspaceID != uuidToString(rt.WorkspaceID) {+ if !identity.AllowsWorkspace(uuidToString(rt.WorkspaceID)) {return nil, fmt.Errorf("runtime not in connection workspace")}ack, _, err := h.processHeartbeat(ctx, rt, supportsBatchImport)diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex f17a0143ef..cffbc82a9a 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -594,6 +594,51 @@ func TestHandleDaemonWSHeartbeat_RuntimeGoneReturnsAckNotError(t *testing.T) {}}+func TestHandleDaemonWSHeartbeat_AllowsAnyAuthorizedWorkspace(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ slug := "handler-ws-heartbeat-" + uuid.New().String()+ var workspaceID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug, description, issue_prefix)+ VALUES ($1, $2, $3, $4)+ RETURNING id+ `, "WS Heartbeat Scope", slug, "Temporary workspace for WS heartbeat tests", "HWS").Scan(&workspaceID); err != nil {+ t.Fatalf("setup: create workspace: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, workspaceID)+ })++ var runtimeID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_runtime (+ workspace_id, daemon_id, name, runtime_mode, provider,+ status, device_info, metadata, owner_id, last_seen_at+ )+ VALUES ($1, NULL, $2, 'cloud', $3, 'online', $4, '{}'::jsonb, $5, now())+ RETURNING id+ `, workspaceID, "WS Heartbeat Runtime", "handler_test_runtime", "WS heartbeat runtime", testUserID).Scan(&runtimeID); err != nil {+ t.Fatalf("setup: create runtime: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)+ })++ ack, err := testHandler.HandleDaemonWSHeartbeat(ctx,+ daemonws.ClientIdentity{WorkspaceIDs: []string{testWorkspaceID, workspaceID}},+ runtimeID, false)+ if err != nil {+ t.Fatalf("HandleDaemonWSHeartbeat: unexpected error %v", err)+ }+ if ack == nil || ack.RuntimeID != runtimeID {+ t.Fatalf("ack = %+v, want runtime_id %q", ack, runtimeID)+ }+}+// TestDaemonHeartbeat_HTTPRuntimeGoneReturns404 pins the HTTP-path mirror:// pgx.ErrNoRows on the runtime lookup is the only DB error mapped to 404.// Anything else (transient pool issue, schema mismatch, ...) must surfacediff --git a/server/internal/handler/daemon_ws.go b/server/internal/handler/daemon_ws.goindex 869e1a13d0..a3f60ff7a9 100644--- a/server/internal/handler/daemon_ws.go+++ b/server/internal/handler/daemon_ws.go@@ -20,6 +20,8 @@ func (h *Handler) DaemonWebSocket(w http.ResponseWriter, r *http.Request) {return}+ workspaceIDs := make([]string, 0, len(runtimeIDs))+ seenWorkspaceIDs := make(map[string]struct{}, len(runtimeIDs))for _, runtimeID := range runtimeIDs {rt, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID)if !ok {@@ -29,12 +31,25 @@ func (h *Handler) DaemonWebSocket(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "runtime not found")return}+ workspaceID := uuidToString(rt.WorkspaceID)+ if workspaceID != "" {+ if _, ok := seenWorkspaceIDs[workspaceID]; !ok {+ seenWorkspaceIDs[workspaceID] = struct{}{}+ workspaceIDs = append(workspaceIDs, workspaceID)+ }+ }+ }++ primaryWorkspaceID := ""+ if len(workspaceIDs) > 0 {+ primaryWorkspaceID = workspaceIDs[0]}h.DaemonHub.HandleWebSocket(w, r, daemonws.ClientIdentity{DaemonID: middleware.DaemonIDFromContext(r.Context()),UserID: requestUserID(r),- WorkspaceID: middleware.DaemonWorkspaceIDFromContext(r.Context()),+ WorkspaceID: primaryWorkspaceID,+ WorkspaceIDs: workspaceIDs,RuntimeIDs: runtimeIDs,ClientVersion: r.Header.Get("X-Client-Version"),})diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex df37d2df62..dd66ad51ba 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -91,12 +91,17 @@ type cloudRuntimeProxy interface {Do(ctx context.Context, req cloudruntime.Request) (*cloudruntime.Response, error)}+type RuntimeProfileRefreshNotifier interface {+ NotifyRuntimeProfilesChanged(workspaceID, profileID string)+}+type Handler struct {Queries *db.QueriesDB dbExecutorTxStarter txStarterHub *realtime.HubDaemonHub *daemonws.Hub+ DaemonProfileRefresh RuntimeProfileRefreshNotifierBus *events.BusTaskService *service.TaskServiceIssueService *service.IssueService@@ -181,6 +186,10 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventif len(daemonHubs) > 0 {daemonHub = daemonHubs[0]}+ var daemonProfileRefresh RuntimeProfileRefreshNotifier+ if daemonHub != nil {+ daemonProfileRefresh = daemonHub+ }taskSvc := service.NewTaskService(queries, txStarter, hub, bus, daemonHub)taskSvc.Analytics = analyticsClient@@ -190,6 +199,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventTxStarter: txStarter,Hub: hub,DaemonHub: daemonHub,+ DaemonProfileRefresh: daemonProfileRefresh,Bus: bus,TaskService: taskSvc,IssueService: service.NewIssueService(queries, txStarter, bus, analyticsClient, taskSvc),diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.goindex 393c918094..a2e3e5c3c1 100644--- a/server/internal/handler/runtime_profile.go+++ b/server/internal/handler/runtime_profile.go@@ -172,8 +172,10 @@ func (h *Handler) CreateRuntimeProfile(w http.ResponseWriter, r *http.Request) {return}+ profileID := uuidToString(profile.ID)+ h.requestDaemonRuntimeProfileRefresh(wsID, profileID)h.publish(protocol.EventDaemonRegister, wsID, "member", uuidToString(member.UserID), map[string]any{- "runtime_profile_id": uuidToString(profile.ID),+ "runtime_profile_id": profileID,})writeJSON(w, http.StatusCreated, runtimeProfileToResponse(profile))@@ -308,8 +310,10 @@ func (h *Handler) UpdateRuntimeProfile(w http.ResponseWriter, r *http.Request) {return}+ profileID := uuidToString(profile.ID)+ h.requestDaemonRuntimeProfileRefresh(wsID, profileID)h.publish(protocol.EventDaemonRegister, wsID, "member", uuidToString(member.UserID), map[string]any{- "runtime_profile_id": uuidToString(profile.ID),+ "runtime_profile_id": profileID,})writeJSON(w, http.StatusOK, runtimeProfileToResponse(profile))@@ -440,8 +444,10 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {}// Tell connected clients to refetch the runtime list (instances vanished).+ profileID := uuidToString(profileUUID)+ h.requestDaemonRuntimeProfileRefresh(wsID, profileID)h.publish(protocol.EventDaemonRegister, wsID, "member", uuidToString(member.UserID), map[string]any{- "deleted_runtime_profile_id": uuidToString(profileUUID),+ "deleted_runtime_profile_id": profileID,})w.WriteHeader(http.StatusNoContent)@@ -475,3 +481,10 @@ func (h *Handler) DaemonListRuntimeProfiles(w http.ResponseWriter, r *http.Reque"runtime_profiles": resp,})}++func (h *Handler) requestDaemonRuntimeProfileRefresh(workspaceID, profileID string) {+ if h.DaemonProfileRefresh == nil {+ return+ }+ h.DaemonProfileRefresh.NotifyRuntimeProfilesChanged(workspaceID, profileID)+}diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex dd2cecd67b..2d2881f1c5 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -30,15 +30,15 @@ const (// subscribes by `task:` prefix and invalidates the workspace task// snapshot, so the granularity here is "what does the user want to see// change" — not "every internal status flip".- EventTaskQueued = "task:queued" // ∅ → queued (enqueue / retry create)- EventTaskDispatch = "task:dispatch" // queued → dispatched (daemon claim)- EventTaskRunning = "task:running" // dispatched → running (daemon started)- EventTaskWaitingLocalDirectory = "task:waiting_local_directory" // dispatched → waiting_local_directory (daemon parked on a busy local_directory path)- EventTaskProgress = "task:progress"- EventTaskCompleted = "task:completed" // running → completed- EventTaskFailed = "task:failed" // running → failed- EventTaskMessage = "task:message"- EventTaskCancelled = "task:cancelled" // * → cancelled+ EventTaskQueued = "task:queued" // ∅ → queued (enqueue / retry create)+ EventTaskDispatch = "task:dispatch" // queued → dispatched (daemon claim)+ EventTaskRunning = "task:running" // dispatched → running (daemon started)+ EventTaskWaitingLocalDirectory = "task:waiting_local_directory" // dispatched → waiting_local_directory (daemon parked on a busy local_directory path)+ EventTaskProgress = "task:progress"+ EventTaskCompleted = "task:completed" // running → completed+ EventTaskFailed = "task:failed" // running → failed+ EventTaskMessage = "task:message"+ EventTaskCancelled = "task:cancelled" // * → cancelled// Inbox eventsEventInboxNew = "inbox:new"@@ -113,10 +113,11 @@ const (EventSquadDeleted = "squad:deleted"// Daemon events- EventDaemonHeartbeat = "daemon:heartbeat"- EventDaemonHeartbeatAck = "daemon:heartbeat_ack"- EventDaemonRegister = "daemon:register"- EventDaemonTaskAvailable = "daemon:task_available"+ EventDaemonHeartbeat = "daemon:heartbeat"+ EventDaemonHeartbeatAck = "daemon:heartbeat_ack"+ EventDaemonRegister = "daemon:register"+ EventDaemonTaskAvailable = "daemon:task_available"+ EventDaemonRuntimeProfilesChanged = "daemon:runtime_profiles_changed"// GitHub integration eventsEventGitHubInstallationCreated = "github_installation:created"diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex 0d599d03c1..0bd41b9943 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -23,6 +23,15 @@ type TaskAvailablePayload struct {TaskID string `json:"task_id,omitempty"`}+// RuntimeProfilesChangedPayload is sent from server to daemon as a wakeup hint+// when a workspace custom runtime profile is created, edited, disabled, or+// deleted. The daemon still fetches profiles and registers runtimes through the+// existing HTTP endpoints.+type RuntimeProfilesChangedPayload struct {+ WorkspaceID string `json:"workspace_id"`+ RuntimeProfileID string `json:"runtime_profile_id,omitempty"`+}+// TaskProgressPayload is sent from daemon to server during task execution.type TaskProgressPayload struct {TaskID string `json:"task_id"`