mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 18:26:40 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - One server process runs every agent on one Node main thread, and
each database statement costs main-thread time
> - The `default` instance settings row is read on hot paths: live run
event delivery, run log redaction, the stranded-task recovery check,
runner tool calls, adapter routes and run preparation
> - A staging measurement with 7 live runs showed the full-row settings
read at 10.24 statements per second, and 3.5 to 5.4 per second when idle
> - The row changes only when an admin or a boot step writes it, so
almost every read returns the same value
> - This pull request adds a per-process read-through cache for that
row, with in-process invalidation on every write and a 2 second age
bound for changes made by another process
> - The benefit is at most one settings read per 2 seconds per server
process, whatever the load
## Linked Issues or Issue Description
**Is your feature request related to a problem?**
The full `instance_settings` row read (`select id, singleton_key,
default_environment_id, general, experimental ...`) runs at 10.24
statements per second on staging with 7 live runs, and 3.5 to 5.4 per
second at idle. It scales with run events and recovery checks, not with
settings changes.
**Describe the solution you would like**
Cache the row per process. Drop the cached row when a settings write
commits, in this process and, through the existing work-signal
notification, in the other process during a deploy overlap. Bound the
age of a cached row to 2 seconds, so any other change (a direct database
edit, a second process outside an overlap) takes effect within 2
seconds.
**Describe alternatives you have considered**
A database trigger with LISTEN/NOTIFY would also catch direct edits, but
it needs a migration, and work notifications cross processes only during
a deploy overlap today. The existing signal plus a 2 second bound keeps
the change small.
## What Changed
- New `server/src/services/instance-settings-cache.ts`: a read-through
cache keyed by the database client. Concurrent misses share one read. A
cached row is at most `INSTANCE_SETTINGS_CACHE_TTL_MS` (2000 ms) old,
measured from the start of the read. Every caller gets its own copy.
Reads through a transaction handle skip the cache.
- `instanceSettingsService` `get`, `getGeneral` and `getExperimental`
use the cache. Write paths (`update`, `updateGeneral`,
`updateExperimental`, and the feedback vote save) still read the row
fresh.
- Every settings write publishes an `instance-settings-changed` work
signal through the existing work-signal channel
(`@paperclipai/db/work-signals`). Inside a transaction it is the first
signal of the write, so its `pg_notify` payload goes out before the
other wakes of the same commit (for example `status-card-evaluation`).
This process drops the cached row when the write commits. During a
deploy overlap, when work notifications cross processes, the other
process drops its cached row on receipt, before a worker woken by the
same write reads the settings. A reconnect of the notification listener
also drops the row.
- `fillUnsetInstanceDefault` writes through `update({ db: tx })`, so its
signal is sent when its transaction commits.
- A read that starts before an invalidation never stores its result, so
an old value can not come back after a write.
- The test setup clears the cache before each test, because many tests
write the row directly.
Hot callers of the cached row:
- Live run event delivery: `live-run-event-redaction.ts`
(`censorUsernameInLogs`), once per delivery batch.
- Run output and run lifecycle redaction: `heartbeat.ts`
`getCurrentUserRedactionOptions`, used by `run-output.ts`,
`run-lifecycle.ts`, `run-completion.ts`.
- The stranded-task recovery check: `recovery/service.ts` reads
`getExperimental().enableAgentChat` once per checked conversation issue.
- Runner tool calls: `paperclip-runner-tool-authority.ts`
(`enableIsolatedWorkspaces`, `enableExternalObjects`).
- Adapter routes: `app.ts` (`enableNativeRunner`, `enableOpenAiDot`) per
request.
- Run preparation: `heartbeat.ts` (`instance_settings` preparation
step), `queued-run-line.ts`, `queued-run-dispatch-liveness.ts`,
`run-control.ts`.
- Issue and comment paths in `issues.ts` (`censorUsernameInLogs`,
`enableAgentChat`).
## Verification
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/instance-settings-cache.test.ts` (embedded PostgreSQL):
- 150 hot reads (`getGeneral`, `getExperimental`, `get` from new service
objects) after one warm read: 0 statements. Without the cache the same
test measures 150 statements (red run).
- 20 concurrent misses: 1 statement.
- `updateExperimental` and `updateGeneral` are visible at once to a new
read in the same process.
- `fillUnsetInstanceDefault` (transaction write of the default
environment) is visible at once after it returns.
- A change written by a second client (another process) becomes visible
within 2000 ms plus a 500 ms test margin.
- A caller that changes the returned object does not change the cached
row.
- A read through a transaction handle sees the transaction's uncommitted
write, two such reads issue 2 statements, and the cache does not keep
the write after rollback.
- A read that started before an invalidation is not stored.
- A received `instance-settings-changed` notification from another
process drops the cached row (next read issues 1 statement).
- `updateExperimental({ enableStatusCards: true })` sends
`instance-settings-changed` as its first notification, before
`status-card-evaluation`; `updateGeneral` sends it alone.
- The server tests that use instance settings or write the row directly
(230 files): see the run notes in the first comment.
## Risks
- A direct database edit, or a change from a second process outside a
deploy overlap, takes up to 2 seconds to apply in this process. Before
this change it applied at the next read. This includes access flags such
as `enableOwnerInstanceAdmin` (read per cloud-tenant request) and the
default environment.
- A change made through the settings service applies at once in this
process, and during a deploy overlap at once in the other process.
- A new code path that writes the `default` row must call
`announceInstanceSettingsChange`, or its change applies within 2
seconds.
- No schema change.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, test runs).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes (no
user-facing setting or command changed)
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
284 lines
20 KiB
TypeScript
284 lines
20 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import express from "express";
|
|
import request from "supertest";
|
|
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
|
import { eq, inArray, sql } from "drizzle-orm";
|
|
import { agents, authUsers, companyMemberships, builtInManagedResources, companies, createDb, environments, instanceSettings, plugins, userCompanyPreferences } from "@paperclipai/db";
|
|
import { projectEnvironmentOptions, withDefaultProjectStorage } from "../services/project-environments.js";
|
|
import { assertProjectStorageEnvironment, projectStorageForEnvironment } from "../services/project-workspace-provider.js";
|
|
import { issueService } from "../services/issues.js";
|
|
import { instanceSettingsService } from "../services/instance-settings.js";
|
|
import { applyDefaultIsolatedExecutionWorkspacePolicy, gateProjectExecutionWorkspacePolicy, parseProjectExecutionWorkspacePolicy, resolveExecutionWorkspaceMode, buildExecutionWorkspaceAdapterConfig, resolveEffectiveWorkspaceStrategyType } from "../services/execution-workspace-policy.js";
|
|
import { projectService } from "../services/projects.js";
|
|
import { preparePluginWorkspace } from "../services/plugin-workspaces.js";
|
|
import { projectRoutes } from "../routes/projects.js";
|
|
import { errorHandler } from "../middleware/index.js";
|
|
import { createPluginWorkspaceFixture } from "./helpers/plugin-workspaces.js";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js";
|
|
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
describe.skipIf(!support.supported)("project environment compatibility", () => {
|
|
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: ReturnType<typeof createDb>;
|
|
beforeAll(async () => {
|
|
database = await startEmbeddedPostgresTestDatabase("project-environments");
|
|
db = createDb(database.connectionString);
|
|
}, 120_000);
|
|
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); });
|
|
beforeEach(async () => { await db.execute(sql`truncate companies, plugins, environments, instance_settings cascade`); });
|
|
|
|
async function fixture() {
|
|
const f = await createPluginWorkspaceFixture(db);
|
|
const [plugin] = await db.select().from(plugins).where(eq(plugins.id, f.pluginId));
|
|
plugin.manifestJson = { ...plugin.manifestJson,
|
|
capabilities: [...plugin.manifestJson.capabilities, "environment.drivers.register"],
|
|
environmentDrivers: [{ driverKey: "tasks", supportsTasks: true, displayName: "Computers", configSchema: { type: "object", properties: {} } }],
|
|
workspaceProvider: { ...plugin.manifestJson.workspaceProvider!, defaultForProjects: { mode: "isolated_workspace", strategy: "git_worktree" } },
|
|
};
|
|
await db.update(plugins).set({ manifestJson: plugin.manifestJson }).where(eq(plugins.id, plugin.id));
|
|
const [computer, local, sandbox, ssh] = await db.insert(environments).values([
|
|
{ name: "Computers", driver: "plugin", config: { pluginKey: plugin.pluginKey, driverKey: "tasks", driverConfig: {} } },
|
|
{ name: "Local", driver: "local" },
|
|
{ name: "Sandbox", driver: "sandbox", config: { provider: "daytona" } },
|
|
{ name: "Build host", driver: "ssh", config: { host: "build.example.com" } },
|
|
]).returning();
|
|
await db.insert(instanceSettings).values({ defaultEnvironmentId: sandbox.id });
|
|
invalidateInstanceSettingsCache();
|
|
return { ...f, plugin, computer, local, sandbox, ssh };
|
|
}
|
|
|
|
it("groups by repository storage, across driver types and provider configurations", async () => {
|
|
const f = await fixture();
|
|
const [otherComputer] = await db.insert(environments).values({ name: "Other computers", driver: "plugin",
|
|
config: { ...f.computer.config, driverConfig: { profile: "other" } } }).returning();
|
|
const [otherSandbox] = await db.insert(environments).values({ name: "Other sandbox", driver: "sandbox", config: { provider: "modal" } }).returning();
|
|
const options = await projectEnvironmentOptions(db, f.companyId);
|
|
expect(options.error).toBeNull();
|
|
expect(options.defaultEnvironmentId).toBe(f.sandbox.id);
|
|
expect(options.groups).toHaveLength(2);
|
|
expect(options.groups.find(group => group.storageProviderPluginId === null)?.environments.map(value => value.id).sort())
|
|
.toEqual([f.local.id, f.sandbox.id, f.ssh.id, otherSandbox.id].sort());
|
|
expect(options.groups.find(group => group.storageProviderPluginId === f.pluginId)?.environments.map(value => value.id).sort())
|
|
.toEqual([f.computer.id, otherComputer.id].sort());
|
|
expect(JSON.stringify(options)).not.toContain("driverConfig");
|
|
expect(JSON.stringify(options)).not.toContain("build.example.com");
|
|
});
|
|
|
|
it("does not equate two plugin drivers with different storage owners", async () => {
|
|
const f = await fixture();
|
|
const other = await createPluginWorkspaceFixture(db, f.companyId);
|
|
await db.update(plugins).set({ manifestJson: { ...f.plugin.manifestJson, id: `test.${other.pluginId}` } }).where(eq(plugins.id, other.pluginId));
|
|
await db.insert(environments).values({ name: "Separate computers", driver: "plugin", config: { pluginKey: `test.${other.pluginId}`, driverKey: "tasks" } });
|
|
expect((await projectEnvironmentOptions(db, f.companyId)).groups).toHaveLength(3);
|
|
expect(projectStorageForEnvironment({ driver: "plugin", config: { pluginKey: f.plugin.pluginKey, driverKey: "unknown" } }, [f.plugin])).toBeNull();
|
|
expect(projectStorageForEnvironment({ driver: "sandbox", config: { provider: "fake" } }, [f.plugin])).toBeNull();
|
|
});
|
|
|
|
it("uses the creating agent, the user's primary agent, then the instance default", async () => {
|
|
const f = await fixture();
|
|
await db.update(agents).set({ defaultEnvironmentId: f.computer.id }).where(eq(agents.id, f.input.agentId));
|
|
await db.insert(userCompanyPreferences).values({ companyId: f.companyId, userId: "person", primaryAgentId: f.input.agentId });
|
|
expect((await projectEnvironmentOptions(db, f.companyId)).defaultEnvironmentId).toBe(f.sandbox.id);
|
|
expect((await projectEnvironmentOptions(db, f.companyId, { userId: "person" })).defaultEnvironmentId).toBe(f.computer.id);
|
|
expect((await projectEnvironmentOptions(db, f.companyId, { agentId: f.input.agentId })).defaultEnvironmentId).toBe(f.computer.id);
|
|
expect(await withDefaultProjectStorage(db, f.companyId, null)).toBeNull();
|
|
expect(await withDefaultProjectStorage(db, f.companyId, null, { userId: "person" })).toMatchObject({ storageProviderPluginId: f.pluginId });
|
|
await db.update(agents).set({ defaultEnvironmentId: null }).where(eq(agents.id, f.input.agentId));
|
|
expect((await projectEnvironmentOptions(db, f.companyId, { userId: "person" })).defaultEnvironmentId).toBe(f.sandbox.id);
|
|
await db.update(instanceSettings).set({ defaultEnvironmentId: null });
|
|
invalidateInstanceSettingsCache();
|
|
expect((await projectEnvironmentOptions(db, f.companyId)).defaultEnvironmentId).toBe(f.local.id);
|
|
});
|
|
|
|
it("pins the selected storage, preserves explicit API choices, and rejects conflicting choices", async () => {
|
|
const f = await fixture();
|
|
const svc = projectService(db);
|
|
const sandboxProject = await svc.createWithRepositories(f.companyId, { name: "Sandbox project" }, [
|
|
{ id: "42", fullName: "example/repo", url: "https://github.com/example/repo", connections: [] },
|
|
]);
|
|
expect(sandboxProject.workspaceProvider?.pluginId).toBeNull();
|
|
const computerProject = await svc.create(f.companyId, { name: "Computer project" }, { environmentId: f.computer.id });
|
|
expect(computerProject.workspaceProvider?.pluginId).toBe(f.pluginId);
|
|
const explicit = { enabled: true, storageProviderPluginId: null };
|
|
expect(await withDefaultProjectStorage(db, f.companyId, explicit)).toEqual(explicit);
|
|
await expect(withDefaultProjectStorage(db, f.companyId, explicit, { environmentId: f.computer.id })).rejects.toMatchObject({ status: 409 });
|
|
await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id });
|
|
invalidateInstanceSettingsCache();
|
|
expect((await svc.getById(sandboxProject.id))?.workspaceProvider?.pluginId).toBeNull();
|
|
});
|
|
|
|
it("saves storage, not a run environment, and keeps that storage after creation", async () => {
|
|
const f = await fixture();
|
|
const svc = projectService(db);
|
|
const core = await svc.create(f.companyId, { name: "Core project" }, { environmentId: f.ssh.id, expectedStorageProviderPluginId: null });
|
|
const managed = await svc.create(f.companyId, { name: "Managed project" }, { environmentId: f.computer.id });
|
|
expect(core).not.toHaveProperty("environmentId");
|
|
expect(core).not.toHaveProperty("legacyEnvironmentId");
|
|
expect(core.workspaceProvider?.pluginId).toBeNull();
|
|
expect(managed.workspaceProvider?.pluginId).toBe(f.pluginId);
|
|
await expect(svc.update(core.id, { executionWorkspacePolicy: { enabled: true, storageProviderPluginId: f.pluginId } }))
|
|
.rejects.toMatchObject({ status: 409, details: { code: "project_storage_locked" } });
|
|
await expect(svc.update(managed.id, { executionWorkspacePolicy: { enabled: true, storageProviderPluginId: null } }))
|
|
.rejects.toMatchObject({ status: 409, details: { code: "project_storage_locked" } });
|
|
expect((await svc.getById(core.id))?.workspaceProvider?.pluginId).toBeNull();
|
|
expect((await svc.getById(managed.id))?.workspaceProvider?.pluginId).toBe(f.pluginId);
|
|
});
|
|
|
|
it("drops a legacy policy environment instead of saving it", async () => {
|
|
const f = await fixture();
|
|
const svc = projectService(db);
|
|
const created = await svc.create(f.companyId, { name: "Legacy create", executionWorkspacePolicy: { enabled: false, environmentId: f.ssh.id } });
|
|
expect(created.executionWorkspacePolicy).toEqual({ enabled: false });
|
|
const updated = await svc.update(created.id, { executionWorkspacePolicy: { enabled: false, environmentId: f.local.id } });
|
|
expect(updated?.executionWorkspacePolicy).toEqual({ enabled: false });
|
|
expect(updated).not.toHaveProperty("environmentId");
|
|
});
|
|
|
|
it("preserves inherited task isolation when checking the observed core storage owner", async () => {
|
|
const f = await fixture();
|
|
const { experimental: settings } = await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true, enableIsolatedWorkspacesByDefault: true });
|
|
const project = await projectService(db).createWithRepositories(f.companyId, { name: "Inherited isolation" }, [
|
|
{ id: "42", fullName: "example/repo", url: "https://github.com/example/repo", connections: [] },
|
|
], { environmentId: f.sandbox.id, expectedStorageProviderPluginId: null });
|
|
expect(project.executionWorkspacePolicy).toBeNull();
|
|
const projectPolicy = applyDefaultIsolatedExecutionWorkspacePolicy({
|
|
projectPolicy: gateProjectExecutionWorkspacePolicy(parseProjectExecutionWorkspacePolicy(project.executionWorkspacePolicy), settings.enableIsolatedWorkspaces),
|
|
defaultIsolatedWorkspacesEnabled: settings.enableIsolatedWorkspacesByDefault,
|
|
hasProjectWorkspace: project.workspaces.length > 0,
|
|
});
|
|
const mode = resolveExecutionWorkspaceMode({ projectPolicy, issueSettings: null, legacyUseProjectWorkspace: null });
|
|
const config = buildExecutionWorkspaceAdapterConfig({ agentConfig: {}, projectPolicy, issueSettings: null, mode, legacyUseProjectWorkspace: null });
|
|
expect(mode).toBe("isolated_workspace");
|
|
expect(resolveEffectiveWorkspaceStrategyType(mode, config)).toBe("git_worktree");
|
|
});
|
|
|
|
it("fails before a provider operation when managed storage cannot serve the selected environment", async () => {
|
|
const f = await fixture();
|
|
expect(() => assertProjectStorageEnvironment(f.plugin, { ...f.sandbox, driver: "sandbox" })).toThrow('does not support the environment "Sandbox"');
|
|
await expect(preparePluginWorkspace(db, f.workers, { ...f.input, environment: { ...f.sandbox, driver: "sandbox" } }))
|
|
.rejects.toMatchObject({ status: 409, details: { code: "project_environment_incompatible", retryable: false } });
|
|
expect(f.calls).toHaveLength(0);
|
|
expect(() => assertProjectStorageEnvironment(f.plugin, { ...f.computer, driver: "plugin" })).not.toThrow();
|
|
});
|
|
|
|
it("excludes archived, company-inaccessible, and disabled plugin environments", async () => {
|
|
const f = await fixture();
|
|
const [otherCompany] = await db.insert(companies).values({ name: "Other", issuePrefix: "OTHER" }).returning();
|
|
await db.insert(builtInManagedResources).values({ companyId: otherCompany.id, bundleKey: "test", resourceKind: "environment",
|
|
resourceKey: "environment", resourceId: f.ssh.id, stockVersion: "1", stockHash: "test" });
|
|
await db.update(environments).set({ status: "archived" }).where(eq(environments.id, f.local.id));
|
|
await db.update(plugins).set({ status: "disabled" }).where(eq(plugins.id, f.pluginId));
|
|
const options = await projectEnvironmentOptions(db, f.companyId);
|
|
expect(options.groups.flatMap(group => group.environments).map(value => value.id)).toEqual([f.sandbox.id]);
|
|
for (const environmentId of [f.local.id, f.ssh.id, f.computer.id, randomUUID()]) {
|
|
await expect(withDefaultProjectStorage(db, f.companyId, null, { environmentId })).rejects.toMatchObject({ status: 409 });
|
|
}
|
|
});
|
|
|
|
it("keeps a cold worker's storage identity, and uses the only storage left after its default is archived", async () => {
|
|
const f = await fixture();
|
|
await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id });
|
|
invalidateInstanceSettingsCache();
|
|
await db.update(plugins).set({ status: "error" }).where(eq(plugins.id, f.pluginId));
|
|
expect(await withDefaultProjectStorage(db, f.companyId, null)).toMatchObject({ storageProviderPluginId: f.pluginId });
|
|
await db.update(environments).set({ status: "archived" }).where(eq(environments.id, f.computer.id));
|
|
expect(await projectEnvironmentOptions(db, f.companyId)).toMatchObject({ defaultEnvironmentId: f.ssh.id, error: null });
|
|
expect(await withDefaultProjectStorage(db, f.companyId, null)).toBeNull();
|
|
});
|
|
|
|
it("refuses to guess storage when the default is unavailable and several storage options remain", async () => {
|
|
const f = await fixture();
|
|
const [fake] = await db.insert(environments).values({ name: "Fake", driver: "sandbox", config: { provider: "fake" } }).returning();
|
|
await db.update(instanceSettings).set({ defaultEnvironmentId: fake.id });
|
|
invalidateInstanceSettingsCache();
|
|
const options = await projectEnvironmentOptions(db, f.companyId);
|
|
expect(options.groups).toHaveLength(2);
|
|
expect(options.defaultEnvironmentId).toBeNull();
|
|
expect(options.error).toBeTruthy();
|
|
await expect(withDefaultProjectStorage(db, f.companyId, null)).rejects.toMatchObject({ status: 409 });
|
|
});
|
|
|
|
it("uses agent computer storage without a choice when managed-only leaves no other environment", async () => {
|
|
const f = await fixture();
|
|
await db.update(environments).set({ status: "archived" }).where(inArray(environments.id, [f.sandbox.id, f.ssh.id]));
|
|
await db.update(instanceSettings).set({ experimental: { enableManagedSandboxOnly: true } });
|
|
invalidateInstanceSettingsCache();
|
|
const options = await projectEnvironmentOptions(db, f.companyId);
|
|
expect(options).toEqual({
|
|
groups: [{ storageProviderPluginId: f.pluginId, environments: [{ id: f.computer.id, name: f.computer.name }] }],
|
|
defaultEnvironmentId: f.computer.id,
|
|
error: null,
|
|
});
|
|
expect(await withDefaultProjectStorage(db, f.companyId, null)).toMatchObject({ storageProviderPluginId: f.pluginId });
|
|
});
|
|
|
|
it.each(["instance", "primary"] as const)("creates repository-free private tasks despite an archived %s default", async source => {
|
|
const f = await fixture();
|
|
const userId = randomUUID();
|
|
const now = new Date();
|
|
await db.insert(authUsers).values({ id: userId, name: "Person", email: `${userId}@example.com`, createdAt: now, updatedAt: now });
|
|
await db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: userId,
|
|
status: "active", membershipRole: "operator" });
|
|
await db.update(environments).set({ status: "archived" }).where(eq(environments.id, f.computer.id));
|
|
if (source === "instance") {
|
|
await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id });
|
|
invalidateInstanceSettingsCache();
|
|
} else {
|
|
await db.update(agents).set({ defaultEnvironmentId: f.computer.id }).where(eq(agents.id, f.input.agentId));
|
|
await db.insert(userCompanyPreferences).values({ companyId: f.companyId, userId, primaryAgentId: f.input.agentId });
|
|
}
|
|
const task = await issueService(db).create(f.companyId, { title: "Private note", visibility: "private", createdByUserId: userId });
|
|
expect(task.visibility).toBe("private");
|
|
const project = await projectService(db).getById(task.projectId!);
|
|
expect(project?.name).toBe("My private tasks");
|
|
expect(project?.executionWorkspacePolicy).toBeNull();
|
|
expect(project?.workspaces).toEqual([]);
|
|
});
|
|
|
|
it("honors managed-only and forced Kubernetes execution policy", async () => {
|
|
const f = await fixture();
|
|
await db.update(environments).set({ metadata: { managedByPaperclip: true, managedKubernetesSandbox: true } }).where(eq(environments.id, f.sandbox.id));
|
|
await db.update(instanceSettings).set({ defaultEnvironmentId: f.local.id, experimental: { enableManagedSandboxOnly: true } });
|
|
invalidateInstanceSettingsCache();
|
|
const managed = await projectEnvironmentOptions(db, f.companyId);
|
|
expect(managed.defaultEnvironmentId).toBe(f.sandbox.id);
|
|
expect(managed.groups.flatMap(group => group.environments).map(value => value.id)).not.toContain(f.local.id);
|
|
await db.update(instanceSettings).set({ general: { executionMode: "kubernetes" } });
|
|
invalidateInstanceSettingsCache();
|
|
const forced = await projectEnvironmentOptions(db, f.companyId);
|
|
expect(forced.groups).toEqual([{ storageProviderPluginId: null, environments: [{ id: f.sandbox.id, name: f.sandbox.name }] }]);
|
|
await expect(withDefaultProjectStorage(db, f.companyId, null, { environmentId: f.computer.id })).rejects.toMatchObject({ status: 409 });
|
|
});
|
|
|
|
it("exposes safe groups and saves a validated choice through the normal API", async () => {
|
|
const f = await fixture();
|
|
function app(actor: Express.Request["actor"]) {
|
|
const result = express(); result.use(express.json());
|
|
result.use((req, _res, next) => { req.actor = actor; next(); });
|
|
result.use("/api", projectRoutes(db)); result.use(errorHandler); return result;
|
|
}
|
|
const board = app({ type: "board", userId: "person", source: "session", companyIds: [f.companyId] });
|
|
const url = `/api/companies/${f.companyId}`;
|
|
const options = await request(board).get(`${url}/project-environments`);
|
|
expect(options.status).toBe(200);
|
|
expect(options.body.groups).toHaveLength(2);
|
|
const created = await request(board).post(`${url}/projects`).send({ name: "Selected", environmentId: f.computer.id });
|
|
expect(created.status).toBe(201);
|
|
expect(created.body.executionWorkspacePolicy).toMatchObject({ storageProviderPluginId: f.pluginId });
|
|
expect(created.body).not.toHaveProperty("environmentId");
|
|
const denied = app({ type: "agent", agentId: f.input.agentId, companyId: randomUUID() });
|
|
expect((await request(denied).get(`${url}/project-environments`)).status).toBe(403);
|
|
expect((await request(app({ type: "none" })).get(`${url}/project-environments`)).status).toBe(401);
|
|
const agent = app({ type: "agent", agentId: f.input.agentId, companyId: f.companyId });
|
|
expect((await request(agent).get(`${url}/project-environments`)).status).toBe(200);
|
|
await db.update(environments).set({ driver: "plugin", config: f.computer.config }).where(eq(environments.id, f.ssh.id));
|
|
const changed = await request(board).post(`${url}/projects`).send({ name: "Changed storage", environmentId: f.ssh.id,
|
|
expectedStorageProviderPluginId: null });
|
|
expect(changed.status).toBe(409);
|
|
expect(changed.body.details.code).toBe("project_environment_incompatible");
|
|
const invalid = await request(board).post(`${url}/projects`).send({ name: "Invalid", environmentId: randomUUID() });
|
|
expect(invalid.status).toBe(409);
|
|
});
|
|
});
|