Files
PaperClipAI/ui/src/components/IssueWorkspaceCard.test.tsx
T
Nicky LeachandClaude Opus 5.5 369e238295 fix(projects): make workspace storage the project's only placement choice (#20835)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A repository project gets its working files from core staging or
from a workspace storage plugin
> - #20459 reported that an installed storage plugin attached every new
repository project, so sandbox agents could not use those projects
> - #20587 fixed creation with an **Available in** choice that selects
storage
> - #20651 then saved an environment on every new project and used it
before the agent default to place runs. That solved a problem that did
not exist: the project needs storage, not a run environment
> - Creation saves the first environment of the chosen group, so a
project silently sends every agent's runs to that environment. Project
Configuration also shows two controls (Environment and Workspace
storage) for one decision
> - This pull request removes the project run environment and makes
storage the only placement choice a project owns. Storage is fixed at
creation
> - The benefit is that runs follow the agent again, and project
settings show one clear, read-only fact about storage

## Linked Issues or Issue Description

Refs #20459. Follow-up to #20587 and #20651.

Refs #11644. That issue asks for a project-level run environment
override. This pull request removes the override that #20651 added for
it, because the override is not necessary to fix #20459. #11644 stays a
separate feature request.

Related: #18176 (open) repairs placement through the legacy
workspace-policy field. This pull request does not restore project
placement, so it conflicts with the direction of #18176.

## What Changed

- **Remove the project run environment.** Migration `0466` drops
`projects.environment_id`. Run placement no longer reads the project.
Runs use the agent default, then the instance default, then local
execution. The low-trust task sandbox and the enforced sandbox policies
keep their precedence.
- **Keep the #20651 recovery and binding guards.** A recovered run still
uses its admitted environment lease (source `run`). Company-binding
checks before admission and during lease creation stay.
- **Keep the creation choice.** **Available in** in New Project still
selects storage. It still shows only when the environments need more
than one storage owner. That can only occur when a storage plugin is
installed. `POST /projects` with `environmentId` selects the storage of
that environment and does not save the environment.
- **Fix storage at creation.** `PATCH /projects/:id` rejects any storage
change with `409 project_storage_locked`, from core to a plugin and from
a plugin to core. Before, a core project could move to a plugin.
- **Drop legacy writes.** Older clients can still send
`executionWorkspacePolicy.environmentId`. The service removes it on
create and update.
- **Simplify Project Configuration.** Remove the Environment and
Workspace storage selectors. Show an advisory **Available in** list of
the environments that can use the project's storage. Show it when a
storage plugin is installed or when the project uses one. When the
project's plugin is not installed, show **Storage plugin unavailable**.
Without a storage plugin, show nothing.
- **Issue workspace card.** Remove the "project default" environment
label.
- **Shared contract.** Remove `Project.environmentId`, the
`environmentId` project field, and `expectedStorageProviderPluginId`
from the update schema. The create schema keeps `environmentId` and
`expectedStorageProviderPluginId` from #20587.
- **Docs and maps.** Update `doc/project-environment-compatibility.md`,
`docs/api/goals-and-projects.md`, and the project feature and
agent-access maps.
- **SDK source pins.** Refresh
`tests/runner-e2e/source-sdk-public-inputs.json` for the two shared
files. The shared file blobs return to their values before #20651. The
refresh also corrects the `pnpm-lock.yaml` pin and `lockSha256`:
`master` pins an older lockfile blob than the one it contains.

## Verification

- Targeted server suites pass (227 tests): `project-environments`,
`project-workspace-provider.integration`,
`heartbeat/environment-selection`, `execution-workspace-policy`,
`environment-selection-route-guards`, `environment-run-orchestrator`,
`openapi-routes`.
- Related server suites pass (349 tests): `environment-service`,
`environment-routes`, `plugin-workspaces.integration`, `issues-service`.
- Targeted UI suites pass: `ProjectProperties.concurrency`,
`IssueWorkspaceCard`, `NewProjectDialog`,
`NewProjectDialog.managed-sandbox`, `ProjectDetail`.
- New tests:
- Creation saves storage, not an environment. Core and plugin projects
both reject a storage change with `project_storage_locked`.
  - A legacy policy `environmentId` is dropped on create and update.
- A new run follows the agent default for any project. A recovered run
keeps its admitted lease after the agent default changes.
- Project Configuration has no storage or environment selector. The note
is hidden without a plugin. It lists the core or plugin environments for
the project's storage. It shows **Storage plugin unavailable** for a
removed plugin.
- `pnpm --filter @paperclipai/server typecheck`, `pnpm --filter
@paperclipai/ui typecheck`, and `pnpm --filter @paperclipai/shared
typecheck` pass.
- `pnpm --filter @paperclipai/db check:migrations`, `pnpm
check:token-gates`, `node scripts/check-maps.mjs`, and `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check` pass.
- Not run locally: the full `pnpm test:run`, `pnpm build`, and browser
suites. CI supplies that coverage.
- Manual check: open Project Configuration on an instance with a storage
plugin. Confirm that there is no Environment or Workspace storage
selector, and that **Available in** lists the environments.

## Risks

- **Migration.** `0466` drops `projects.environment_id` and its foreign
key. The migration deletes the saved project environments. Apply it
before you serve the new revision. An old server revision that reads
`projects` fails until it stops. This is the same pattern as earlier
drop-column migrations (`0229`, `0289`).
- **Behavior change for existing projects.** Projects created after
#20651 shipped have a saved environment that overrides the agent. After
this change, their runs follow the agent default again. This is the
intended fix. Before #20651, a project environment selection was not
applied to runs (#11644), so no older behavior is lost.
- **No path from core to a plugin.** A core project, including one
created before a plugin was installed, cannot move to the plugin. To use
plugin storage, create a new project.
- **API.** A `PATCH` that sends `environmentId` or
`expectedStorageProviderPluginId` no longer has an effect. The schema
strips these fields.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) by Anthropic, in Claude Code, with
tool use (shell, file edits, test runs). Extended thinking was
available.

## 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:00:21 -08:00

294 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",
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",
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();
});
});
});