Skip to content

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

Go

fix(runtimes): hide private runtimes from non-owners (#7435)

m2keloop8442504201b3
diff --git a/packages/views/agents/components/agent-detail-inspector.labels.test.tsx b/packages/views/agents/components/agent-detail-inspector.labels.test.tsx
index 28ca1dc5b5..d3bda35d63 100644
--- a/packages/views/agents/components/agent-detail-inspector.labels.test.tsx
+++ b/packages/views/agents/components/agent-detail-inspector.labels.test.tsx
@@ -45,7 +45,9 @@ const agent = {
} as Agent;
describe("AgentDetailInspector labels", () => {
- afterEach(cleanup);
+ afterEach(() => {
+ cleanup();
+ });
// Agent labels were removed from the product (MUL-5600). Label Settings no
// longer manages an agent catalog, so an attach-only picker here would be a
diff --git a/packages/views/agents/components/agent-detail-inspector.runtime-access.test.tsx b/packages/views/agents/components/agent-detail-inspector.runtime-access.test.tsx
new file mode 100644
index 0000000000..0e84ce6046
--- /dev/null
+++ b/packages/views/agents/components/agent-detail-inspector.runtime-access.test.tsx
@@ -0,0 +1,121 @@
+// @vitest-environment jsdom
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, cleanup, waitFor } from "@testing-library/react";
+import type {
+ Agent,
+ AgentRuntime,
+ RuntimeModelListRequest,
+} from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+
+const mockInitiateListModels = vi.hoisted(() => vi.fn());
+const mockGetListModelsResult = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/api", () => ({
+ api: {
+ initiateListModels: (...args: unknown[]) =>
+ mockInitiateListModels(...args),
+ getListModelsResult: (...args: unknown[]) =>
+ mockGetListModelsResult(...args),
+ },
+}));
+
+vi.mock("../../common/avatar-upload-control", () => ({
+ AvatarUploadControl: () => <div data-testid="avatar-upload" />,
+}));
+
+vi.mock("./inspector/runtime-picker", () => ({
+ RuntimePicker: () => <div data-testid="runtime-picker" />,
+}));
+
+import { AgentDetailInspector } from "./agent-detail-inspector";
+
+const agent = {
+ id: "agent-1",
+ workspace_id: "workspace-1",
+ name: "Lambda",
+ description: "Test agent",
+ runtime_id: "runtime-1",
+} as Agent;
+
+const privateRuntime = {
+ id: "runtime-1",
+ workspace_id: "workspace-1",
+ daemon_id: "daemon-1",
+ name: "Private runtime",
+ runtime_mode: "local",
+ provider: "codex",
+ launch_header: "",
+ status: "online",
+ device_info: "Mac",
+ metadata: {},
+ owner_id: "user-2",
+ visibility: "private",
+ last_seen_at: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+} satisfies AgentRuntime;
+
+const completedModelsRequest = {
+ id: "request-1",
+ runtime_id: privateRuntime.id,
+ status: "completed",
+ models: [],
+ supported: true,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+} satisfies RuntimeModelListRequest;
+
+let queryClient: QueryClient;
+
+function renderInspector(currentUserId: string) {
+ renderWithI18n(
+ <QueryClientProvider client={queryClient}>
+ <AgentDetailInspector
+ agent={agent}
+ runtime={privateRuntime}
+ runtimes={[privateRuntime]}
+ members={[]}
+ currentUserId={currentUserId}
+ canEdit
+ onUpdate={vi.fn(async () => {})}
+ />
+ </QueryClientProvider>,
+ );
+}
+
+describe("AgentDetailInspector runtime access", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockInitiateListModels.mockResolvedValue(completedModelsRequest);
+ mockGetListModelsResult.mockResolvedValue(completedModelsRequest);
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ queryClient.clear();
+ });
+
+ it("does not discover models for another member's private runtime", async () => {
+ renderInspector("admin-1");
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(mockInitiateListModels).not.toHaveBeenCalled();
+ });
+
+ it("still discovers models for the private runtime owner", async () => {
+ renderInspector(privateRuntime.owner_id);
+
+ await waitFor(() => {
+ expect(mockInitiateListModels).toHaveBeenCalledWith(privateRuntime.id);
+ });
+ });
+});
diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsx
index d8dd8d3887..aa70930fe2 100644
--- a/packages/views/agents/components/agent-detail-inspector.tsx
+++ b/packages/views/agents/components/agent-detail-inspector.tsx
@@ -12,7 +12,10 @@ import {
AGENT_MAX_CONCURRENT_TASKS_MAX,
AGENT_MAX_CONCURRENT_TASKS_MIN,
} from "@multica/core/agents";
-import { runtimeModelsOptions } from "@multica/core/runtimes";
+import {
+ isRuntimeUsableForUser,
+ runtimeModelsOptions,
+} from "@multica/core/runtimes";
import { isImeComposing } from "@multica/core/utils";
import { Input } from "@multica/ui/components/ui/input";
import { Textarea } from "@multica/ui/components/ui/textarea";
@@ -115,13 +118,16 @@ export function AgentDetailInspector({
});
const isOnline = runtime?.status === "online";
+ const canReadRuntime =
+ runtime != null && isRuntimeUsableForUser(runtime, currentUserId);
+ const canDiscoverRuntimeModels = isOnline && canReadRuntime;
const nameInvalid = name.trim().length === 0;
// Same query the Thinking / Speed fields already use, so switching model
// costs no extra request. `null` = not authoritative (offline runtime, still
// loading, or discovery failed) and must not trigger any clearing.
const modelsQuery = useQuery(
- runtimeModelsOptions(isOnline ? agent.runtime_id : null),
+ runtimeModelsOptions(canDiscoverRuntimeModels ? agent.runtime_id : null),
);
const modelCatalog = useMemo<ModelCatalog>(
() =>
@@ -269,7 +275,7 @@ export function AgentDetailInspector({
variant="field"
showLabel={false}
runtimeId={agent.runtime_id}
- runtimeOnline={!!isOnline}
+ runtimeOnline={canDiscoverRuntimeModels}
value={agent.model ?? ""}
canEdit={canEdit}
onChange={handleModelChange}
@@ -278,7 +284,7 @@ export function AgentDetailInspector({
<ThinkingSettingField
label={t(($) => $.inspector.prop_thinking)}
runtimeId={agent.runtime_id}
- runtimeOnline={!!isOnline}
+ runtimeOnline={canDiscoverRuntimeModels}
provider={runtime?.provider ?? ""}
model={agent.model ?? ""}
value={agent.thinking_level ?? ""}
@@ -290,7 +296,7 @@ export function AgentDetailInspector({
<ServiceTierSettingField
label={t(($) => $.inspector.prop_speed)}
runtimeId={agent.runtime_id}
- runtimeOnline={!!isOnline}
+ runtimeOnline={canDiscoverRuntimeModels}
provider={runtime?.provider ?? ""}
model={agent.model ?? ""}
value={agent.service_tier ?? ""}
diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsx
index 4471f88f44..4fa758ad21 100644
--- a/packages/views/agents/components/agent-overview-pane.tsx
+++ b/packages/views/agents/components/agent-overview-pane.tsx
@@ -434,6 +434,7 @@ export function AgentOverviewPane({
<SkillsTab
agent={agent}
runtime={runtime}
+ currentUserId={currentUserId}
canEdit={canEdit}
/>
)}
@@ -441,6 +442,7 @@ export function AgentOverviewPane({
<McpConfigTab
agent={agent}
runtime={runtime}
+ currentUserId={currentUserId}
canEdit={canEdit}
onSave={(updates) => onUpdate(agent.id, updates)}
onDirtyChange={setActiveDirty}
diff --git a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx b/packages/views/agents/components/tabs/mcp-config-tab.test.tsx
index a94db97602..067b7ad27d 100644
--- a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx
+++ b/packages/views/agents/components/tabs/mcp-config-tab.test.tsx
@@ -121,12 +121,14 @@ function renderTab(
overrides: Partial<Agent> = {},
onSave = vi.fn().mockResolvedValue(undefined),
runtime: AgentRuntime | null = null,
+ currentUserId: string | null = "user-1",
) {
const result = render(
<TestShell>
<McpConfigTab
agent={{ ...baseAgent, ...overrides }}
runtime={runtime}
+ currentUserId={currentUserId}
onSave={onSave}
/>
</TestShell>,
@@ -332,6 +334,17 @@ describe("McpConfigTab", () => {
).toBeInTheDocument();
});
+ it("does not discover MCP servers for another member's private runtime", async () => {
+ renderTab({}, undefined, { ...onlineRuntime, owner_id: "user-2" }, "admin-1");
+
+ expect(
+ await screen.findByText(
+ "You don't have permission to view this runtime's MCP servers.",
+ ),
+ ).toBeInTheDocument();
+ expect(mockRuntimeCapabilities).not.toHaveBeenCalled();
+ });
+
it("shows a retry notice when capability discovery fails", async () => {
mockRuntimeCapabilities.mockRejectedValue(
new Error("daemon did not respond within 3 minutes"),
diff --git a/packages/views/agents/components/tabs/mcp-config-tab.tsx b/packages/views/agents/components/tabs/mcp-config-tab.tsx
index 90e0644997..473d3ed08d 100644
--- a/packages/views/agents/components/tabs/mcp-config-tab.tsx
+++ b/packages/views/agents/components/tabs/mcp-config-tab.tsx
@@ -14,6 +14,7 @@ import { useQuery } from "@tanstack/react-query";
import type { Agent, AgentRuntime, WorkspaceMcpServer } from "@multica/core/types";
import { ApiError } from "@multica/core/api";
import {
+ isRuntimeUsableForUser,
runtimeCapabilitiesOptions,
runtimeDisplayLabel,
} from "@multica/core/runtimes";
@@ -58,12 +59,14 @@ import { McpServerDialog } from "./mcp-server-dialog";
export function McpConfigTab({
agent,
runtime,
+ currentUserId,
canEdit = true,
onSave,
onDirtyChange,
}: {
agent: Agent;
runtime: AgentRuntime | null;
+ currentUserId?: string | null;
/**
* Whether this viewer may change the agent. A member without it can still
* read the inventory — it carries no credential material — but every write
@@ -74,8 +77,12 @@ export function McpConfigTab({
onDirtyChange?: (dirty: boolean) => void;
}) {
const { t } = useT("agents");
+ const canReadRuntime =
+ runtime != null && isRuntimeUsableForUser(runtime, currentUserId ?? null);
const runtimeId =
- runtime?.runtime_mode === "local" && runtime.status === "online"
+ runtime?.runtime_mode === "local" &&
+ runtime.status === "online" &&
+ canReadRuntime
? runtime.id
: null;
const runtimeQuery = useQuery(runtimeCapabilitiesOptions(runtimeId));
@@ -339,6 +346,8 @@ export function McpConfigTab({
</div>
{!runtime ? (
<McpNotice text={t(($) => $.tab_body.mcp_config.runtime_missing)} />
+ ) : !canReadRuntime ? (
+ <McpNotice text={t(($) => $.tab_body.mcp_config.runtime_forbidden)} />
) : runtime.status !== "online" ? (
<McpNotice text={t(($) => $.tab_body.mcp_config.runtime_offline)} />
) : runtimeQuery.isLoading ? (
diff --git a/packages/views/agents/components/tabs/skills-tab.test.tsx b/packages/views/agents/components/tabs/skills-tab.test.tsx
index 8a22799d8c..c38f806051 100644
--- a/packages/views/agents/components/tabs/skills-tab.test.tsx
+++ b/packages/views/agents/components/tabs/skills-tab.test.tsx
@@ -122,6 +122,7 @@ const onlineRuntime: AgentRuntime = {
function renderSkillsTab(
agentOverrides: Partial<Agent> = {},
runtime: AgentRuntime | null = null,
+ currentUserId: string | null = "user-1",
) {
const queryClient = new QueryClient({
defaultOptions: {
@@ -134,7 +135,11 @@ function renderSkillsTab(
return render(
<I18nProvider locale="en" resources={TEST_RESOURCES}>
<QueryClientProvider client={queryClient}>
- <SkillsTab agent={{ ...agent, ...agentOverrides }} runtime={runtime} />
+ <SkillsTab
+ agent={{ ...agent, ...agentOverrides }}
+ runtime={runtime}
+ currentUserId={currentUserId}
+ />
</QueryClientProvider>
</I18nProvider>,
);
@@ -301,6 +306,17 @@ describe("SkillsTab", () => {
).toBeInTheDocument();
});
+ it("does not discover skills for another member's private runtime", async () => {
+ renderSkillsTab({}, { ...onlineRuntime, owner_id: "user-2" }, "admin-1");
+
+ expect(
+ await screen.findByText(
+ "You don't have permission to view this runtime's skills.",
+ ),
+ ).toBeInTheDocument();
+ expect(mockRuntimeCapabilities).not.toHaveBeenCalled();
+ });
+
it("shows a retry notice when capability discovery fails", async () => {
mockRuntimeCapabilities.mockRejectedValue(
new Error("daemon did not respond within 3 minutes"),
diff --git a/packages/views/agents/components/tabs/skills-tab.tsx b/packages/views/agents/components/tabs/skills-tab.tsx
index e6547adc14..20409349e8 100644
--- a/packages/views/agents/components/tabs/skills-tab.tsx
+++ b/packages/views/agents/components/tabs/skills-tab.tsx
@@ -20,6 +20,7 @@ import type {
import { api, ApiError } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
import {
+ isRuntimeUsableForUser,
runtimeCapabilitiesOptions,
runtimeDisplayLabel,
} from "@multica/core/runtimes";
@@ -50,18 +51,24 @@ type SelectedSkill =
export function SkillsTab({
agent,
runtime,
+ currentUserId,
canEdit = true,
}: {
agent: Agent;
runtime: AgentRuntime | null;
+ currentUserId?: string | null;
canEdit?: boolean;
}) {
const { t } = useT("agents");
const qc = useQueryClient();
const wsId = useWorkspaceId();
const { data: workspaceSkills = [] } = useQuery(skillListOptions(wsId));
+ const canReadRuntime =
+ runtime != null && isRuntimeUsableForUser(runtime, currentUserId ?? null);
const runtimeId =
- runtime?.runtime_mode === "local" && runtime.status === "online"
+ runtime?.runtime_mode === "local" &&
+ runtime.status === "online" &&
+ canReadRuntime
? runtime.id
: null;
const runtimeQuery = useQuery(runtimeCapabilitiesOptions(runtimeId));
@@ -255,6 +262,8 @@ export function SkillsTab({
>
{!runtime ? (
<RuntimeNotice text={t(($) => $.tab_body.skills.runtime_missing)} />
+ ) : !canReadRuntime ? (
+ <RuntimeNotice text={t(($) => $.tab_body.skills.runtime_forbidden)} />
) : runtime.status !== "online" ? (
<RuntimeNotice text={t(($) => $.tab_body.skills.runtime_offline)} />
) : runtimeQuery.isLoading ? (
diff --git a/packages/views/runtimes/components/machine-cli-section.test.tsx b/packages/views/runtimes/components/machine-cli-section.test.tsx
index a0d8ddfebc..85316523a5 100644
--- a/packages/views/runtimes/components/machine-cli-section.test.tsx
+++ b/packages/views/runtimes/components/machine-cli-section.test.tsx
@@ -89,7 +89,6 @@ describe("MachineCliSection", () => {
<MachineCliSection
machine={machine([offlineOwned, onlineOwned, otherUsers])}
currentUserId="user-1"
- canManageAnyRuntime={false}
/>,
);
@@ -103,7 +102,7 @@ describe("MachineCliSection", () => {
});
});
- it("lets a workspace admin update through an online teammate-owned runtime", () => {
+ it("does not update through a private teammate-owned runtime for an admin", () => {
const offline = runtime({
id: "offline-other-user",
owner_id: "user-2",
@@ -118,7 +117,39 @@ describe("MachineCliSection", () => {
<MachineCliSection
machine={machine([offline, online])}
currentUserId="user-1"
- canManageAnyRuntime
+ canManagePublicRuntimes
+ />,
+ );
+
+ expect(
+ screen.queryByRole("button", { name: "Update" }),
+ ).not.toBeInTheDocument();
+ expect(mockUpdateSection).toHaveBeenCalledWith({
+ runtimeId: null,
+ currentVersion: "0.3.17",
+ isOnline: false,
+ launchedBy: null,
+ });
+ });
+
+ it("updates through an online public teammate-owned runtime for an admin", () => {
+ const offline = runtime({
+ id: "offline-other-user",
+ owner_id: "user-2",
+ status: "offline",
+ visibility: "public",
+ });
+ const online = runtime({
+ id: "online-other-user",
+ owner_id: "user-2",
+ visibility: "public",
+ });
+
+ render(
+ <MachineCliSection
+ machine={machine([offline, online])}
+ currentUserId="user-1"
+ canManagePublicRuntimes
/>,
);
@@ -131,6 +162,32 @@ describe("MachineCliSection", () => {
});
});
+ it("does not update through a public teammate-owned runtime for a member", () => {
+ const online = runtime({
+ id: "online-other-user",
+ owner_id: "user-2",
+ visibility: "public",
+ });
+
+ render(
+ <MachineCliSection
+ machine={machine([online])}
+ currentUserId="user-1"
+ canManagePublicRuntimes={false}
+ />,
+ );
+
+ expect(
+ screen.queryByRole("button", { name: "Update" }),
+ ).not.toBeInTheDocument();
+ expect(mockUpdateSection).toHaveBeenCalledWith({
+ runtimeId: null,
+ currentVersion: "0.3.17",
+ isOnline: false,
+ launchedBy: null,
+ });
+ });
+
it("shows read-only machine CLI status when the viewer owns no runtime", () => {
render(
<MachineCliSection
@@ -144,7 +201,6 @@ describe("MachineCliSection", () => {
}),
])}
currentUserId="user-1"
- canManageAnyRuntime={false}
/>,
);
diff --git a/packages/views/runtimes/components/machine-cli-section.tsx b/packages/views/runtimes/components/machine-cli-section.tsx
index 38cf7d9183..eb26e63c62 100644
--- a/packages/views/runtimes/components/machine-cli-section.tsx
+++ b/packages/views/runtimes/components/machine-cli-section.tsx
@@ -3,26 +3,28 @@ import type { RuntimeMachine } from "./runtime-machines";
import { UpdateSection } from "./update-section";
/**
- * Pick one runtime the viewer may manage as the command channel for a
- * machine-wide daemon update. Workspace admins may manage any runtime; other
- * members must own the runtime. An online runtime wins so the daemon can
- * receive the request immediately.
+ * Pick one runtime the viewer may use as the command channel for a
+ * machine-wide daemon update. The viewer may use their own runtime, or a
+ * public runtime when they are a workspace owner/admin. An online runtime
+ * wins so the daemon can receive the request immediately.
*/
export function machineUpdateRuntime(
machine: RuntimeMachine,
currentUserId: string | undefined,
- canManageAnyRuntime: boolean,
+ canManagePublicRuntimes: boolean,
): AgentRuntime | null {
if (machine.mode !== "local") return null;
- const manageable = canManageAnyRuntime
- ? machine.runtimes
- : currentUserId
- ? machine.runtimes.filter((runtime) => runtime.owner_id === currentUserId)
- : [];
+ const usable = currentUserId
+ ? machine.runtimes.filter(
+ (runtime) =>
+ runtime.owner_id === currentUserId ||
+ (canManagePublicRuntimes && runtime.visibility === "public"),
+ )
+ : [];
return (
- manageable.find((runtime) => runtime.status === "online") ??
- manageable[0] ??
+ usable.find((runtime) => runtime.status === "online") ??
+ usable[0] ??
null
);
}
@@ -30,16 +32,16 @@ export function machineUpdateRuntime(
export function MachineCliSection({
machine,
currentUserId,
- canManageAnyRuntime,
+ canManagePublicRuntimes = false,
}: {
machine: RuntimeMachine;
currentUserId: string | undefined;
- canManageAnyRuntime: boolean;
+ canManagePublicRuntimes?: boolean;
}) {
const updateRuntime = machineUpdateRuntime(
machine,
currentUserId,
- canManageAnyRuntime,
+ canManagePublicRuntimes,
);
if (machine.mode !== "local") {
diff --git a/packages/views/runtimes/components/runtime-detail-page.tsx b/packages/views/runtimes/components/runtime-detail-page.tsx
index 2639b7abd0..75505089ee 100644
--- a/packages/views/runtimes/components/runtime-detail-page.tsx
+++ b/packages/views/runtimes/components/runtime-detail-page.tsx
@@ -264,7 +264,7 @@ export function RuntimeDetailPage({
<MachineCliSection
machine={machine}
currentUserId={currentUserId}
- canManageAnyRuntime={isAdmin}
+ canManagePublicRuntimes={isAdmin}
/>
{machine.lastSeenAt && (
<span>{timeAgo(machine.lastSeenAt)}</span>
diff --git a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
index 905ee64979..74eb23ccfd 100644
--- a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
+++ b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
@@ -74,7 +74,15 @@ vi.mock("@multica/core/auth", () => ({
sel({ user: { id: "user-me" } }),
}));
-vi.mock("@multica/core/runtimes", () => ({
+// isRuntimeUsableForUser is the shared owner/public rule the component reads
+// runtime access from, so the real implementation is kept rather than stubbed —
+// a stub here would just re-derive the rule this test is meant to pin down.
+vi.mock("@multica/core/runtimes", async () => ({
+ isRuntimeUsableForUser: (
+ await vi.importActual<typeof import("@multica/core/runtimes")>(
+ "@multica/core/runtimes",
+ )
+ ).isRuntimeUsableForUser,
deriveRuntimeHealth: () => "online",
runtimeDisplayName: (rt: { name: string; custom_name?: string | null }) =>
rt.custom_name?.trim() || rt.name,
@@ -122,7 +130,9 @@ vi.mock("@multica/core/runtimes/mutations", () => ({
// Stubbing ProviderLogo / UsageSection avoids dragging in chart libs and
// additional query keys we don't care about here.
vi.mock("./provider-logo", () => ({ ProviderLogo: () => null }));
-vi.mock("./usage-section", () => ({ UsageSection: () => null }));
+vi.mock("./usage-section", () => ({
+ UsageSection: () => <div data-testid="usage-section" />,
+}));
vi.mock("./shared", () => ({ HealthBadge: () => null }));
vi.mock("../../agents/presence", () => ({
availabilityConfig: { offline: { dotClass: "", textClass: "" } },
@@ -282,6 +292,46 @@ describe("RuntimeDetail visibility section", () => {
expect(screen.queryByText("Public")).not.toBeInTheDocument();
});
+ it("hides usage from a workspace admin viewing another member's private runtime", () => {
+ mockQueryData.members = [
+ { user_id: "user-me", role: "admin" },
+ { user_id: "someone-else", role: "member" },
+ ];
+
+ renderDetail(
+ makeRuntime({ owner_id: "someone-else", visibility: "private" }),
+ );
+
+ expect(screen.queryByTestId("usage-section")).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /Delete runtime/i }),
+ ).toBeInTheDocument();
+ });
+
+ it("shows usage to a workspace admin viewing another member's public runtime", () => {
+ mockQueryData.members = [
+ { user_id: "user-me", role: "admin" },
+ { user_id: "someone-else", role: "member" },
+ ];
+
+ renderDetail(
+ makeRuntime({ owner_id: "someone-else", visibility: "public" }),
+ );
+
+ expect(screen.getByTestId("usage-section")).toBeInTheDocument();
+ });
+
+ // An ownerless runtime is unreadable server-side (the read gate reuses
+ // canUseRuntimeForAgent, which is fail-closed without an owner), so the
+ // page must not render a Usage section that can only 404.
+ it("hides usage for an ownerless runtime even when it is public", () => {
+ mockQueryData.members = [{ user_id: "user-me", role: "admin" }];
+
+ renderDetail(makeRuntime({ owner_id: null, visibility: "public" }));
+
+ expect(screen.queryByTestId("usage-section")).not.toBeInTheDocument();
+ });
+
// MUL-3352: an owner viewing an online local (self-healing) runtime
// used to see a disabled Delete button with only a hover tooltip
// explaining why. The new contract: the button is always clickable
diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index 21941a92e4..5150095984 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -22,6 +22,7 @@ import { memberListOptions, agentListOptions } from "@multica/core/workspace/que
import { useUpdateRuntime } from "@multica/core/runtimes/mutations";
import {
deriveRuntimeHealth,
+ isRuntimeUsableForUser,
runtimeDisplayName,
runtimeProfileListOptions,
} from "@multica/core/runtimes";
@@ -119,6 +120,7 @@ export function RuntimeDetail({
: false;
const isRuntimeOwner = user && runtime.owner_id === user.id;
const canEditRuntime = isAdmin || isRuntimeOwner;
+ const canReadRuntime = isRuntimeUsableForUser(runtime, user?.id ?? null);
const runtimeProfile: RuntimeProfile | null = runtime.profile_id
? profiles.find((p) => p.id === runtime.profile_id) ?? null
: null;
@@ -193,7 +195,7 @@ export function RuntimeDetail({
cliVersion={cliVersion}
daemonShort={daemonShort}
/>
- <UsageSection runtime={runtime} />
+ {canReadRuntime && <UsageSection runtime={runtime} />}
</div>
{/* Right rail: serving agents + diagnostics */}
diff --git a/packages/views/runtimes/components/runtime-list.test.ts b/packages/views/runtimes/components/runtime-list.test.ts
index d66a5b8a1c..25e28ca624 100644
--- a/packages/views/runtimes/components/runtime-list.test.ts
+++ b/packages/views/runtimes/components/runtime-list.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import type { Agent, AgentTask } from "@multica/core/types";
-import { buildWorkloadIndex } from "./runtime-list";
+import type { Agent, AgentRuntime, AgentTask } from "@multica/core/types";
+import { buildWorkloadIndex, canReadRuntimeUsage } from "./runtime-list";
function makeAgent(overrides: Partial<Agent> = {}): Agent {
return {
@@ -71,3 +71,36 @@ describe("buildWorkloadIndex", () => {
});
});
});
+
+function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
+ return {
+ id: "runtime-1",
+ workspace_id: "ws-1",
+ daemon_id: "daemon-1",
+ name: "Runtime",
+ runtime_mode: "local",
+ provider: "codex",
+ launch_header: "",
+ status: "online",
+ device_info: "Mac",
+ metadata: {},
+ owner_id: "user-2",
+ visibility: "private",
+ last_seen_at: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+describe("canReadRuntimeUsage", () => {
+ it("does not load usage for an admin viewing another member's private runtime", () => {
+ expect(canReadRuntimeUsage(makeRuntime(), "admin-1")).toBe(false);
+ });
+
+ it("allows usage for a public teammate runtime", () => {
+ expect(
+ canReadRuntimeUsage(makeRuntime({ visibility: "public" }), "member-1"),
+ ).toBe(true);
+ });
+});
diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsx
index d8424526f9..f8aa94865b 100644
--- a/packages/views/runtimes/components/runtime-list.tsx
+++ b/packages/views/runtimes/components/runtime-list.tsx
@@ -29,6 +29,7 @@ import {
import { agentTaskSnapshotOptions } from "@multica/core/agents";
import {
deriveRuntimeHealth,
+ isRuntimeUsableForUser,
runtimeProfileListOptions,
runtimeUsageOptions,
} from "@multica/core/runtimes";
@@ -375,13 +376,27 @@ function HealthCell({
// page are large.
const COST_CELL_DAYS = 14;
-export function CostCell({ runtimeId }: { runtimeId: string }) {
+export function canReadRuntimeUsage(
+ runtime: AgentRuntime,
+ currentUserId: string | null,
+): boolean {
+ return isRuntimeUsableForUser(runtime, currentUserId);
+}
+
+export function CostCell({
+ runtimeId,
+ enabled,
+}: {
+ runtimeId: string;
+ enabled: boolean;
+}) {
const { t, i18n } = useT("runtimes");
const tz = useViewingTimezone();
const locales = i18n.resolvedLanguage ?? i18n.language;
- const { data: usage = [] } = useQuery(
- runtimeUsageOptions(runtimeId, COST_CELL_DAYS, tz),
- );
+ const { data: usage = [] } = useQuery({
+ ...runtimeUsageOptions(runtimeId, COST_CELL_DAYS, tz),
+ enabled,
+ });
const cost7d = useMemo(() => computeCostInWindow(usage, 7, tz), [usage, tz]);
const costPrev7d = useMemo(
() => computeCostInWindow(usage, 7, tz, 7),
@@ -809,7 +824,10 @@ export function RuntimeList({
<span className="text-caption text-faint-foreground">—</span>
</div>
) : (
- <CostCell runtimeId={row.runtime.id} />
+ <CostCell
+ runtimeId={row.runtime.id}
+ enabled={canReadRuntimeUsage(row.runtime, user?.id ?? null)}
+ />
)}
</ListGridCell>
<ListGridCell className="hidden @2xl:flex">
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index da1fe35ba2..5ce6e221e0 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -109,21 +109,11 @@ type RuntimeUsageResponse struct {
// same tool).
func (h *Handler) GetRuntimeUsage(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
- runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
+ rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)
if !ok {
return
}
- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
- if err != nil {
- writeError(w, http.StatusNotFound, "runtime not found")
- return
- }
-
- if _, ok := h.requireWorkspaceMember(w, r, uuidToString(rt.WorkspaceID), "runtime not found"); !ok {
- return
- }
-
// All runtime reports render in the viewer's tz.
viewTZ := h.resolveViewingTZ(r)
since := parseSinceParamInTZ(r, 90, viewTZ)
@@ -173,21 +163,11 @@ func (h *Handler) listRuntimeUsage(ctx context.Context, runtimeID pgtype.UUID, t
// GetRuntimeTaskActivity returns hourly task activity distribution for a runtime.
func (h *Handler) GetRuntimeTaskActivity(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
- runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
+ rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)
if !ok {
return
}
- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
- if err != nil {
- writeError(w, http.StatusNotFound, "runtime not found")
- return
- }
-
- if _, ok := h.requireWorkspaceMember(w, r, uuidToString(rt.WorkspaceID), "runtime not found"); !ok {
- return
- }
-
viewTZ := h.resolveViewingTZ(r)
rows, err := h.Queries.GetRuntimeTaskHourlyActivity(r.Context(), db.GetRuntimeTaskHourlyActivityParams{
RuntimeID: rt.ID,
@@ -241,21 +221,11 @@ type RuntimeUsageByAgentResponse struct {
// since the cutoff window. Drives the runtime-detail "Cost by agent" tab.
func (h *Handler) GetRuntimeUsageByAgent(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
- runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
+ rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)
if !ok {
return
}
- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
- if err != nil {
- writeError(w, http.StatusNotFound, "runtime not found")
- return
- }
-
- if _, ok := h.requireWorkspaceMember(w, r, uuidToString(rt.WorkspaceID), "runtime not found"); !ok {
- return
- }
-
// No date bucketing — tz only sets the cutoff boundary so "last 30
// days" means 30 of the viewer's days.
viewTZ := h.resolveViewingTZ(r)
@@ -323,21 +293,11 @@ type RuntimeUsageByHourResponse struct {
// `?tz=` param or the authenticated user's stored user.timezone.
func (h *Handler) GetRuntimeUsageByHour(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
- runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
+ rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)
if !ok {
return
}
- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
- if err != nil {
- writeError(w, http.StatusNotFound, "runtime not found")
- return
- }
-
- if _, ok := h.requireWorkspaceMember(w, r, uuidToString(rt.WorkspaceID), "runtime not found"); !ok {
- return
- }
-
viewTZ := h.resolveViewingTZ(r)
since := parseSinceParamInTZ(r, 30, viewTZ)
@@ -670,6 +630,34 @@ func canEditRuntime(member db.Member, rt db.AgentRuntime) bool {
return rt.OwnerID.Valid && uuidToString(rt.OwnerID) == uuidToString(member.UserID)
}
+// requireRuntimeReadAccess protects runtime data and machine-triggering
+// capabilities. Governance access is deliberately separate: workspace owners
+// and admins may list, rename, or delete another member's private runtime,
+// but a private machine is readable or usable only by its owner. Returning
+// 404 for that case prevents a known runtime ID from becoming an oracle.
+func (h *Handler) requireRuntimeReadAccess(w http.ResponseWriter, r *http.Request, runtimeID string) (db.AgentRuntime, db.Member, bool) {
+ runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
+ if !ok {
+ return db.AgentRuntime{}, db.Member{}, false
+ }
+
+ rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
+ if err != nil {
+ writeError(w, http.StatusNotFound, "runtime not found")
+ return db.AgentRuntime{}, db.Member{}, false
+ }
+
+ member, ok := h.requireWorkspaceMember(w, r, uuidToString(rt.WorkspaceID), "runtime not found")
+ if !ok || !canUseRuntimeForAgent(member, rt) {
+ if ok {
+ writeError(w, http.StatusNotFound, "runtime not found")
+ }
+ return db.AgentRuntime{}, db.Member{}, false
+ }
+
+ return rt, member, true
+}
+
func (h *Handler) runtimeHasLiveProfile(ctx context.Context, rt db.AgentRuntime) (bool, error) {
if !rt.ProfileID.Valid {
return false, nil
@@ -726,21 +714,33 @@ func canSetRuntimeVisibility(member db.Member, rt db.AgentRuntime) bool {
func (h *Handler) ListAgentRuntimes(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ member, ok := h.requireWorkspaceMember(w, r, workspaceID, "workspace not found")
+ if !ok {
+ return
+ }
var runtimes []db.AgentRuntime
var err error
if ownerFilter := r.URL.Query().Get("owner"); ownerFilter == "me" {
- userID, ok := requireUserID(w, r)
- if !ok {
- return
- }
runtimes, err = h.Queries.ListAgentRuntimesByOwner(r.Context(), db.ListAgentRuntimesByOwnerParams{
WorkspaceID: parseUUID(workspaceID),
OwnerID: parseUUID(userID),
})
- } else {
+ } else if roleAllowed(member.Role, "owner", "admin") {
+ // Governance visibility preserves the existing owner/admin contract:
+ // admins can find a private runtime to rename or delete it, but the
+ // per-runtime read gate still denies data and machine access.
runtimes, err = h.Queries.ListAgentRuntimes(r.Context(), parseUUID(workspaceID))
+ } else {
+ runtimes, err = h.Queries.ListVisibleAgentRuntimes(r.Context(), db.ListVisibleAgentRuntimesParams{
+ WorkspaceID: parseUUID(workspaceID),
+ OwnerID: parseUUID(userID),
+ })
}
if err != nil {
diff --git a/server/internal/handler/runtime_local_skills.go b/server/internal/handler/runtime_local_skills.go
index 7d7eb0a8f9..a94b963814 100644
--- a/server/internal/handler/runtime_local_skills.go
+++ b/server/internal/handler/runtime_local_skills.go
@@ -543,30 +543,18 @@ func runtimeLocalSkillRequestTerminal(status RuntimeLocalSkillRequestStatus) boo
status == RuntimeLocalSkillTimeout || status == RuntimeLocalSkillConflict
}
-// requireRuntimeCapabilityReadAccess resolves the runtime and asserts the
-// caller is a member of its workspace. This is the read-level gate for
-// capability discovery (local skills + the redacted MCP inventory): the
-// payload is deliberately non-secret so any member viewing an agent can see
-// what it inherits from its runtime, regardless of who owns that runtime.
-// Flows that copy skill files off the owner's machine must use the stricter
-// requireRuntimeLocalSkillAccess instead.
+// requireRuntimeCapabilityReadAccess applies the runtime read gate to
+// capability discovery (local skills + the redacted MCP inventory). Private
+// machines remain owner-only even for admins; public runtimes are readable by
+// workspace members. Flows that copy skill files off the owner's machine add
+// the stricter owner-only check in requireRuntimeLocalSkillAccess.
func (h *Handler) requireRuntimeCapabilityReadAccess(w http.ResponseWriter, r *http.Request, runtimeID string) (runtimeIDAndWorkspace, db.Member, bool) {
- runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
+ rt, member, ok := h.requireRuntimeReadAccess(w, r, runtimeID)
if !ok {
return runtimeIDAndWorkspace{}, db.Member{}, false
}
- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
- if err != nil {
- writeError(w, http.StatusNotFound, "runtime not found")
- return runtimeIDAndWorkspace{}, db.Member{}, false
- }
-
wsID := uuidToString(rt.WorkspaceID)
- member, ok := h.requireWorkspaceMember(w, r, wsID, "runtime not found")
- if !ok {
- return runtimeIDAndWorkspace{}, db.Member{}, false
- }
return runtimeIDAndWorkspace{
runtimeID: uuidToString(rt.ID),
diff --git a/server/internal/handler/runtime_local_skills_test.go b/server/internal/handler/runtime_local_skills_test.go
index 71fd795f4f..3499da3ba8 100644
--- a/server/internal/handler/runtime_local_skills_test.go
+++ b/server/internal/handler/runtime_local_skills_test.go
@@ -223,16 +223,18 @@ func TestInMemoryLocalSkillImportStore_TimesOutRunningRequests(t *testing.T) {
}
}
-// Capability discovery (list + poll) is readable by any workspace member so
-// the Agent capabilities surfaces work for agents bound to someone else's
-// runtime. Import stays owner-only (tests below).
-func TestListLocalSkills_AllowsNonOwnerWorkspaceMember(t *testing.T) {
+// Capability discovery (list + poll) is readable by workspace members only
+// after the runtime owner shares the machine with the workspace.
+func TestListLocalSkills_AllowsNonOwnerForPublicRuntime(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)
memberUserID := createRuntimeLocalSkillTestMember(t, "member")
+ if _, err := testPool.Exec(context.Background(), `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID); err != nil {
+ t.Fatalf("make runtime public: %v", err)
+ }
w := httptest.NewRecorder()
req := withURLParams(
@@ -312,8 +314,8 @@ func TestInitiateImportLocalSkill_RequiresRuntimeOwner(t *testing.T) {
)
testHandler.InitiateImportLocalSkill(w, req)
- if w.Code != http.StatusForbidden {
- t.Fatalf("expected 403, got %d: %s", w.Code, w.Body.String())
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())
}
}
@@ -341,8 +343,8 @@ func TestGetLocalSkillImportRequest_RequiresRuntimeOwner(t *testing.T) {
)
testHandler.GetLocalSkillImportRequest(w, req)
- if w.Code != http.StatusForbidden {
- t.Fatalf("expected 403, got %d: %s", w.Code, w.Body.String())
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())
}
}
diff --git a/server/internal/handler/runtime_models.go b/server/internal/handler/runtime_models.go
index d4a0d3b1a9..d99e56f49f 100644
--- a/server/internal/handler/runtime_models.go
+++ b/server/internal/handler/runtime_models.go
@@ -317,19 +317,10 @@ func modelListRequestTerminal(status ModelListStatus) bool {
// HeartbeatInterval away.
func (h *Handler) InitiateListModels(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
- runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
+ rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)
if !ok {
return
}
-
- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
- if err != nil {
- writeError(w, http.StatusNotFound, "runtime not found")
- return
- }
- if _, ok := h.requireWorkspaceMember(w, r, uuidToString(rt.WorkspaceID), "runtime not found"); !ok {
- return
- }
if rt.Status != "online" {
writeError(w, http.StatusServiceUnavailable, "runtime is offline")
return
@@ -436,6 +427,12 @@ func (h *Handler) requestDaemonPendingWork(runtimeID, kind string) {
// GetModelListRequest returns the status of a model list request.
func (h *Handler) GetModelListRequest(w http.ResponseWriter, r *http.Request) {
+ runtimeID := chi.URLParam(r, "runtimeId")
+ rt, _, ok := h.requireRuntimeReadAccess(w, r, runtimeID)
+ if !ok {
+ return
+ }
+
requestID := chi.URLParam(r, "requestId")
req, err := h.ModelListStore.Get(r.Context(), requestID)
@@ -443,7 +440,7 @@ func (h *Handler) GetModelListRequest(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to load request: "+err.Error())
return
}
- if req == nil {
+ if req == nil || req.RuntimeID != uuidToString(rt.ID) {
writeError(w, http.StatusNotFound, "request not found")
return
}
diff --git a/server/internal/handler/runtime_update.go b/server/internal/handler/runtime_update.go
index 2a30b11f38..bef556534c 100644
--- a/server/internal/handler/runtime_update.go
+++ b/server/internal/handler/runtime_update.go
@@ -211,18 +211,7 @@ func (s *InMemoryUpdateStore) Fail(_ context.Context, id string, errMsg string)
// InitiateUpdate creates a new CLI update request (protected route, called by frontend).
func (h *Handler) InitiateUpdate(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
- runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
- if !ok {
- return
- }
-
- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
- if err != nil {
- writeError(w, http.StatusNotFound, "runtime not found")
- return
- }
-
- member, ok := h.requireWorkspaceMember(w, r, uuidToString(rt.WorkspaceID), "runtime not found")
+ rt, member, ok := h.requireRuntimeReadAccess(w, r, runtimeID)
if !ok {
return
}
@@ -272,17 +261,7 @@ func (h *Handler) InitiateUpdate(w http.ResponseWriter, r *http.Request) {
// GetUpdate returns the status of an update request (protected route, called by frontend).
func (h *Handler) GetUpdate(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
- runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
- if !ok {
- return
- }
-
- rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
- if err != nil {
- writeError(w, http.StatusNotFound, "runtime not found")
- return
- }
- member, ok := h.requireWorkspaceMember(w, r, uuidToString(rt.WorkspaceID), "runtime not found")
+ rt, member, ok := h.requireRuntimeReadAccess(w, r, runtimeID)
if !ok {
return
}
diff --git a/server/internal/handler/runtime_update_authorization_test.go b/server/internal/handler/runtime_update_authorization_test.go
index 67870b0de3..7d9d15266b 100644
--- a/server/internal/handler/runtime_update_authorization_test.go
+++ b/server/internal/handler/runtime_update_authorization_test.go
@@ -38,8 +38,8 @@ func TestInitiateUpdateRequiresRuntimeManager(t *testing.T) {
wantStatus int
}{
{name: "runtime owner", actor: "runtime_owner", wantStatus: http.StatusOK},
- {name: "workspace admin", actor: "workspace_admin", wantStatus: http.StatusOK},
- {name: "plain member", actor: "plain_member", wantStatus: http.StatusForbidden},
+ {name: "workspace admin on another private runtime", actor: "workspace_admin", wantStatus: http.StatusNotFound},
+ {name: "plain member on another private runtime", actor: "plain_member", wantStatus: http.StatusNotFound},
}
for _, tc := range tests {
@@ -91,8 +91,8 @@ func TestGetUpdateRequiresRuntimeManager(t *testing.T) {
wantStatus int
}{
{name: "runtime owner", actor: "runtime_owner", wantStatus: http.StatusOK},
- {name: "workspace admin", actor: "workspace_admin", wantStatus: http.StatusOK},
- {name: "plain member", actor: "plain_member", wantStatus: http.StatusForbidden},
+ {name: "workspace admin on another private runtime", actor: "workspace_admin", wantStatus: http.StatusNotFound},
+ {name: "plain member on another private runtime", actor: "plain_member", wantStatus: http.StatusNotFound},
}
for _, tc := range tests {
@@ -127,12 +127,19 @@ func TestGetUpdateRequiresRuntimeManager(t *testing.T) {
}
}
-func TestGetUpdateAllowsInitiatorAfterAdminDemotion(t *testing.T) {
+func TestGetUpdateAllowsInitiatorAfterAdminDemotionOnPublicRuntime(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
runtimeID, _, adminID := runtimeVisibilityFixture(t)
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE agent_runtime
+ SET visibility = 'public'
+ WHERE id = $1
+ `, runtimeID); err != nil {
+ t.Fatalf("make runtime public: %v", err)
+ }
promoteRuntimeTestMemberToAdmin(t, adminID)
initRecorder := httptest.NewRecorder()
diff --git a/server/internal/handler/runtime_visibility_test.go b/server/internal/handler/runtime_visibility_test.go
index 935feeb6ae..4651f924d0 100644
--- a/server/internal/handler/runtime_visibility_test.go
+++ b/server/internal/handler/runtime_visibility_test.go
@@ -7,6 +7,7 @@ import (
"net/http/httptest"
"testing"
+ "github.com/multica-ai/multica/server/internal/testutil"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -230,6 +231,136 @@ func TestCreateAgent_AllowsPublicRuntimeForPlainMember(t *testing.T) {
}
}
+func TestListAgentRuntimes_HidesOtherMembersPrivateRuntimes(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ privateRuntimeID, _, plainMemberID := runtimeVisibilityFixture(t)
+
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, testRuntimeID,
+ ); err != nil {
+ t.Fatalf("make fixture runtime public: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `UPDATE agent_runtime SET visibility = 'private' WHERE id = $1`, testRuntimeID)
+ })
+
+ w := testutil.Call(t, testHandler.ListAgentRuntimes,
+ newRequestAs(plainMemberID, http.MethodGet, "/api/runtimes", nil),
+ ).Want(http.StatusOK)
+ var runtimes []AgentRuntimeResponse
+ w.JSON(&runtimes)
+
+ for _, runtime := range runtimes {
+ if runtime.ID == privateRuntimeID {
+ t.Fatalf("private runtime %s owned by another member was returned", privateRuntimeID)
+ }
+ }
+ if len(runtimes) != 1 || runtimes[0].ID != testRuntimeID {
+ t.Fatalf("visible runtimes = %#v; want only public runtime %s", runtimes, testRuntimeID)
+ }
+}
+
+func TestListAgentRuntimes_AllowsAdminsToGovernPrivateRuntimes(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ privateRuntimeID, _, adminID := runtimeVisibilityFixture(t)
+ promoteRuntimeTestMemberToAdmin(t, adminID)
+
+ w := testutil.Call(t, testHandler.ListAgentRuntimes,
+ newRequestAs(adminID, http.MethodGet, "/api/runtimes", nil),
+ ).Want(http.StatusOK)
+ var runtimes []AgentRuntimeResponse
+ w.JSON(&runtimes)
+
+ for _, runtime := range runtimes {
+ if runtime.ID == privateRuntimeID {
+ return
+ }
+ }
+ t.Fatalf("admin runtime list did not include private runtime %s", privateRuntimeID)
+}
+
+func TestPrivateRuntimeReadEndpointsHideKnownRuntimeFromNonOwners(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ runtimeID, runtimeOwnerID, plainMemberID := runtimeVisibilityFixture(t)
+
+ modelRequest, err := testHandler.ModelListStore.Create(context.Background(), runtimeID)
+ if err != nil {
+ t.Fatalf("create model list request: %v", err)
+ }
+ localSkillRequest, err := testHandler.LocalSkillListStore.Create(context.Background(), runtimeID)
+ if err != nil {
+ t.Fatalf("create local skill list request: %v", err)
+ }
+
+ tests := []struct {
+ name string
+ method string
+ path string
+ handle func(http.ResponseWriter, *http.Request)
+ params []string
+ }{
+ {"usage", http.MethodGet, "/api/runtimes/" + runtimeID + "/usage", testHandler.GetRuntimeUsage, []string{"runtimeId", runtimeID}},
+ {"activity", http.MethodGet, "/api/runtimes/" + runtimeID + "/activity", testHandler.GetRuntimeTaskActivity, []string{"runtimeId", runtimeID}},
+ {"usage by agent", http.MethodGet, "/api/runtimes/" + runtimeID + "/usage/by-agent", testHandler.GetRuntimeUsageByAgent, []string{"runtimeId", runtimeID}},
+ {"usage by hour", http.MethodGet, "/api/runtimes/" + runtimeID + "/usage/by-hour", testHandler.GetRuntimeUsageByHour, []string{"runtimeId", runtimeID}},
+ {"model discovery", http.MethodPost, "/api/runtimes/" + runtimeID + "/models", testHandler.InitiateListModels, []string{"runtimeId", runtimeID}},
+ {"model discovery poll", http.MethodGet, "/api/runtimes/" + runtimeID + "/models/" + modelRequest.ID, testHandler.GetModelListRequest, []string{"runtimeId", runtimeID, "requestId", modelRequest.ID}},
+ {"local skill discovery", http.MethodPost, "/api/runtimes/" + runtimeID + "/local-skills", testHandler.InitiateListLocalSkills, []string{"runtimeId", runtimeID}},
+ {"local skill discovery poll", http.MethodGet, "/api/runtimes/" + runtimeID + "/local-skills/" + localSkillRequest.ID, testHandler.GetLocalSkillListRequest, []string{"runtimeId", runtimeID, "requestId", localSkillRequest.ID}},
+ }
+
+ for _, tc := range tests {
+ t.Run("plain member/"+tc.name, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := withURLParams(newRequestAs(plainMemberID, tc.method, tc.path, nil), tc.params...)
+ tc.handle(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+ }
+
+ promoteRuntimeTestMemberToAdmin(t, plainMemberID)
+ for _, tc := range tests {
+ t.Run("workspace admin/"+tc.name, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := withURLParams(newRequestAs(plainMemberID, tc.method, tc.path, nil), tc.params...)
+ tc.handle(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+ }
+
+ // The owner remains allowed to start discovery on their own private machine.
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequestAs(runtimeOwnerID, http.MethodPost, "/api/runtimes/"+runtimeID+"/models", nil), "runtimeId", runtimeID)
+ testHandler.InitiateListModels(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("owner model discovery: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if _, err := testPool.Exec(context.Background(), `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID); err != nil {
+ t.Fatalf("make runtime public: %v", err)
+ }
+ w = httptest.NewRecorder()
+ req = withURLParam(newRequestAs(plainMemberID, http.MethodPost, "/api/runtimes/"+runtimeID+"/models", nil), "runtimeId", runtimeID)
+ testHandler.InitiateListModels(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("public runtime model discovery: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
// TestUpdateAgent_RejectsRebindToPrivateRuntime is the regression for the
// "update can bypass create" backdoor — without this gate a plain member
// could create an agent on a public runtime, then re-bind it onto someone
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index f206386af0..5165d9c531 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -778,6 +778,59 @@ func (q *Queries) ListStaleOfflineRuntimeGCCandidates(ctx context.Context, arg L
return items, nil
}
+const listVisibleAgentRuntimes = `-- name: ListVisibleAgentRuntimes :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, custom_name FROM agent_runtime
+WHERE workspace_id = $1
+ AND (owner_id = $2 OR visibility = 'public')
+ORDER BY created_at ASC
+`
+
+type ListVisibleAgentRuntimesParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+}
+
+// A private runtime is another member's machine and must not leak into their
+// runtime list. The owner can always see their own runtime; everyone else
+// sees only runtimes the owner has explicitly shared with the workspace.
+func (q *Queries) ListVisibleAgentRuntimes(ctx context.Context, arg ListVisibleAgentRuntimesParams) ([]AgentRuntime, error) {
+ rows, err := q.db.Query(ctx, listVisibleAgentRuntimes, arg.WorkspaceID, 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 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, custom_name FROM agent_runtime
WHERE id = $1
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index af7712bc9b..11dca94657 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -3,6 +3,15 @@ SELECT * FROM agent_runtime
WHERE workspace_id = $1
ORDER BY created_at ASC;
+-- name: ListVisibleAgentRuntimes :many
+-- A private runtime is another member's machine and must not leak into their
+-- runtime list. The owner can always see their own runtime; everyone else
+-- sees only runtimes the owner has explicitly shared with the workspace.
+SELECT * FROM agent_runtime
+WHERE workspace_id = $1
+ AND (owner_id = $2 OR visibility = 'public')
+ORDER BY created_at ASC;
+
-- name: GetAgentRuntime :one
SELECT * FROM agent_runtime
WHERE id = $1;