The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(server): bound inherited workspace runtime services (#10589)
Dottaa29b10510c2c
diff --git a/server/src/__tests__/execution-workspaces-service.test.ts b/server/src/__tests__/execution-workspaces-service.test.tsindex 80af2fd5aa..230163f0db 100644--- a/server/src/__tests__/execution-workspaces-service.test.ts+++ b/server/src/__tests__/execution-workspaces-service.test.ts@@ -2264,6 +2264,239 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {expect(comments).toHaveLength(0);}, 20_000);+ it("returns full details at the observed volume without multiplying unconfigured shared service history", async () => {+ const companyId = randomUUID();+ const projectId = randomUUID();+ const projectWorkspaceId = randomUUID();+ const workspaceCount = 6_176;++ await db.insert(companies).values({+ id: companyId,+ name: "Paperclip",+ issuePrefix: "PAP",+ requireBoardApprovalForNewAgents: false,+ });+ await db.insert(projects).values({+ id: projectId,+ companyId,+ name: "Workspace scale regression",+ status: "in_progress",+ });+ await db.insert(projectWorkspaces).values({+ id: projectWorkspaceId,+ companyId,+ projectId,+ name: "Primary",+ sourceType: "local_path",+ isPrimary: true,+ cwd: "/tmp/workspace-scale-regression",+ });++ const workspaceRows = Array.from({ length: workspaceCount }, (_, index) => ({+ id: randomUUID(),+ companyId,+ projectId,+ projectWorkspaceId,+ mode: "shared_workspace" as const,+ strategyType: "project_primary" as const,+ name: `Shared workspace ${index + 1}`,+ status: "idle" as const,+ providerType: "local_fs" as const,+ cwd: "/tmp/workspace-scale-regression",+ }));+ for (let offset = 0; offset < workspaceRows.length; offset += 400) {+ await db.insert(executionWorkspaces).values(workspaceRows.slice(offset, offset + 400));+ }+ await db.insert(workspaceRuntimeServices).values(+ Array.from({ length: 163 }, (_, index) => ({+ id: randomUUID(),+ companyId,+ projectId,+ projectWorkspaceId,+ scopeType: "project_workspace",+ scopeId: projectWorkspaceId,+ serviceName: `historical-service-${index + 1}`,+ status: "stopped",+ lifecycle: "shared",+ reuseKey: `historical-service-${index + 1}`,+ command: `pnpm historical:${index + 1}`,+ cwd: "/tmp/workspace-scale-regression",+ provider: "local_process",+ healthStatus: "unknown",+ })),+ );++ const workspaces = await svc.list(companyId);++ expect(workspaces).toHaveLength(workspaceCount);+ expect(workspaces.reduce((count, workspace) => count + (workspace.runtimeServices?.length ?? 0), 0)).toBe(0);+ expect(JSON.stringify(workspaces).length).toBeLessThan(12_000_000);++ const overview = await svc.listOverview(companyId, { limit: 1, offset: 0 });+ expect(overview.total).toBe(workspaceCount);+ expect(overview.items[0]).toMatchObject({+ serviceCount: 0,+ runningServiceCount: 0,+ primaryService: null,+ hasRuntimeConfig: false,+ });+ }, 30_000);++ it("inherits only runtime-service rows matching the current project workspace configuration and reuse scopes", async () => {+ const companyId = randomUUID();+ const projectId = randomUUID();+ const projectWorkspaceId = randomUUID();+ const executionWorkspaceId = randomUUID();+ const currentWebServiceId = randomUUID();+ const currentWorkerServiceId = randomUUID();++ await db.insert(companies).values({+ id: companyId,+ name: "Paperclip",+ issuePrefix: "PAP",+ requireBoardApprovalForNewAgents: false,+ });+ await db.insert(projects).values({+ id: projectId,+ companyId,+ name: "Configured runtime selection",+ status: "in_progress",+ });+ await db.insert(projectWorkspaces).values({+ id: projectWorkspaceId,+ companyId,+ projectId,+ name: "Primary",+ sourceType: "local_path",+ isPrimary: true,+ cwd: "/tmp/configured-runtime-selection",+ metadata: {+ runtimeConfig: {+ workspaceRuntime: {+ services: [+ { name: "web", command: "pnpm dev" },+ {+ name: "worker",+ command: "pnpm worker",+ reuseScope: "execution_workspace",+ },+ ],+ },+ desiredState: "stopped",+ },+ },+ });+ await db.insert(executionWorkspaces).values({+ id: executionWorkspaceId,+ companyId,+ projectId,+ projectWorkspaceId,+ mode: "shared_workspace",+ strategyType: "project_primary",+ name: "Shared configured workspace",+ status: "idle",+ providerType: "local_fs",+ cwd: "/tmp/configured-runtime-selection",+ });+ await db.insert(workspaceRuntimeServices).values([+ {+ id: randomUUID(),+ companyId,+ projectId,+ projectWorkspaceId,+ scopeType: "project_workspace",+ scopeId: projectWorkspaceId,+ serviceName: "web",+ status: "stopped",+ lifecycle: "shared",+ reuseKey: "old-web",+ command: "pnpm dev",+ cwd: "/tmp/configured-runtime-selection",+ provider: "local_process",+ healthStatus: "unknown",+ updatedAt: new Date("2026-07-29T10:00:00.000Z"),+ },+ {+ id: currentWebServiceId,+ companyId,+ projectId,+ projectWorkspaceId,+ scopeType: "project_workspace",+ scopeId: projectWorkspaceId,+ serviceName: "web",+ status: "stopped",+ lifecycle: "shared",+ reuseKey: "current-web",+ command: "pnpm dev",+ cwd: "/tmp/configured-runtime-selection",+ provider: "local_process",+ healthStatus: "unknown",+ updatedAt: new Date("2026-07-30T10:00:00.000Z"),+ },+ {+ id: randomUUID(),+ companyId,+ projectId,+ projectWorkspaceId,+ scopeType: "project_workspace",+ scopeId: projectWorkspaceId,+ serviceName: "removed-worker",+ status: "stopped",+ lifecycle: "shared",+ reuseKey: "removed-worker",+ command: "pnpm worker",+ cwd: "/tmp/configured-runtime-selection",+ provider: "local_process",+ healthStatus: "unknown",+ updatedAt: new Date("2026-07-31T10:00:00.000Z"),+ },+ {+ id: currentWorkerServiceId,+ companyId,+ projectId,+ projectWorkspaceId,+ executionWorkspaceId,+ scopeType: "execution_workspace",+ scopeId: executionWorkspaceId,+ serviceName: "worker",+ status: "running",+ lifecycle: "shared",+ reuseKey: "current-worker",+ command: "pnpm worker",+ cwd: "/tmp/configured-runtime-selection",+ provider: "local_process",+ healthStatus: "healthy",+ updatedAt: new Date("2026-07-31T11:00:00.000Z"),+ },+ ]);++ const [workspace] = await svc.list(companyId);+ expect(workspace?.runtimeServices).toEqual([+ expect.objectContaining({+ id: currentWebServiceId,+ serviceName: "web",+ configIndex: 0,+ }),+ expect.objectContaining({+ id: currentWorkerServiceId,+ serviceName: "worker",+ configIndex: 1,+ }),+ ]);++ const overview = await svc.listOverview(companyId, { limit: 10, offset: 0 });+ expect(overview.items[0]).toMatchObject({+ serviceCount: 2,+ runningServiceCount: 1,+ hasRuntimeConfig: true,+ primaryService: {+ id: currentWorkerServiceId,+ serviceName: "worker",+ status: "running",+ },+ });+ });+it("returns a bounded company-scoped workspace overview with service and linked issue summaries", async () => {const companyId = randomUUID();const otherCompanyId = randomUUID();diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.tsindex d7e12172f3..de8cde106c 100644--- a/server/src/services/execution-workspaces.ts+++ b/server/src/services/execution-workspaces.ts@@ -37,6 +37,7 @@ import { readProjectWorkspaceRuntimeConfig } from "./project-workspace-runtime-cimport {listCurrentRuntimeServicesForExecutionWorkspaces,listCurrentRuntimeServicesForProjectWorkspaces,+ selectConfiguredRuntimeServiceRows,} from "./workspace-runtime-read-model.js";type ExecutionWorkspaceRow = typeof executionWorkspaces.$inferSelect;@@ -752,7 +753,9 @@ export function mergeExecutionWorkspaceConfig(return Object.keys(nextMetadata).length > 0 ? nextMetadata : null;}-function toRuntimeService(row: WorkspaceRuntimeServiceRow): WorkspaceRuntimeService {+function toRuntimeService(+ row: WorkspaceRuntimeServiceRow & { configIndex?: number | null },+): WorkspaceRuntimeService {return {id: row.id,companyId: row.companyId,@@ -779,6 +782,7 @@ function toRuntimeService(row: WorkspaceRuntimeServiceRow): WorkspaceRuntimeServstoppedAt: row.stoppedAt ?? null,stopPolicy: (row.stopPolicy as Record<string, unknown> | null) ?? null,healthStatus: row.healthStatus as WorkspaceRuntimeService["healthStatus"],+ configIndex: row.configIndex ?? null,createdAt: row.createdAt,updatedAt: row.updatedAt,};@@ -876,8 +880,13 @@ function noActiveRuntimeServicesForWorkspaceCondition(row: ExecutionWorkspaceRowconst activeServiceConditions = inheritedProjectWorkspaceId? and(eq(workspaceRuntimeServices.companyId, row.companyId),- eq(workspaceRuntimeServices.projectWorkspaceId, inheritedProjectWorkspaceId),- eq(workspaceRuntimeServices.scopeType, "project_workspace"),+ or(+ and(+ eq(workspaceRuntimeServices.projectWorkspaceId, inheritedProjectWorkspaceId),+ eq(workspaceRuntimeServices.scopeType, "project_workspace"),+ ),+ eq(workspaceRuntimeServices.executionWorkspaceId, row.id),+ ),ne(workspaceRuntimeServices.status, "stopped"),): and(@@ -893,28 +902,77 @@ async function loadEffectiveRuntimeServicesByExecutionWorkspace(companyId: string,rows: ExecutionWorkspaceRow[],) {- const executionRuntimeServices = await listCurrentRuntimeServicesForExecutionWorkspaces(- db,- companyId,- rows.map((row) => row.id),- );- const projectWorkspaceIds = rows- .filter((row) => usesInheritedProjectRuntimeServices(row))+ const inheritedRows = rows.filter((row) => usesInheritedProjectRuntimeServices(row));+ const projectWorkspaceIds = inheritedRows.map((row) => row.projectWorkspaceId).filter((value): value is string => Boolean(value));- const projectRuntimeServices = await listCurrentRuntimeServicesForProjectWorkspaces(- db,- companyId,- [...new Set(projectWorkspaceIds)],+ const uniqueProjectWorkspaceIds = [...new Set(projectWorkspaceIds)];+ const [executionRuntimeServices, projectRuntimeServices, projectWorkspaceRows] = await Promise.all([+ listCurrentRuntimeServicesForExecutionWorkspaces(+ db,+ companyId,+ rows.map((row) => row.id),+ ),+ listCurrentRuntimeServicesForProjectWorkspaces(+ db,+ companyId,+ uniqueProjectWorkspaceIds,+ ),+ uniqueProjectWorkspaceIds.length > 0+ ? db+ .select({+ id: projectWorkspaces.id,+ metadata: projectWorkspaces.metadata,+ })+ .from(projectWorkspaces)+ .where(+ and(+ eq(projectWorkspaces.companyId, companyId),+ inArray(projectWorkspaces.id, uniqueProjectWorkspaceIds),+ ),+ )+ : Promise.resolve([]),+ ]);+ const projectRuntimeConfigByWorkspaceId = new Map(+ projectWorkspaceRows.map((row) => [+ row.id,+ readProjectWorkspaceRuntimeConfig((row.metadata as Record<string, unknown> | null) ?? null)?.workspaceRuntime+ ?? null,+ ]),+ );+ const effectiveProjectRuntimeServices = new Map(+ uniqueProjectWorkspaceIds.map((projectWorkspaceId) => [+ projectWorkspaceId,+ selectConfiguredRuntimeServiceRows(+ projectRuntimeServices.get(projectWorkspaceId) ?? [],+ projectRuntimeConfigByWorkspaceId.get(projectWorkspaceId) ?? null,+ ),+ ]),);return new Map(- rows.map((row) => [- row.id,- usesInheritedProjectRuntimeServices(row)- ? (projectRuntimeServices.get(row.projectWorkspaceId!) ?? [])- : (executionRuntimeServices.get(row.id) ?? []),- ]),+ rows.map((row) => {+ if (!usesInheritedProjectRuntimeServices(row)) {+ return [row.id, executionRuntimeServices.get(row.id) ?? []] as const;+ }++ const workspaceRuntime = projectRuntimeConfigByWorkspaceId.get(row.projectWorkspaceId!) ?? null;+ const executionScopedRows = selectConfiguredRuntimeServiceRows(+ (executionRuntimeServices.get(row.id) ?? []).filter(+ (runtimeService) => runtimeService.scopeType !== "project_workspace",+ ),+ workspaceRuntime,+ );+ const effectiveRows = [+ ...(effectiveProjectRuntimeServices.get(row.projectWorkspaceId!) ?? []),+ ...executionScopedRows,+ ].sort(+ (left, right) =>+ (left.configIndex ?? Number.MAX_SAFE_INTEGER) -+ (right.configIndex ?? Number.MAX_SAFE_INTEGER),+ );+ return [row.id, effectiveRows] as const;+ }),);}@@ -1738,8 +1796,13 @@ export function executionWorkspaceService(db: Db) {usesInheritedProjectRuntimeServices(lockedRow)? and(eq(workspaceRuntimeServices.companyId, lockedRow.companyId),- eq(workspaceRuntimeServices.projectWorkspaceId, lockedRow.projectWorkspaceId!),- eq(workspaceRuntimeServices.scopeType, "project_workspace"),+ or(+ and(+ eq(workspaceRuntimeServices.projectWorkspaceId, lockedRow.projectWorkspaceId!),+ eq(workspaceRuntimeServices.scopeType, "project_workspace"),+ ),+ eq(workspaceRuntimeServices.executionWorkspaceId, lockedRow.id),+ ),): and(eq(workspaceRuntimeServices.companyId, lockedRow.companyId),diff --git a/server/src/services/workspace-runtime-read-model.test.ts b/server/src/services/workspace-runtime-read-model.test.tsnew file mode 100644index 0000000000..1de4250b07--- /dev/null+++ b/server/src/services/workspace-runtime-read-model.test.ts@@ -0,0 +1,120 @@+import { randomUUID } from "node:crypto";+import { workspaceRuntimeServices } from "@paperclipai/db";+import { describe, expect, it } from "vitest";+import { selectConfiguredRuntimeServiceRows } from "./workspace-runtime-read-model.js";++type WorkspaceRuntimeServiceRow = typeof workspaceRuntimeServices.$inferSelect;++function runtimeServiceRow(+ overrides: Partial<WorkspaceRuntimeServiceRow> = {},+): WorkspaceRuntimeServiceRow {+ const now = new Date("2026-07-31T10:00:00.000Z");+ return {+ id: randomUUID(),+ companyId: randomUUID(),+ projectId: randomUUID(),+ projectWorkspaceId: randomUUID(),+ executionWorkspaceId: null,+ issueId: null,+ scopeType: "project_workspace",+ scopeId: null,+ serviceName: "web",+ status: "stopped",+ lifecycle: "shared",+ reuseKey: randomUUID(),+ command: "pnpm dev",+ cwd: "/tmp/paperclip",+ port: null,+ url: null,+ provider: "local_process",+ providerRef: null,+ ownerAgentId: null,+ startedByRunId: null,+ lastUsedAt: now,+ startedAt: now,+ stoppedAt: now,+ stopPolicy: null,+ healthStatus: "unknown",+ createdAt: now,+ updatedAt: now,+ ...overrides,+ };+}++describe("selectConfiguredRuntimeServiceRows", () => {+ it("excludes stopped project-workspace history when no services remain configured", () => {+ const historicalRows = Array.from({ length: 163 }, (_, index) =>+ runtimeServiceRow({+ serviceName: `historical-service-${index + 1}`,+ command: `pnpm historical:${index + 1}`,+ }),+ );++ expect(selectConfiguredRuntimeServiceRows(historicalRows, null)).toEqual([]);+ });++ it("selects the newest current row for each configured service and annotates its config index", () => {+ const oldWeb = runtimeServiceRow({+ serviceName: "web",+ command: "pnpm dev",+ updatedAt: new Date("2026-07-29T10:00:00.000Z"),+ });+ const currentWeb = runtimeServiceRow({+ serviceName: "web",+ command: "pnpm dev",+ updatedAt: new Date("2026-07-30T10:00:00.000Z"),+ });+ const removedWorker = runtimeServiceRow({+ serviceName: "worker",+ command: "pnpm worker",+ updatedAt: new Date("2026-07-31T10:00:00.000Z"),+ });++ const selected = selectConfiguredRuntimeServiceRows(+ [removedWorker, currentWeb, oldWeb],+ { services: [{ name: "web", command: "pnpm dev" }] },+ );++ expect(selected).toEqual([+ expect.objectContaining({+ id: currentWeb.id,+ serviceName: "web",+ configIndex: 0,+ }),+ ]);+ });++ it("matches configured services only to rows with the configured reuse scope", () => {+ const staleProjectScopedWorker = runtimeServiceRow({+ serviceName: "worker",+ command: "pnpm worker",+ });+ const executionScopedWorker = runtimeServiceRow({+ executionWorkspaceId: randomUUID(),+ scopeType: "execution_workspace",+ scopeId: randomUUID(),+ serviceName: "worker",+ command: "pnpm worker",+ });++ const selected = selectConfiguredRuntimeServiceRows(+ [staleProjectScopedWorker, executionScopedWorker],+ {+ services: [+ {+ name: "worker",+ command: "pnpm worker",+ reuseScope: "execution_workspace",+ },+ ],+ },+ );++ expect(selected).toEqual([+ expect.objectContaining({+ id: executionScopedWorker.id,+ configIndex: 0,+ }),+ ]);+ });+});diff --git a/server/src/services/workspace-runtime-read-model.ts b/server/src/services/workspace-runtime-read-model.tsindex b492f11110..471211fa43 100644--- a/server/src/services/workspace-runtime-read-model.ts+++ b/server/src/services/workspace-runtime-read-model.ts@@ -1,5 +1,9 @@import type { Db } from "@paperclipai/db";import { workspaceRuntimeServices } from "@paperclipai/db";+import {+ listWorkspaceServiceCommandDefinitions,+ matchWorkspaceRuntimeServiceToCommand,+} from "@paperclipai/shared";import { and, desc, eq, inArray } from "drizzle-orm";type WorkspaceRuntimeServiceRow = typeof workspaceRuntimeServices.$inferSelect;@@ -27,6 +31,42 @@ export function selectCurrentRuntimeServiceRows(rows: WorkspaceRuntimeServiceRowreturn [...current.values()];}+export function selectConfiguredRuntimeServiceRows(+ rows: WorkspaceRuntimeServiceRow[],+ workspaceRuntime: Record<string, unknown> | null | undefined,+) {+ const availableRows = selectCurrentRuntimeServiceRows(rows).map((row) => ({+ ...row,+ configIndex: null as number | null,+ }));+ const selectedRows: Array<WorkspaceRuntimeServiceRow & { configIndex: number | null }> = [];++ for (const command of listWorkspaceServiceCommandDefinitions(workspaceRuntime)) {+ const reuseScope = command.rawConfig.reuseScope;+ const expectedScope =+ reuseScope === "project_workspace" ||+ reuseScope === "execution_workspace" ||+ reuseScope === "agent" ||+ reuseScope === "run"+ ? reuseScope+ : command.lifecycle === "shared"+ ? "project_workspace"+ : "run";+ const matchedRow = matchWorkspaceRuntimeServiceToCommand(+ command,+ availableRows.filter((row) => row.scopeType === expectedScope),+ );+ if (!matchedRow) continue;+ selectedRows.push({+ ...matchedRow,+ configIndex: command.serviceIndex,+ });+ availableRows.splice(availableRows.indexOf(matchedRow), 1);+ }++ return selectedRows;+}+export async function listCurrentRuntimeServicesForProjectWorkspaces(db: RuntimeServiceReadDb,companyId: string,