Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix: runtime member isolation — prevent cross-member runtime access
Gus07a710a0252e
diff --git a/src/shared/src/db/queries/machine.ts b/src/shared/src/db/queries/machine.tsindex 844e5e724..2fcd982cd 100644--- a/src/shared/src/db/queries/machine.ts+++ b/src/shared/src/db/queries/machine.ts@@ -1,4 +1,4 @@-import { eq, and } from "drizzle-orm";+import { eq, and, sql } from "drizzle-orm";import { machine } from "../schema";import type { Database } from "../index";@@ -9,6 +9,7 @@ export async function upsertMachine(workspaceId: string;deviceInfo: string;lastSeenAt?: string | null;+ ownerId?: string;}) {const now = new Date().toISOString();@@ -22,6 +23,7 @@ export async function upsertMachine(lastSeenAt,createdAt: now,updatedAt: now,+ ownerId: data.ownerId,}).onConflictDoUpdate({target: [machine.workspaceId, machine.daemonId],@@ -29,6 +31,7 @@ export async function upsertMachine(deviceInfo: data.deviceInfo,lastSeenAt,updatedAt: now,+ ownerId: sql`COALESCE(${machine.ownerId}, ${data.ownerId ?? null})`,},}).returning();@@ -79,12 +82,15 @@ export async function getMachineByDaemon(export async function listMachinesForWorkspace(db: Database,- workspaceId: string+ workspaceId: string,+ userId?: string) {+ const conditions = [eq(machine.workspaceId, workspaceId)];+ if (userId) conditions.push(eq(machine.ownerId, userId));return db.select().from(machine)- .where(eq(machine.workspaceId, workspaceId));+ .where(and(...conditions));}export async function deleteMachine(diff --git a/src/shared/src/db/queries/runtime.ts b/src/shared/src/db/queries/runtime.tsindex 07f9fba9b..6334c6c4c 100644--- a/src/shared/src/db/queries/runtime.ts+++ b/src/shared/src/db/queries/runtime.ts@@ -42,7 +42,9 @@ export async function upsertAgentRuntime(return rows[0]!;}-export async function listAgentRuntimes(db: Database, workspaceId: string) {+export async function listAgentRuntimes(db: Database, workspaceId: string, userId?: string) {+ const conditions = [eq(agentRuntime.workspaceId, workspaceId)];+ if (userId) conditions.push(eq(machine.ownerId, userId));return db.select({id: agentRuntime.id,@@ -57,6 +59,7 @@ export async function listAgentRuntimes(db: Database, workspaceId: string) {machineLastSeenAt: machine.lastSeenAt,pendingUpdateVersion: machine.pendingUpdateVersion,pendingRescan: machine.pendingRescan,+ machineOwnerId: machine.ownerId,}).from(agentRuntime).leftJoin(@@ -66,7 +69,7 @@ export async function listAgentRuntimes(db: Database, workspaceId: string) {eq(machine.workspaceId, agentRuntime.workspaceId)))- .where(eq(agentRuntime.workspaceId, workspaceId))+ .where(and(...conditions)).orderBy(asc(agentRuntime.createdAt));}@@ -81,8 +84,11 @@ export async function getAgentRuntime(db: Database, id: string) {export async function getAgentRuntimeForWorkspace(db: Database,id: string,- workspaceId: string+ workspaceId: string,+ userId?: string) {+ const conditions = [eq(agentRuntime.id, id), eq(agentRuntime.workspaceId, workspaceId)];+ if (userId) conditions.push(eq(machine.ownerId, userId));const rows = await db.select({id: agentRuntime.id,@@ -106,18 +112,19 @@ export async function getAgentRuntimeForWorkspace(eq(machine.workspaceId, agentRuntime.workspaceId)))- .where(- and(eq(agentRuntime.id, id), eq(agentRuntime.workspaceId, workspaceId))- );+ .where(and(...conditions));return rows[0] ?? null;}export async function getAgentRuntimesForWorkspace(db: Database,ids: string[],- workspaceId: string+ workspaceId: string,+ userId?: string) {if (ids.length === 0) return [];+ const conditions = [inArray(agentRuntime.id, ids), eq(agentRuntime.workspaceId, workspaceId)];+ if (userId) conditions.push(eq(machine.ownerId, userId));return db.select({id: agentRuntime.id,@@ -141,9 +148,7 @@ export async function getAgentRuntimesForWorkspace(eq(machine.workspaceId, agentRuntime.workspaceId)))- .where(- and(inArray(agentRuntime.id, ids), eq(agentRuntime.workspaceId, workspaceId))- );+ .where(and(...conditions));}export async function deleteRuntimesByDaemonId(diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex 3fcb2b8e6..f5a1c9564 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -199,6 +199,7 @@ export const machine = sqliteTable(pendingUpdateVersion: text("pending_update_version"),pendingRescan: integer("pending_rescan", { mode: "boolean" }).default(false),updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),+ ownerId: text("owner_id").references(() => user.id, { onDelete: "set null" }),},(t) => [primaryKey({ columns: [t.workspaceId, t.daemonId] })]);diff --git a/src/web/migrations/0043_machine_owner_id.sql b/src/web/migrations/0043_machine_owner_id.sqlnew file mode 100644index 000000000..74dc6ab73--- /dev/null+++ b/src/web/migrations/0043_machine_owner_id.sql@@ -0,0 +1,26 @@+-- Add owner_id column+ALTER TABLE machine ADD COLUMN owner_id TEXT REFERENCES "user"(id) ON DELETE SET NULL;++-- Backfill from machine_token using hostname ↔ daemon_id correlation+UPDATE machine+SET owner_id = (+ SELECT mt.user_id+ FROM machine_token mt+ WHERE mt.workspace_id = machine.workspace_id+ AND mt.hostname = machine.daemon_id+ AND mt.status = 'active'+ ORDER BY mt.last_used_at DESC+ LIMIT 1+)+WHERE machine.owner_id IS NULL;++-- Fallback: assign to workspace owner for any remaining unmatched machines+UPDATE machine+SET owner_id = (+ SELECT m.user_id+ FROM member m+ WHERE m.workspace_id = machine.workspace_id+ AND m.role = 'owner'+ LIMIT 1+)+WHERE machine.owner_id IS NULL;diff --git a/src/web/src/app/api/agents/[id]/route.test.ts b/src/web/src/app/api/agents/[id]/route.test.tsindex 69481b306..6bcbadba9 100644--- a/src/web/src/app/api/agents/[id]/route.test.ts+++ b/src/web/src/app/api/agents/[id]/route.test.ts@@ -211,7 +211,7 @@ describe("PATCH /api/agents/[id]", () => {);});- it("PATCH with valid runtime_id (same workspace) updates agent successfully", async () => {+ it("TC-6: PATCH with valid runtime_id (own runtime) updates agent successfully", async () => {mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });mockGetAgentRuntimeForWorkspace.mockResolvedValue({ id: "rt1", workspaceId: "w1" });mockUpdateAgent.mockResolvedValue({ id: "a1", name: "Agent" });@@ -228,6 +228,7 @@ describe("PATCH /api/agents/[id]", () => {expect.anything(),"rt1","w1",+ "u1",);expect(mockUpdateAgent).toHaveBeenCalledWith(expect.anything(),@@ -238,12 +239,12 @@ describe("PATCH /api/agents/[id]", () => {);});- it("PATCH with runtime_id from another workspace returns 400", async () => {+ it("TC-5: PATCH with runtime_id belonging to another member returns 400", async () => {mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);const req = new NextRequest("http://localhost/api/agents/a1", {method: "PATCH",- body: JSON.stringify({ runtime_id: "rt_other_ws" }),+ body: JSON.stringify({ runtime_id: "rt_other_user" }),});const ctx = { params: Promise.resolve({ id: "a1" }) };const res = await PATCH(req, ctx);diff --git a/src/web/src/app/api/agents/[id]/route.ts b/src/web/src/app/api/agents/[id]/route.tsindex b681202fc..ccba38c55 100644--- a/src/web/src/app/api/agents/[id]/route.ts+++ b/src/web/src/app/api/agents/[id]/route.ts@@ -47,7 +47,7 @@ export const PATCH = withAuth(async (req, ctx) => {if (body.description !== undefined) data.description = body.description;if (body.instructions !== undefined) data.instructions = body.instructions;if (body.runtime_id !== undefined) {- const runtime = await queries.runtime.getAgentRuntimeForWorkspace(db, body.runtime_id, ws.workspaceId);+ const runtime = await queries.runtime.getAgentRuntimeForWorkspace(db, body.runtime_id, ws.workspaceId, ctx.userId);if (!runtime) {return writeError("runtime not found in workspace", 400);}diff --git a/src/web/src/app/api/agents/recruit/route.ts b/src/web/src/app/api/agents/recruit/route.tsindex 9307f1c31..65241cae4 100644--- a/src/web/src/app/api/agents/recruit/route.ts+++ b/src/web/src/app/api/agents/recruit/route.ts@@ -56,10 +56,10 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {}const runtime = callingAgent.runtimeId- ? await queries.runtime.getAgentRuntimeForWorkspace(db, callingAgent.runtimeId, ws.workspaceId)+ ? await queries.runtime.getAgentRuntimeForWorkspace(db, callingAgent.runtimeId, ws.workspaceId, ctx.userId): null;if (!runtime) {- return writeError("calling agent has no runtime", 400);+ return writeError("calling agent has no runtime — reassign the agent to your own runtime first", 400);}const agentName = body.name?.trim() || uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" });diff --git a/src/web/src/app/api/agents/route.test.ts b/src/web/src/app/api/agents/route.test.tsindex 35d138c9a..22a425fed 100644--- a/src/web/src/app/api/agents/route.test.ts+++ b/src/web/src/app/api/agents/route.test.ts@@ -139,7 +139,7 @@ describe("POST /api/agents", () => {expect(body.details).toContainEqual(expect.stringContaining("runtime_id"));});- it("returns 404 when runtime not in workspace", async () => {+ it("TC-3: returns 404 when creating agent on non-owned runtime", async () => {mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);const req = new NextRequest("http://localhost/api/agents", {@@ -153,6 +153,25 @@ describe("POST /api/agents", () => {expect(body.error).toBe("runtime not found in workspace");});+ it("TC-4: creates agent on own runtime successfully", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue({ machineLastSeenAt: null, runtimeMode: "local" });+ mockCreateAgent.mockResolvedValue({ id: "a1", name: "New Agent" });++ const req = new NextRequest("http://localhost/api/agents", {+ method: "POST",+ body: JSON.stringify(validBody),+ });+ const res = await POST(req, {});++ expect(res.status).toBe(201);+ expect(mockGetAgentRuntimeForWorkspace).toHaveBeenCalledWith(+ expect.anything(),+ "r1",+ "w1",+ "u1",+ );+ });+it("creates agent with reconcile when runtime is online", async () => {mockGetAgentRuntimeForWorkspace.mockResolvedValue({ machineLastSeenAt: new Date().toISOString(), runtimeMode: "local" });mockCreateAgent.mockResolvedValue({ id: "a1", name: "New Agent" });diff --git a/src/web/src/app/api/agents/route.ts b/src/web/src/app/api/agents/route.tsindex 2d9d156d0..e411f984c 100644--- a/src/web/src/app/api/agents/route.ts+++ b/src/web/src/app/api/agents/route.ts@@ -55,7 +55,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const runtime = await queries.runtime.getAgentRuntimeForWorkspace(db,runtimeId,- ws.workspaceId+ ws.workspaceId,+ ctx.userId);if (!runtime) {return writeError("runtime not found in workspace", 404);diff --git a/src/web/src/app/api/conversations/[id]/threads/route.ts b/src/web/src/app/api/conversations/[id]/threads/route.tsindex 171c90ba4..60ede4ea7 100644--- a/src/web/src/app/api/conversations/[id]/threads/route.ts+++ b/src/web/src/app/api/conversations/[id]/threads/route.ts@@ -42,6 +42,8 @@ export const POST = withAuth(async (req, ctx) => {);if (existing) {// Thread already exists — create message in the existing thread and enqueue task+ const msgCount = await queries.message.getActiveMessageCount(db, existing.id);+const threadMessage = await queries.message.createMessage(db, {conversationId: existing.id,role: "user",@@ -54,6 +56,25 @@ export const POST = withAuth(async (req, ctx) => {message: messageToResponse(threadMessage),}).catch(() => {});+ let taskContext: Record<string, unknown> = { message_id: threadMessage.id };+ if (msgCount === 0) {+ const historyMessages = await queries.message.listMessagesUpTo(+ db, conversationId, body.parent_message_id+ );+ const rootMsg = historyMessages.find(m => m.id === body.parent_message_id);+ const historyWithoutRoot = historyMessages+ .filter(m => m.id !== body.parent_message_id)+ .map(m => ({ role: m.role, content: m.content, created_at: m.createdAt }));+ const rootMessageContext = rootMsg+ ? { role: rootMsg.role, content: rootMsg.content }+ : null;+ taskContext = {+ message_id: threadMessage.id,+ conversation_history: historyWithoutRoot,+ ...(rootMessageContext ? { root_message: rootMessageContext } : {}),+ };+ }+const taskService = new TaskService(db);const traceId = "tr_" + nanoid();try {@@ -65,7 +86,7 @@ export const POST = withAuth(async (req, ctx) => {TASK_TYPES.USER_DM_MESSAGE,{contextKey: existing.id,- context: { message_id: threadMessage.id },+ context: taskContext,traceId,parentTaskId: null,},diff --git a/src/web/src/app/api/daemon/heartbeat/route.test.ts b/src/web/src/app/api/daemon/heartbeat/route.test.tsindex 044b022db..1b1c293bd 100644--- a/src/web/src/app/api/daemon/heartbeat/route.test.ts+++ b/src/web/src/app/api/daemon/heartbeat/route.test.ts@@ -89,6 +89,7 @@ describe("POST /api/daemon/heartbeat", () => {daemonId: "d1",workspaceId: "w1",deviceInfo: "d1",+ ownerId: "u1",});});diff --git a/src/web/src/app/api/daemon/heartbeat/route.ts b/src/web/src/app/api/daemon/heartbeat/route.tsindex f2e27607d..9ca606473 100644--- a/src/web/src/app/api/daemon/heartbeat/route.ts+++ b/src/web/src/app/api/daemon/heartbeat/route.ts@@ -28,6 +28,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {daemonId: body.daemon_id,workspaceId: ctx.workspaceId!,deviceInfo: body.daemon_id,+ ownerId: ctx.userId,});} catch (e) {log.warn("heartbeat: machine upsert failed", { daemonId: body.daemon_id, err: String(e) });diff --git a/src/web/src/app/api/daemon/register/route.ts b/src/web/src/app/api/daemon/register/route.tsindex fe9425a22..506e5bc5a 100644--- a/src/web/src/app/api/daemon/register/route.ts+++ b/src/web/src/app/api/daemon/register/route.ts@@ -49,6 +49,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {daemonId,workspaceId,deviceInfo: deviceName.trim(),+ ownerId: ctx.userId,});} catch (e) {log.warn("register: machine upsert failed", { daemonId, err: String(e) });diff --git a/src/web/src/app/api/machine-tokens/activate/route.test.ts b/src/web/src/app/api/machine-tokens/activate/route.test.tsindex a41f17846..0a6c7ea37 100644--- a/src/web/src/app/api/machine-tokens/activate/route.test.ts+++ b/src/web/src/app/api/machine-tokens/activate/route.test.ts@@ -112,6 +112,7 @@ describe("POST /api/machine-tokens/activate", () => {workspaceId: "ws_1",deviceInfo: "TestMachine.local",lastSeenAt: null,+ ownerId: "u1",});expect(mockUpsertAgentRuntime).toHaveBeenCalledWith(expect.anything(), {diff --git a/src/web/src/app/api/machine-tokens/activate/route.ts b/src/web/src/app/api/machine-tokens/activate/route.tsindex c0fd98bc4..f1ca51f94 100644--- a/src/web/src/app/api/machine-tokens/activate/route.ts+++ b/src/web/src/app/api/machine-tokens/activate/route.ts@@ -47,6 +47,7 @@ export async function POST(req: NextRequest) {workspaceId,deviceInfo: hostname,lastSeenAt: null,+ ownerId: mt.userId,});const results = [];diff --git a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.tsindex 6a704085b..41f7c8c83 100644--- a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts+++ b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts@@ -86,6 +86,18 @@ describe("POST /api/runtimes/[runtimeId]/rescan", () => {expect(res.status).toBe(200);expect(body.pending_rescan).toBe(true);expect(mockSetPendingRescan).toHaveBeenCalledWith({}, "d1", "w1");+ expect(mockGetAgentRuntimeForWorkspace).toHaveBeenCalledWith({}, "rt1", "w1", "u1");+ });++ it("TC-10: returns 404 when rescanning another member's runtime", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);++ const res = await POST(makeReq("rt1", "w1"));+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toContain("not found");+ expect(mockSetPendingRescan).not.toHaveBeenCalled();});it("returns 404 for non-existent runtime", async () => {diff --git a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.ts b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.tsindex 7a45e91d3..0f6d9e523 100644--- a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.ts+++ b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.ts@@ -21,6 +21,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {db,runtimeId,ws.workspaceId,+ ctx.userId,);if (!runtime) return writeError("runtime not found", 404);diff --git a/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts b/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.tsindex c93904bca..3195551cb 100644--- a/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts+++ b/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts@@ -100,6 +100,18 @@ describe("POST /api/runtimes/[runtimeId]/update", () => {expect(res.status).toBe(200);expect(body.pending_update_version).toBe("1.0.0");expect(mockSetPendingUpdateVersion).toHaveBeenCalledWith({}, "d1", "w1", "1.0.0");+ expect(mockGetAgentRuntimeForWorkspace).toHaveBeenCalledWith({}, "rt1", "w1", "u1");+ });++ it("TC-8: returns 404 when updating another member's runtime", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);++ const res = await POST(makeReq("POST", "rt1", "w1"));+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toContain("not found");+ expect(mockSetPendingUpdateVersion).not.toHaveBeenCalled();});it("returns 404 for non-existent runtime", async () => {@@ -160,6 +172,18 @@ describe("DELETE /api/runtimes/[runtimeId]/update", () => {workspaceId: "w1",status: "online",});+ expect(mockGetAgentRuntimeForWorkspace).toHaveBeenCalledWith({}, "rt1", "w1", "u1");+ });++ it("TC-9: returns 404 when cancelling update on another member's runtime", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);++ const res = await DELETE(makeReq("DELETE", "rt1", "w1"));+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toContain("not found");+ expect(mockClearPendingUpdateVersion).not.toHaveBeenCalled();});it("returns 204 even when broadcast fails", async () => {diff --git a/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts b/src/web/src/app/api/runtimes/[runtimeId]/update/route.tsindex 7443908c6..750590cdb 100644--- a/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts+++ b/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts@@ -22,6 +22,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {db,runtimeId,ws.workspaceId,+ ctx.userId,);if (!runtime) return writeError("runtime not found", 404);@@ -49,6 +50,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {db,runtimeId,ws.workspaceId,+ ctx.userId,);if (!runtime) return writeError("runtime not found", 404);diff --git a/src/web/src/app/api/runtimes/machine/route.test.ts b/src/web/src/app/api/runtimes/machine/route.test.tsindex 4377008c8..401fc3036 100644--- a/src/web/src/app/api/runtimes/machine/route.test.ts+++ b/src/web/src/app/api/runtimes/machine/route.test.ts@@ -3,6 +3,7 @@ import { NextRequest } from "next/server";const mockDeleteRuntimesByDaemonId = vi.fn();const mockDeleteMachine = vi.fn();+const mockGetMachineByDaemon = vi.fn();const mockGetMemberByUserAndWorkspace = vi.fn();vi.mock("@opennextjs/cloudflare", () => ({@@ -20,6 +21,8 @@ vi.mock("@alook/shared", () => ({machine: {deleteMachine: (...args: any[]) =>mockDeleteMachine(...args),+ getMachineByDaemon: (...args: any[]) =>+ mockGetMachineByDaemon(...args),},member: {getMemberByUserAndWorkspace: (...args: any[]) =>@@ -99,8 +102,9 @@ describe("DELETE /api/runtimes/machine", () => {expect(body.error).toContain("workspace not found");});- it("returns 204 on successful delete", async () => {+ it("returns 204 on successful delete (TC-12)", async () => {mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ mockGetMachineByDaemon.mockResolvedValue({ daemonId: "d1", ownerId: "u1" });mockDeleteRuntimesByDaemonId.mockResolvedValue(undefined);mockDeleteMachine.mockResolvedValue(undefined);@@ -111,8 +115,36 @@ describe("DELETE /api/runtimes/machine", () => {expect(res.status).toBe(204);});+ it("TC-11: returns 404 when deleting another member's machine", async () => {+ mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ mockGetMachineByDaemon.mockResolvedValue({ daemonId: "d1", ownerId: "other-user" });++ const res = await DELETE(+ makeReq({ daemon_id: "d1", workspace_id: "w1" })+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toContain("not found");+ expect(mockDeleteRuntimesByDaemonId).not.toHaveBeenCalled();+ });++ it("returns 404 when machine does not exist", async () => {+ mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ mockGetMachineByDaemon.mockResolvedValue(null);++ const res = await DELETE(+ makeReq({ daemon_id: "d1", workspace_id: "w1" })+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toContain("not found");+ });+it("passes correct daemon_id with dots and dashes", async () => {mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ mockGetMachineByDaemon.mockResolvedValue({ daemonId: "my-daemon.v2.host-01", ownerId: "u1" });mockDeleteRuntimesByDaemonId.mockResolvedValue(undefined);mockDeleteMachine.mockResolvedValue(undefined);@@ -128,6 +160,7 @@ describe("DELETE /api/runtimes/machine", () => {it("calls deleteRuntimesByDaemonId exactly once", async () => {mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ mockGetMachineByDaemon.mockResolvedValue({ daemonId: "d1", ownerId: "u1" });mockDeleteRuntimesByDaemonId.mockResolvedValue(undefined);mockDeleteMachine.mockResolvedValue(undefined);@@ -138,6 +171,7 @@ describe("DELETE /api/runtimes/machine", () => {it("returns 500 when deleteRuntimesByDaemonId throws", async () => {mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ mockGetMachineByDaemon.mockResolvedValue({ daemonId: "d1", ownerId: "u1" });mockDeleteRuntimesByDaemonId.mockRejectedValue(new Error("DB exploded"));const res = await DELETE(@@ -152,6 +186,7 @@ describe("DELETE /api/runtimes/machine", () => {it("broadcasts daemon.evict on successful delete", async () => {const { broadcastToDaemon } = await import("@/lib/broadcast");mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ mockGetMachineByDaemon.mockResolvedValue({ daemonId: "d1", ownerId: "u1" });mockDeleteRuntimesByDaemonId.mockResolvedValue(undefined);mockDeleteMachine.mockResolvedValue(undefined);diff --git a/src/web/src/app/api/runtimes/machine/route.ts b/src/web/src/app/api/runtimes/machine/route.tsindex 40e1bdc63..28c703a1a 100644--- a/src/web/src/app/api/runtimes/machine/route.ts+++ b/src/web/src/app/api/runtimes/machine/route.ts@@ -21,6 +21,11 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {return writeJSON({ error: "daemon_id is required" }, 400);}+ const ownerMachine = await queries.machine.getMachineByDaemon(db, daemonId, ws.workspaceId);+ if (!ownerMachine || ownerMachine.ownerId !== ctx.userId) {+ return writeJSON({ error: "machine not found" }, 404);+ }+try {await queries.runtime.deleteRuntimesByDaemonId(db, daemonId, ws.workspaceId);await queries.machine.deleteMachine(db, daemonId, ws.workspaceId);diff --git a/src/web/src/app/api/runtimes/route.test.ts b/src/web/src/app/api/runtimes/route.test.tsindex 5573a3d6d..420c586f2 100644--- a/src/web/src/app/api/runtimes/route.test.ts+++ b/src/web/src/app/api/runtimes/route.test.ts@@ -61,6 +61,19 @@ describe("GET /api/runtimes", () => {{ id: "r1", status: "online" },{ id: "r2", status: "offline" },]);- expect(mockListAgentRuntimes).toHaveBeenCalledWith({}, "w1");+ expect(mockListAgentRuntimes).toHaveBeenCalledWith({}, "w1", "u1");+ });++ it("TC-1/TC-2: passes userId so only owner's runtimes are returned", async () => {+ mockListAgentRuntimes.mockResolvedValue([{ id: "r1", status: "online" }]);++ const req = new NextRequest("http://localhost/api/runtimes");+ await GET(req, {} as any);++ expect(mockListAgentRuntimes).toHaveBeenCalledWith(+ expect.anything(),+ "w1",+ "u1",+ );});});diff --git a/src/web/src/app/api/runtimes/route.ts b/src/web/src/app/api/runtimes/route.tsindex 527814cdb..906b61463 100644--- a/src/web/src/app/api/runtimes/route.ts+++ b/src/web/src/app/api/runtimes/route.ts@@ -13,7 +13,7 @@ export const GET = withAuth(async (req, ctx) => {const { env } = getCloudflareContext()const db = getDb((env as Env).DB)- const runtimes = await queries.runtime.listAgentRuntimes(db, ws.workspaceId);+ const runtimes = await queries.runtime.listAgentRuntimes(db, ws.workspaceId, ctx.userId);return writeJSON(runtimes.map(runtimeToResponse));});diff --git a/src/web/src/app/api/studios/route.test.ts b/src/web/src/app/api/studios/route.test.tsindex cfa11b5b1..6f7c35019 100644--- a/src/web/src/app/api/studios/route.test.ts+++ b/src/web/src/app/api/studios/route.test.ts@@ -211,7 +211,7 @@ describe("POST /api/studios", () => {expect(res.status).toBe(400);});- it("returns 404 if runtime not in workspace", async () => {+ it("TC-7: returns 404 when using another member's runtime", async () => {mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);mockGetAgentRuntimesForWorkspace.mockResolvedValue([]);diff --git a/src/web/src/app/api/studios/route.ts b/src/web/src/app/api/studios/route.tsindex 90f837deb..9e0dd8ce4 100644--- a/src/web/src/app/api/studios/route.ts+++ b/src/web/src/app/api/studios/route.ts@@ -55,7 +55,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (valErr) return valErr;const runtimeIds = [...new Set(body.members.map((m) => m.runtime_id))];- const runtimes = await queries.runtime.getAgentRuntimesForWorkspace(db, runtimeIds, ws.workspaceId);+ const runtimes = await queries.runtime.getAgentRuntimesForWorkspace(db, runtimeIds, ws.workspaceId, ctx.userId);const runtimeCache = new Map(runtimes.map((r) => [r.id, r]));for (const rid of runtimeIds) {if (!runtimeCache.has(rid)) {