mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-13 15:55:46 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A project supplies work context and repository storage to task runs. > - Creation selected a storage owner but did not retain the selected environment on the project. > - Configuration stored an environment inside checkout policy, but policy reads and run selection dropped it. > - Projects therefore continued to follow shared agent and instance defaults. > - This pull request saves placement on each project and uses it for new runs. > - The benefit is an independent Project to Environment association with the existing storage, trust, and recovery safeguards. ## Linked Issues or Issue Description Refs #20459 and #11644. Follow-up to #20587. The reported journey is Project > Configuration: changing one project's environment must not change another project's mapping or shared defaults. Related open PR #18176 repairs placement through the legacy workspace-policy field. This follow-up introduces a separate project association, saves creation defaults, and migrates saved legacy references. It overlaps that PR's placement, permission, and recovery safeguards. The changes should be reviewed together. #9588 concerns environment-variable response privacy and does not address placement. ROADMAP.md has no separate project-association work planned. ## What Changed - Add nullable `projects.environment_id` and expose `Project.environmentId`. Save the effective creation default once on the project. Keep environment placement separate from checkout/isolation policy. - Read and write Environment directly in Project Configuration. Keep the control available with isolated workspaces disabled. Each form reads its project's value, even when environment choices share a query cache. - Offer environments compatible with the current storage owner. Change the target and storage together when the existing storage selector attaches a core project to a plugin. Preserve retained-data restrictions and validate the observed storage owner again on save. - Resolve new task runs from their organizational project's target before agent and instance defaults. File sources from another project do not change placement. Explicit low-trust sandbox choices and enforced sandbox policies retain precedence. External provider placement remains separate. - Restore admitted native runs from their owned environment lease. Later project edits apply to new admissions. Require workspace-write permission for environment changes and clears. Check company bindings before runtime admission and during lease creation. - Migrate valid saved policy references into the project column. Normalize legacy API writes. Count and clear matching project references when an environment is deleted. Update API and behavior documentation. - Refresh the maintained SDK source registry for the two changed shared files. Runtime pins are unchanged. ## Verification - [Hosted CI](https://github.com/paperclipai/paperclip/actions/runs/42908045146) is green on `8b3b7d5b5aed51fc4c8e9c2e3506508bbaf9e00c`: **60 successful checks**, three skipped gates, no failures, and `ci / verify` passed. GitHub reports no merge conflicts. Standard Greptile scored the same commit **5/5** with both review threads resolved. - Source checkout on macOS arm64, Node 26.12.0, with fresh isolated PostgreSQL. No production data or live provider calls. - The two-project component test changes the first form with isolation disabled and a shared query cache. The second form keeps its target. Storage changes update only the selected project. A saved target remains selected while the list loads, and an explicit clear remains possible. - API integration creates two projects from the same default, patches one, reads both, and checks that agent and instance defaults remain unchanged. A later instance-default change does not rewrite either saved project target. Tests cover unavailable/incompatible choices, anonymous and cross-company denials, and storage preconditions. - The migration test runs the actual SQL against an existing project row and verifies its environment and disabled checkout policy survive. Deletion accounting and clearing affect only matching project references. - The final guard set passes **53 tests across four files**: `project-environments.test.ts`, `environment-selection-route-guards.test.ts`, `heartbeat/environment-selection.test.ts`, and `ProjectProperties.environment.test.tsx`. All **64 environment-run-orchestrator tests** pass, including direct lease acquisition without an extra caller argument. The broader affected set passed **109 tests across eight files** before the additional admission guards. These sets overlap. - UI typecheck, migration numbering/safety, token gates, module boundaries, query-error rendering, and diff checks pass. `pnpm verify --explain` returns exit 2 and requires broad CI because shared schema/runtime paths and behavior documentation changed. Broad coverage is delegated to current-head CI. - Early iterations failed due to a legacy parser that drops the environment field, a fixture without real company membership, and incorrect expectations for privacy-preserving 404 denials. The service now reads legacy references before normalization, the API fixture has real membership, and denial assertions match the existing privacy contract. The orchestrator mock also needed the reused company-binding guard in its service contract. The focused suites above pass after those corrections. - Local server typecheck remains blocked by installed ACPX, Slack, AI SDK, and Runner type mismatches in unchanged dependency-facing code. It reports no errors in the changed production paths. This is not a full local typecheck or suite pass. Hosted CI supplies full current-head coverage. - SDK source-proof and privacy qualification passes **56 tests across three files**, including the real built SDK. The maintained source registry matches the committed revision; runtime pins are unchanged. - Review reproduced two failures: an incoming policy without a storage owner could be validated before the existing owner was restored, and uppercase legacy UUIDs missed migration matching. Preserve the owner before validation and compare normalized UUID text. Both regressions now pass. The post-fix project/storage/orchestrator batch passes **107 tests**: `node node_modules/vitest/vitest.mjs run server/src/__tests__/project-environments.test.ts server/src/__tests__/project-workspace-provider.integration.test.ts server/src/__tests__/environment-run-orchestrator.test.ts --silent`. - The first hosted run failed build, typecheck, and canary at the same `run-completion.test.ts` call because lease acquisition required a new argument. The lease method now enforces binding internally. Its existing caller compiles without a new field, and the orchestrator tests prove the binding flag reaches the runtime. The full server check no longer reports that error; the local dependency errors above remain. ## Risks - Apply the normal database migration before serving the new revision. The migration adds a nullable foreign key and copies valid legacy project selections. It does not move repository data or resize provider storage. The five newest schema snapshots are retained. - New projects retain their creation target when shared defaults change. Existing projects without a saved selection continue to inherit defaults. A null target explicitly opts into inheritance. - Existing saved project selections now affect placement. Missing, archived, incompatible, and foreign-company targets fail validation; they do not silently choose another storage owner. A running admitted process keeps its original owned lease. - Local dependency limitations are listed above. No live-provider, deployed-browser, or production rollout qualification is claimed. ## Model Used OpenAI Codex, based on GPT-6, with reasoning, tool use, and code execution. The exact serving snapshot and context-window size are not exposed in this session. ## 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 - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
296 lines
9.4 KiB
TypeScript
296 lines
9.4 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import type { ComponentProps } from "react";
|
|
import { flushSync } from "react-dom";
|
|
import { createRoot } from "react-dom/client";
|
|
import type { ExecutionWorkspace, Issue } from "@paperclipai/shared";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { IssueWorkspaceCard } from "./IssueWorkspaceCard";
|
|
|
|
function act(callback: () => void | Promise<void>) {
|
|
let result: void | Promise<void> | undefined;
|
|
flushSync(() => {
|
|
result = callback();
|
|
});
|
|
return result;
|
|
}
|
|
|
|
const useQueryMock = vi.fn();
|
|
|
|
vi.mock("@tanstack/react-query", async () => {
|
|
const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
|
|
return {
|
|
...actual,
|
|
useQuery: (options: unknown) => useQueryMock(options),
|
|
};
|
|
});
|
|
|
|
vi.mock("../context/CompanyContext", () => ({
|
|
useCompany: () => ({ selectedCompanyId: "company-1" }),
|
|
}));
|
|
|
|
vi.mock("@/lib/router", () => ({
|
|
Link: ({ children, className, ...props }: ComponentProps<"a">) => (
|
|
<a className={className} {...props}>{children}</a>
|
|
),
|
|
}));
|
|
|
|
const visibility = vi.hoisted(() => ({ visible: true, loaded: true }));
|
|
vi.mock("@/hooks/useWorkspaceIsolationControls", () => ({ useWorkspaceIsolationControls: () => visibility }));
|
|
beforeEach(() => { visibility.visible = true; visibility.loaded = true; });
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
|
|
|
function createExecutionWorkspace(overrides: Partial<ExecutionWorkspace> = {}): ExecutionWorkspace {
|
|
return {
|
|
id: "workspace-1",
|
|
companyId: "company-1",
|
|
projectId: "project-1",
|
|
projectWorkspaceId: "project-workspace-1",
|
|
sourceIssueId: null,
|
|
mode: "isolated_workspace",
|
|
strategyType: "git_worktree",
|
|
name: "Issue sandbox",
|
|
status: "active",
|
|
deliveryState: "unknown",
|
|
cwd: "/tmp/issue-sandbox",
|
|
repoUrl: null,
|
|
baseRef: null,
|
|
branchName: "paperclip/papa-81",
|
|
providerType: "git_worktree",
|
|
providerRef: null,
|
|
derivedFromExecutionWorkspaceId: null,
|
|
lastUsedAt: new Date("2026-04-16T05:00:00.000Z"),
|
|
openedAt: new Date("2026-04-16T04:59:00.000Z"),
|
|
closedAt: null,
|
|
cleanupEligibleAt: null,
|
|
cleanupReason: null,
|
|
config: {
|
|
environmentId: "env-workspace",
|
|
provisionCommand: null,
|
|
teardownCommand: null,
|
|
cleanupCommand: null,
|
|
workspaceRuntime: null,
|
|
desiredState: null,
|
|
},
|
|
metadata: null,
|
|
runtimeServices: [],
|
|
createdAt: new Date("2026-04-16T04:59:00.000Z"),
|
|
updatedAt: new Date("2026-04-16T05:00:00.000Z"),
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function createIssue(overrides: Partial<Issue> = {}): Issue {
|
|
return {
|
|
id: "issue-1",
|
|
identifier: "PAPA-81",
|
|
companyId: "company-1",
|
|
projectId: "project-1",
|
|
projectWorkspaceId: "project-workspace-1",
|
|
goalId: null,
|
|
parentId: null,
|
|
title: "Sandboxing",
|
|
description: null,
|
|
status: "in_progress",
|
|
priority: "medium",
|
|
reviewPolicy: null,
|
|
assigneeAgentId: "agent-1",
|
|
assigneeUserId: null,
|
|
responsibleUserId: null,
|
|
createdByAgentId: null,
|
|
createdByUserId: null,
|
|
issueNumber: 81,
|
|
requestDepth: 0,
|
|
billingCode: null,
|
|
assigneeAdapterOverrides: null,
|
|
executionWorkspaceId: "workspace-1",
|
|
executionWorkspacePreference: "isolated_workspace",
|
|
executionWorkspaceSettings: {
|
|
mode: "isolated_workspace",
|
|
environmentId: "env-issue",
|
|
},
|
|
checkoutRunId: null,
|
|
executionRunId: null,
|
|
executionAgentNameKey: null,
|
|
executionLockedAt: null,
|
|
startedAt: null,
|
|
completedAt: null,
|
|
cancelledAt: null,
|
|
hiddenAt: null,
|
|
createdAt: new Date("2026-04-16T04:30:00.000Z"),
|
|
updatedAt: new Date("2026-04-16T05:30:00.000Z"),
|
|
labels: [],
|
|
labelIds: [],
|
|
currentExecutionWorkspace: null,
|
|
...overrides,
|
|
workMode: overrides.workMode ?? "standard",
|
|
};
|
|
}
|
|
|
|
describe("IssueWorkspaceCard", () => {
|
|
let container: HTMLDivElement;
|
|
let originalResizeObserver: typeof ResizeObserver | undefined;
|
|
|
|
beforeEach(() => {
|
|
originalResizeObserver = globalThis.ResizeObserver;
|
|
globalThis.ResizeObserver = class ResizeObserver {
|
|
observe() {}
|
|
unobserve() {}
|
|
disconnect() {}
|
|
};
|
|
container = document.createElement("div");
|
|
document.body.appendChild(container);
|
|
useQueryMock.mockReset();
|
|
});
|
|
|
|
afterEach(() => {
|
|
globalThis.ResizeObserver = originalResizeObserver!;
|
|
container.remove();
|
|
});
|
|
|
|
it("keeps workspace details and files while suppressing editing and draft writes", () => {
|
|
visibility.visible = false;
|
|
useQueryMock.mockImplementation((options: { queryKey: unknown[] }) => ({
|
|
data: options.queryKey[0] === "instance" ? { enableIsolatedWorkspaces: true } : [],
|
|
}));
|
|
const root = createRoot(container);
|
|
const onUpdate = vi.fn();
|
|
const onDraftChange = vi.fn();
|
|
const onBrowseFiles = vi.fn();
|
|
act(() => root.render(<IssueWorkspaceCard
|
|
issue={createIssue({ currentExecutionWorkspace: createExecutionWorkspace() })}
|
|
project={{ id: "project-1", executionWorkspacePolicy: { enabled: true, defaultMode: "isolated_workspace" } }}
|
|
initialEditing livePreview onUpdate={onUpdate} onDraftChange={onDraftChange} onBrowseFiles={onBrowseFiles}
|
|
/>));
|
|
expect(container.querySelector("select")).toBeNull();
|
|
expect(container.textContent).not.toContain("Save");
|
|
expect(container.textContent).toContain("View workspace details");
|
|
const browse = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Browse files"));
|
|
act(() => browse!.click());
|
|
expect(onBrowseFiles).toHaveBeenCalledOnce();
|
|
expect(onUpdate).not.toHaveBeenCalled();
|
|
expect(onDraftChange).not.toHaveBeenCalled();
|
|
act(() => root.unmount());
|
|
});
|
|
|
|
it("clears the legacy issue environment override when reusing a workspace", () => {
|
|
const root = createRoot(container);
|
|
const onUpdate = vi.fn();
|
|
const reusableWorkspace = createExecutionWorkspace();
|
|
|
|
useQueryMock.mockImplementation((options: { queryKey: unknown[] }) => {
|
|
if (options.queryKey[0] === "instance") {
|
|
return { data: { enableEnvironments: true, enableIsolatedWorkspaces: true } };
|
|
}
|
|
if (options.queryKey[0] === "environments") {
|
|
return {
|
|
data: [{ id: "env-workspace", name: "Local", driver: "local" }],
|
|
};
|
|
}
|
|
if (options.queryKey[0] === "execution-workspaces") {
|
|
return { data: [reusableWorkspace] };
|
|
}
|
|
return { data: undefined };
|
|
});
|
|
|
|
act(() => {
|
|
root.render(
|
|
<IssueWorkspaceCard
|
|
issue={createIssue()}
|
|
project={{
|
|
id: "project-1",
|
|
environmentId: "env-project",
|
|
executionWorkspacePolicy: {
|
|
enabled: true,
|
|
defaultMode: "isolated_workspace",
|
|
},
|
|
}}
|
|
onUpdate={onUpdate}
|
|
/>,
|
|
);
|
|
});
|
|
|
|
const editButton = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Edit"));
|
|
expect(editButton).not.toBeUndefined();
|
|
|
|
act(() => {
|
|
editButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
|
});
|
|
|
|
const selects = container.querySelectorAll("select");
|
|
expect(selects).toHaveLength(1);
|
|
expect(container.querySelector("button[role='combobox']")?.textContent).toContain("Issue sandbox");
|
|
|
|
const saveButton = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Save"));
|
|
expect(saveButton).not.toBeUndefined();
|
|
|
|
act(() => {
|
|
saveButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
|
});
|
|
|
|
expect(onUpdate).toHaveBeenCalledWith({
|
|
executionWorkspacePreference: "reuse_existing",
|
|
executionWorkspaceId: "workspace-1",
|
|
executionWorkspaceSettings: {
|
|
mode: "isolated_workspace",
|
|
environmentId: null,
|
|
},
|
|
});
|
|
|
|
act(() => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("hides environment UI when environments are disabled", () => {
|
|
const root = createRoot(container);
|
|
|
|
useQueryMock.mockImplementation((options: { queryKey: unknown[] }) => {
|
|
if (options.queryKey[0] === "instance") {
|
|
return { data: { enableEnvironments: false, enableIsolatedWorkspaces: true } };
|
|
}
|
|
if (options.queryKey[0] === "execution-workspaces") {
|
|
return { data: [createExecutionWorkspace()] };
|
|
}
|
|
return { data: undefined };
|
|
});
|
|
|
|
act(() => {
|
|
root.render(
|
|
<IssueWorkspaceCard
|
|
issue={createIssue()}
|
|
project={{
|
|
id: "project-1",
|
|
environmentId: "env-project",
|
|
executionWorkspacePolicy: {
|
|
enabled: true,
|
|
defaultMode: "isolated_workspace",
|
|
},
|
|
}}
|
|
onUpdate={vi.fn()}
|
|
/>,
|
|
);
|
|
});
|
|
|
|
expect(container.textContent).not.toContain("Environment:");
|
|
|
|
const editButton = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Edit"));
|
|
expect(editButton).not.toBeUndefined();
|
|
|
|
act(() => {
|
|
editButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
|
});
|
|
|
|
const selects = container.querySelectorAll("select");
|
|
expect(selects).toHaveLength(1);
|
|
expect(container.querySelector("button[role='combobox']")?.textContent).toContain("Issue sandbox");
|
|
expect(container.textContent).not.toContain("Project default environment");
|
|
|
|
act(() => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
});
|