@@ -1300,6 +948,18 @@ function PrettyPreview({ value }: { value: unknown }) {
if (typeof value === "string") {
return {value};
}
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ return (
+
+ {Object.entries(value as Record).map(([key, field]) => (
+
+
- {key}
+ - {typeof field === "object" && field !== null ? safeStringify(collapseDeep(field, 2)) : cellText(field)}
+
+ ))}
+
+ );
+ }
return (
{safeStringify(collapseDeep(value, 2))}
@@ -1307,6 +967,42 @@ function PrettyPreview({ value }: { value: unknown }) {
);
}
+function PreviewRowCard({ row, index }: { row: Record; index: number }) {
+ const titleKey = ["title", "name", "label"].find((key) => typeof row[key] === "string" && row[key] !== "");
+ const summaryKey = ["highlight", "description", "summary"].find((key) => typeof row[key] === "string" && row[key] !== "");
+ const url = typeof row.url === "string" && /^https?:\/\//i.test(row.url) ? row.url : null;
+ const details = Object.entries(row)
+ .filter(([key]) => key !== titleKey && key !== summaryKey && (key !== "url" || !url))
+ .sort(([left], [right]) => {
+ const order = ["url", "type", "status", "timestamp", "id"];
+ const leftRank = order.indexOf(left);
+ const rightRank = order.indexOf(right);
+ return (leftRank < 0 ? order.length : leftRank) - (rightRank < 0 ? order.length : rightRank);
+ });
+ return (
+
+
+
+ {titleKey ? cellText(row[titleKey]) : `Result ${index + 1}`}
+
+ {url &&
Open link}
+
+ {summaryKey &&
{cellText(row[summaryKey]).replace(/\*\*(.*?)\*\*/g, "$1")}
}
+ {details.length > 0 && (
+
+ {details.slice(0, 3).map(([key, field]) => (
+
+
- {key}
+ - {cellText(field)}
+
+ ))}
+
+ )}
+ {details.length > 3 &&
{details.length - 3} more {details.length === 4 ? "field" : "fields"} in the raw response
}
+
+ );
+}
+
function cellText(value: unknown): string {
if (value === null || value === undefined) return "—";
if (typeof value === "object") return Array.isArray(value) ? `[${value.length}]` : "{…}";
@@ -1325,8 +1021,8 @@ function collapseDeep(value: unknown, maxDepth: number, depth = 0): unknown {
return out;
}
-function RawResponseDisclosure({ value }: { value: unknown }) {
- const [showRaw, setShowRaw] = useState(false);
+function RawResponseDisclosure({ value, initiallyOpen = false }: { value: unknown; initiallyOpen?: boolean }) {
+ const [showRaw, setShowRaw] = useState(initiallyOpen);
if (value === undefined || value === null) return null;
return (
@@ -1384,6 +1080,7 @@ function ErrorResult({
))}
+ {outcome.result.result !== undefined && }
{needsReconnect ? "After reconnecting, run this action again." : "Adjust the input above and try again."}
diff --git a/ui/src/pages/apps/app-detail/PermissionsPanel.tsx b/ui/src/pages/apps/app-detail/PermissionsPanel.tsx
index 033a35f8814..aa08b887c0a 100644
--- a/ui/src/pages/apps/app-detail/PermissionsPanel.tsx
+++ b/ui/src/pages/apps/app-detail/PermissionsPanel.tsx
@@ -12,7 +12,7 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/comp
import { cn } from "@/lib/utils";
import { type InstallState } from "@/lib/tool-installs";
import { QuarantinedActionsReview } from "./SetupPanel";
-import { ActionTestDialog } from "./TestPanel";
+import { ActionTestDialog } from "./ActionTestDialog";
import type { AccessDraft, AppDetailSectionProps } from "./types";
type ActionPermission = "off" | "ask" | "allowed";
diff --git a/ui/src/pages/apps/app-detail/TestPanel.test.tsx b/ui/src/pages/apps/app-detail/TestPanel.test.tsx
deleted file mode 100644
index 3b14ea5c5ad..00000000000
--- a/ui/src/pages/apps/app-detail/TestPanel.test.tsx
+++ /dev/null
@@ -1,575 +0,0 @@
-// @vitest-environment jsdom
-
-import { flushSync } from "react-dom";
-import type { ReactNode } from "react";
-import { createRoot } from "react-dom/client";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import type { ToolCatalogEntry } from "@paperclipai/shared";
-import { TestPanel, errorHints } from "./TestPanel";
-
-const listTestAgentsMock = vi.hoisted(() => vi.fn());
-const getTestAgentAccessMock = vi.hoisted(() => vi.fn());
-const runTestCallMock = vi.hoisted(() => vi.fn());
-const getTestCallStatusMock = vi.hoisted(() => vi.fn());
-const declineActionRequestMock = vi.hoisted(() => vi.fn());
-
-vi.mock("@/api/tools", () => ({
- toolsApi: {
- listTestAgents: (connectionId: string) => listTestAgentsMock(connectionId),
- getTestAgentAccess: (connectionId: string, agentId: string) =>
- getTestAgentAccessMock(connectionId, agentId),
- runTestCall: (connectionId: string, input: unknown) => runTestCallMock(connectionId, input),
- getTestCallStatus: (connectionId: string, actionRequestId: string) =>
- getTestCallStatusMock(connectionId, actionRequestId),
- declineActionRequest: (companyId: string, actionRequestId: string) =>
- declineActionRequestMock(companyId, actionRequestId),
- },
-}));
-
-vi.mock("@/context/CompanyContext", () => ({
- useCompany: () => ({ selectedCompanyId: "company-1", selectedCompany: { id: "company-1", name: "Paperclip" } }),
-}));
-
-vi.mock("@/lib/router", () => ({
- Link: ({ to, children, ...props }: { to: string; children: ReactNode }) => (
-
- {children}
-
- ),
-}));
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
-
-async function act(callback: () => void | Promise) {
- let result: void | Promise = undefined;
- flushSync(() => {
- result = callback();
- });
- await result;
-}
-
-async function flushReact() {
- for (let i = 0; i < 4; i += 1) {
- await act(async () => {
- await Promise.resolve();
- await new Promise((resolve) => window.setTimeout(resolve, 0));
- });
- }
-}
-
-/** The form field input — excludes the "Find an action" search box. */
-function formInput(): HTMLInputElement {
- const inputs = [...container.querySelectorAll("input")].filter(
- (i) => i.getAttribute("aria-label") !== "Find an action",
- );
- return inputs[0] as HTMLInputElement;
-}
-
-async function fillFormField(value: string) {
- const input = formInput();
- expect(input).toBeTruthy();
- const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!;
- await act(async () => {
- setter.call(input, value);
- input.dispatchEvent(new Event("input", { bubbles: true }));
- });
- await flushReact();
-}
-
-/** Wait past the 200ms minimum-spinner delay so the result panel renders. */
-async function settle() {
- await act(async () => {
- await new Promise((resolve) => window.setTimeout(resolve, 260));
- });
- await flushReact();
-}
-
-async function clickByText(text: string) {
- const btn = [...container.querySelectorAll("button")].find((b) => b.textContent?.trim() === text);
- expect(btn).toBeTruthy();
- await act(async () => btn!.click());
- await flushReact();
-}
-
-function catalogEntry(overrides: Partial = {}): ToolCatalogEntry {
- return {
- id: "catalog-read",
- companyId: "company-1",
- applicationId: "app-1",
- connectionId: "conn-1",
- entryKind: "tool",
- toolName: "read_sheet",
- title: "Read a sheet",
- description: "Get rows and cell values from a sheet.",
- inputSchema: {
- type: "object",
- properties: { spreadsheetId: { type: "string", title: "Spreadsheet" } },
- required: ["spreadsheetId"],
- },
- outputSchema: null,
- annotations: null,
- riskLevel: "read",
- isReadOnly: true,
- isWrite: false,
- isDestructive: false,
- status: "active",
- addedAt: new Date("2026-01-01T00:00:00Z"),
- version: null,
- schemaHash: null,
- firstSeenAt: new Date("2026-01-01T00:00:00Z"),
- lastSeenAt: new Date("2026-01-01T00:00:00Z"),
- reviewedAt: null,
- reviewedByAgentId: null,
- reviewedByUserId: null,
- createdAt: new Date("2026-01-01T00:00:00Z"),
- updatedAt: new Date("2026-01-01T00:00:00Z"),
- ...overrides,
- } as ToolCatalogEntry;
-}
-
-function agent(overrides: Record = {}) {
- return {
- id: "agent-claude",
- name: "ClaudeCoder",
- role: "engineer",
- title: "Engineer",
- status: "active",
- orgDepth: 1,
- effectiveAccess: {
- connectionId: "conn-1",
- toolCount: 3,
- allowedCount: 1,
- askFirstCount: 1,
- offCount: 1,
- lastChangedAt: null,
- lastChangedByAgentId: null,
- lastChangedByName: null,
- tools: [
- { toolName: "read_sheet", gatewayToolName: "gs__read_sheet", displayName: "Read a sheet", risk: "read", decision: "allowed", reasonCode: null, matchedPolicyIds: [] },
- { toolName: "append_row", gatewayToolName: "gs__append_row", displayName: "Append a row", risk: "write", decision: "ask_first", reasonCode: null, matchedPolicyIds: [] },
- { toolName: "delete_row", gatewayToolName: "gs__delete_row", displayName: "Delete a row", risk: "destructive", decision: "off", reasonCode: null, matchedPolicyIds: [] },
- ],
- },
- ...overrides,
- };
-}
-
-const readEntry = catalogEntry();
-const writeAskEntry = catalogEntry({
- id: "catalog-append",
- toolName: "append_row",
- title: "Append a row",
- description: "Add a new row to the bottom of a sheet.",
- isReadOnly: false,
- isWrite: true,
- riskLevel: "write",
-});
-const offEntry = catalogEntry({
- id: "catalog-delete",
- toolName: "delete_row",
- title: "Delete a row",
- description: "Remove a row from a sheet permanently.",
- isReadOnly: false,
- isWrite: true,
- isDestructive: true,
- riskLevel: "destructive",
-});
-
-let container: HTMLDivElement;
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-let root: any;
-let client: QueryClient;
-
-function renderPanel(
- active: ToolCatalogEntry[] = [readEntry, writeAskEntry, offEntry],
- quarantined: ToolCatalogEntry[] = [],
-) {
- root.render(
-
-
- ,
- );
-}
-
-beforeEach(() => {
- container = document.createElement("div");
- document.body.appendChild(container);
- root = createRoot(container);
- client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- listTestAgentsMock.mockReset();
- getTestAgentAccessMock.mockReset();
- runTestCallMock.mockReset();
- getTestCallStatusMock.mockReset();
- declineActionRequestMock.mockReset();
- listTestAgentsMock.mockResolvedValue({ agents: [agent()] });
- getTestAgentAccessMock.mockResolvedValue({ access: agent().effectiveAccess });
- // Default ask-first polls report the request still waiting on approval.
- getTestCallStatusMock.mockResolvedValue({
- actionRequestId: "req-1",
- invocationId: "inv-2",
- phase: "waiting",
- parameters: { spreadsheetId: "sheet-123" },
- requestedAt: "2026-06-18T00:00:00.000Z",
- resolvedAt: null,
- durationMs: null,
- });
- window.sessionStorage.clear();
-});
-
-afterEach(() => {
- act(() => root.unmount());
- container.remove();
- window.sessionStorage.clear();
-});
-
-describe("TestPanel", () => {
- it("shows a lightweight agent-loading state before requesting permissions", async () => {
- listTestAgentsMock.mockImplementation(() => new Promise(() => undefined));
-
- await act(async () => renderPanel());
-
- expect(container.textContent).toContain("Loading agents…");
- expect(container.querySelector(".animate-spin")).toBeTruthy();
- expect(container.querySelectorAll('[data-slot="skeleton"]')).not.toHaveLength(0);
- expect(getTestAgentAccessMock).not.toHaveBeenCalled();
- });
-
- it("loads permissions only for the selected agent and reuses the cached summary", async () => {
- await act(async () => renderPanel());
- await flushReact();
-
- expect(getTestAgentAccessMock).toHaveBeenCalledTimes(1);
- expect(getTestAgentAccessMock).toHaveBeenCalledWith("conn-1", "agent-claude");
-
- await act(async () => root.unmount());
- root = createRoot(container);
- await act(async () => renderPanel());
- await flushReact();
-
- expect(getTestAgentAccessMock).toHaveBeenCalledTimes(1);
- });
-
- it("renders the test hierarchy and grouped actions with access badges", async () => {
- await act(async () => renderPanel());
- await flushReact();
-
- expect(container.textContent).toContain("Test an action");
- expect(container.textContent).toContain("Agent");
- expect(container.textContent).toContain("ClaudeCoder");
- expect(container.textContent).toContain("Allowed for 1 action · Ask first for 1 action · Off for 1 action");
- expect(container.textContent).toContain("Read (1)");
- expect(container.textContent).toContain("Write (2)");
- // Each action shows its decision badge.
- expect(container.textContent).toContain("Allowed");
- expect(container.textContent).toContain("Ask first");
- expect(container.textContent).toContain("Off");
- expect(container.querySelector(".bg-card")).toBeNull();
- });
-
- it("defaults to the highest-ranked accessible agent", async () => {
- listTestAgentsMock.mockResolvedValue({
- agents: [
- agent({ id: "agent-report", name: "A report", orgDepth: 2 }),
- agent({ id: "agent-root", name: "Root agent", orgDepth: 0 }),
- agent({ id: "agent-manager", name: "Manager", orgDepth: 1 }),
- ],
- });
-
- await act(async () => renderPanel());
- await flushReact();
-
- expect(container.textContent).toContain("Root agent");
- expect(container.textContent).not.toContain("A report");
- });
-
- it("shows the empty state when there are no actions", async () => {
- await act(async () => renderPanel([]));
- await flushReact();
- expect(container.textContent).toContain("Nothing to test yet");
- expect(container.textContent).toContain("Go to Permissions");
- });
-
- it("renders an allowed result panel with a row-count headline after a successful run", async () => {
- runTestCallMock.mockResolvedValue({
- decision: "allowed",
- invocationId: "inv-1",
- result: [
- { name: "Acme", stage: "Demo" },
- { name: "Globex", stage: "Trial" },
- ],
- });
- await act(async () => renderPanel());
- await flushReact();
-
- // Expand the allowed (read) action.
- const trigger = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Read a sheet"));
- expect(trigger).toBeTruthy();
- await act(async () => trigger!.click());
- await flushReact();
-
- // Fill the required field then Run.
- await fillFormField("sheet-123");
- await clickByText("Run");
- await settle();
-
- expect(runTestCallMock).toHaveBeenCalledWith("conn-1", {
- agentId: "agent-claude",
- toolName: "read_sheet",
- parameters: { spreadsheetId: "sheet-123" },
- });
- expect(container.textContent).toContain("Worked. 2 rows came back.");
- expect(container.textContent).toContain("Ran as ClaudeCoder");
- expect(container.textContent).toContain("Preview");
- });
-
- it.each(["grant_credential_invalid", "oauth_insufficient_scope"])("guides %s failures to reconnect instead of changing action inputs", async (reasonCode) => {
- runTestCallMock.mockResolvedValue({
- decision: "allowed",
- invocationId: "inv-credential",
- error: { message: "The connection must be reconnected.", reasonCode },
- });
- await act(async () => renderPanel());
- await flushReact();
- const trigger = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Read a sheet"));
- await act(async () => trigger!.click());
- await flushReact();
- await fillFormField("sheet-123");
- await clickByText("Run");
- await settle();
-
- expect(container.textContent).toContain("After reconnecting, run this action again.");
- expect(container.textContent).not.toContain("Adjust the input above");
- expect(container.textContent).not.toContain("Check the field formats");
- expect(container.textContent).toContain(reasonCode === "grant_credential_invalid"
- ? "Ask the connection owner to reconnect"
- : "allow the permissions required for this action");
- });
-
- it("renders a failure card (not 'Worked') when an allowed call returns isError:true", async () => {
- // The gateway let the call through (decision:"allowed") but the upstream MCP
- // tool failed at the tool layer — the envelope carries isError + an error.
- runTestCallMock.mockResolvedValue({
- decision: "allowed",
- invocationId: "inv-err",
- result: {
- content: "Invalid arguments: range is required",
- data: { content: [{ type: "text", text: "Invalid arguments: range is required" }], isError: true },
- error: "MCP tool returned an error result",
- },
- });
- await act(async () => renderPanel());
- await flushReact();
-
- const trigger = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Read a sheet"));
- await act(async () => trigger!.click());
- await flushReact();
- await fillFormField("sheet-123");
- await clickByText("Run");
- await settle();
-
- expect(container.textContent).toContain("It didn't work.");
- expect(container.textContent).not.toContain("Worked.");
- // The actual MCP message wins over the generic gateway wrapper string.
- expect(container.textContent).toContain("Invalid arguments: range is required");
- });
-
- it("renders the ask-first card linking to Review", async () => {
- runTestCallMock.mockResolvedValue({ decision: "ask_first", invocationId: "inv-2", actionRequestId: "req-1" });
- await act(async () => renderPanel());
- await flushReact();
-
- const trigger = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Append a row"));
- await act(async () => trigger!.click());
- await flushReact();
-
- await fillFormField("sheet-123");
- await clickByText("Run");
- await settle();
-
- expect(container.textContent).toContain("Sent for your OK.");
- expect(container.textContent).toContain("Cancel this request");
- // "Where" is populated from the polled action-request snapshot.
- expect(container.textContent).toContain("spreadsheetId: sheet-123");
- expect(container.textContent).toContain("Waiting ·");
- const reviewLink = [...container.querySelectorAll("a")].find((a) => a.textContent?.includes("Open Review tab"));
- expect(reviewLink?.getAttribute("href")).toBe("/apps/conn-1/review");
- });
-
- it("restores the ask-first card after leaving and returning to the Test tab", async () => {
- runTestCallMock.mockResolvedValue({ decision: "ask_first", invocationId: "inv-2", actionRequestId: "req-1" });
- await act(async () => renderPanel());
- await flushReact();
-
- const trigger = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Append a row"));
- await act(async () => trigger!.click());
- await flushReact();
- await fillFormField("sheet-123");
- await clickByText("Run");
- await settle();
- expect(container.textContent).toContain("Sent for your OK.");
-
- await act(async () => root.unmount());
- root = createRoot(container);
- await act(async () => renderPanel());
- await flushReact();
-
- expect(runTestCallMock).toHaveBeenCalledTimes(1);
- expect(container.textContent).toContain("Sent for your OK.");
- expect(container.textContent).toContain("spreadsheetId: sheet-123");
- expect(container.textContent).toContain("Cancel this request");
- });
-
- it("shows 'Approved · running' while an approved ask-first call is executing", async () => {
- runTestCallMock.mockResolvedValue({ decision: "ask_first", invocationId: "inv-2", actionRequestId: "req-1" });
- getTestCallStatusMock.mockResolvedValue({
- actionRequestId: "req-1",
- invocationId: "inv-2",
- phase: "running",
- parameters: { spreadsheetId: "sheet-123" },
- requestedAt: "2026-06-18T00:00:00.000Z",
- resolvedAt: "2026-06-18T00:00:05.000Z",
- durationMs: null,
- });
- await act(async () => renderPanel());
- await flushReact();
-
- const trigger = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Append a row"));
- await act(async () => trigger!.click());
- await flushReact();
- await fillFormField("sheet-123");
- await clickByText("Run");
- await settle();
-
- expect(container.textContent).toContain("Approved · running");
- // While running we don't offer cancel — the call is already on its way.
- expect(container.textContent).not.toContain("Cancel this request");
- });
-
- it("mutates the ask-first card into the allowed result once approved and done", async () => {
- runTestCallMock.mockResolvedValue({ decision: "ask_first", invocationId: "inv-2", actionRequestId: "req-1" });
- getTestCallStatusMock.mockResolvedValue({
- actionRequestId: "req-1",
- invocationId: "inv-2",
- phase: "done",
- parameters: { spreadsheetId: "sheet-123" },
- result: [{ name: "Acme", stage: "Demo" }],
- requestedAt: "2026-06-18T00:00:00.000Z",
- resolvedAt: "2026-06-18T00:00:05.000Z",
- durationMs: 1200,
- });
- await act(async () => renderPanel());
- await flushReact();
-
- const trigger = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Append a row"));
- await act(async () => trigger!.click());
- await flushReact();
- await fillFormField("sheet-123");
- await clickByText("Run");
- await settle();
-
- // No longer the pending card — the real response is shown without re-running.
- expect(container.textContent).not.toContain("Sent for your OK.");
- expect(container.textContent).toContain("Worked.");
- expect(container.textContent).toContain("1.2s");
- });
-
- it("shows the denied status when an ask-first call is declined in Review", async () => {
- runTestCallMock.mockResolvedValue({ decision: "ask_first", invocationId: "inv-2", actionRequestId: "req-1" });
- getTestCallStatusMock.mockResolvedValue({
- actionRequestId: "req-1",
- invocationId: "inv-2",
- phase: "denied",
- parameters: { spreadsheetId: "sheet-123" },
- requestedAt: "2026-06-18T00:00:00.000Z",
- resolvedAt: "2026-06-18T00:00:05.000Z",
- durationMs: null,
- });
- await act(async () => renderPanel());
- await flushReact();
-
- const trigger = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Append a row"));
- await act(async () => trigger!.click());
- await flushReact();
- await fillFormField("sheet-123");
- await clickByText("Run");
- await settle();
-
- expect(container.textContent).toContain("Denied — see Review for why");
- expect(container.textContent).not.toContain("Cancel this request");
- });
-
- it("explains an off action and links to Permissions without calling the API", async () => {
- await act(async () => renderPanel());
- await flushReact();
-
- const trigger = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Delete a row"));
- await act(async () => trigger!.click());
- await flushReact();
-
- expect(container.textContent).toContain("Delete a row is off for ClaudeCoder.");
- const permLink = [...container.querySelectorAll("a")].find((a) => a.getAttribute("href") === "/apps/conn-1/permissions");
- expect(permLink).toBeTruthy();
- // No Run button is offered for an off action.
- expect([...container.querySelectorAll("button")].some((b) => b.textContent?.trim() === "Run")).toBe(false);
- expect(runTestCallMock).not.toHaveBeenCalled();
- });
-
- it("shows the 'Last changed by' audit hint when the access summary carries one", async () => {
- getTestAgentAccessMock.mockResolvedValue({
- access: {
- ...agent().effectiveAccess,
- lastChangedAt: new Date(Date.now() - 5 * 60_000).toISOString(),
- lastChangedByAgentId: "agent-admin",
- lastChangedByName: "Dotta",
- },
- });
- await act(async () => renderPanel());
- await flushReact();
-
- const trigger = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Delete a row"));
- await act(async () => trigger!.click());
- await flushReact();
-
- expect(container.textContent).toContain("Last changed by Dotta");
- });
-
- it("surfaces quarantined actions in a 'New' group with the not-yet-on explanation", async () => {
- const quarantinedEntry = catalogEntry({
- id: "catalog-new",
- toolName: "rename_sheet",
- title: "Rename a sheet",
- description: "Change a sheet's name.",
- isReadOnly: false,
- isWrite: true,
- riskLevel: "write",
- status: "quarantined",
- });
- await act(async () => renderPanel([readEntry, writeAskEntry, offEntry], [quarantinedEntry]));
- await flushReact();
-
- expect(container.textContent).toContain("New (1)");
-
- const trigger = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Rename a sheet"));
- expect(trigger).toBeTruthy();
- await act(async () => trigger!.click());
- await flushReact();
-
- expect(container.textContent).toContain("This action is new and hasn't been turned on yet.");
- expect(runTestCallMock).not.toHaveBeenCalled();
- });
-});
-
-describe("errorHints", () => {
- it("maps known reason codes to tailored hints", () => {
- expect(errorHints("Requested entity was not found.", "NOT_FOUND").length).toBeGreaterThan(0);
- expect(errorHints("permission denied", "PERMISSION_DENIED")[0]).toContain("permission");
- expect(errorHints("bad input", "INVALID_ARGUMENT").length).toBeGreaterThan(0);
- expect(errorHints("slow down", "RATE_LIMIT")[0]).toContain("rate-limit");
- });
-
- it("returns the locked generic fallback for an unknown error", () => {
- expect(errorHints("boom", "tool_execution_failed")).toEqual(["Check the inputs above and try again."]);
- });
-});
diff --git a/ui/storybook/stories/action-permissions-test.stories.tsx b/ui/storybook/stories/action-permissions-test.stories.tsx
new file mode 100644
index 00000000000..38f2601ca3d
--- /dev/null
+++ b/ui/storybook/stories/action-permissions-test.stories.tsx
@@ -0,0 +1,243 @@
+import { useEffect, useMemo } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ToolCatalogEntry, ToolConnectionTestCallResult } from "@paperclipai/shared";
+import { queryKeys } from "@/lib/queryKeys";
+import { ActionsSection } from "@/pages/apps/app-detail/PermissionsPanel";
+
+const CONNECTION = "conn-asana-storybook";
+const TOOL: ToolCatalogEntry = {
+ id: "asana-list-projects",
+ companyId: "company-storybook",
+ applicationId: "app-asana",
+ connectionId: CONNECTION,
+ entryKind: "tool",
+ toolName: "list_projects",
+ title: "List projects",
+ description: "Find projects available in this Asana workspace.",
+ inputSchema: { type: "object", properties: {} },
+ outputSchema: null,
+ annotations: null,
+ riskLevel: "read",
+ isReadOnly: true,
+ isWrite: false,
+ isDestructive: false,
+ status: "active",
+ addedAt: new Date("2026-09-01T00:00:00Z"),
+ version: null,
+ schemaHash: null,
+ firstSeenAt: new Date("2026-09-01T00:00:00Z"),
+ lastSeenAt: new Date("2026-10-01T00:00:00Z"),
+ reviewedAt: null,
+ reviewedByAgentId: null,
+ reviewedByUserId: null,
+ createdAt: new Date("2026-09-01T00:00:00Z"),
+ updatedAt: new Date("2026-10-01T00:00:00Z"),
+} as ToolCatalogEntry;
+
+const PROJECTS = [
+ { gid: "1214644669600482", name: "Q4 launch", resource_subtype: "default_project", team: "Marketing" },
+ { gid: "1214644669600483", name: "Customer onboarding", resource_subtype: "default_project", team: "Product" },
+ { gid: "1214644669600484", name: "Support operations", resource_subtype: "default_project", team: "Operations" },
+];
+
+const NOTION_TOOL = {
+ ...TOOL,
+ id: "notion-search",
+ applicationId: "app-notion",
+ toolName: "search",
+ title: "Search Notion",
+ description: "Search pages in your Notion workspace.",
+ inputSchema: { type: "object", properties: { query: { type: "string" } }, required: ["query"] },
+} as ToolCatalogEntry;
+
+const NOTION_RESULTS = [
+ {
+ id: "11111111-2222-4333-8444-555555555555",
+ title: "Northstar launch plan",
+ url: "https://www.notion.so/11111111222243338444555555555555",
+ type: "page",
+ highlight: "The team is tracking launch milestones, owners, dependencies, and the decisions needed before the release window.",
+ timestamp: "2026-09-10T14:30:00.000Z",
+ },
+ {
+ id: "66666666-7777-4888-8999-aaaaaaaaaaaa",
+ title: "Launch customer research",
+ url: "https://www.notion.so/66666666777748888999aaaaaaaaaaaa",
+ type: "page",
+ highlight: "Interviews with early customers point to a clearer onboarding flow and better examples for complex team setups.",
+ timestamp: "2026-09-08T09:15:00.000Z",
+ },
+];
+
+function mcpResult(content: Array>, structuredContent: unknown = null, isError = false) {
+ return {
+ content: content.map((block) => block.type === "text" ? block.text : JSON.stringify(block)).join("\n"),
+ data: { content, structuredContent, isError, transport: "mcp_http", spawnedLocalProcess: false },
+ ...(isError ? { error: "MCP tool returned an error result" } : {}),
+ };
+}
+
+function seededClient(tool: ToolCatalogEntry) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { staleTime: Infinity, gcTime: Infinity, retry: false, refetchOnMount: false } },
+ });
+ client.setQueryData(queryKeys.tools.testAgents(CONNECTION), {
+ agents: [{ id: "agent-ceo", name: "CEO", role: "ceo", title: "CEO", status: "active", orgDepth: 0 }],
+ });
+ client.setQueryData(queryKeys.tools.testAgentAccess(CONNECTION, "agent-ceo"), {
+ access: {
+ connectionId: CONNECTION,
+ toolCount: 1,
+ allowedCount: 1,
+ askFirstCount: 0,
+ offCount: 0,
+ lastChangedAt: null,
+ lastChangedByAgentId: null,
+ lastChangedByName: null,
+ tools: [{
+ toolName: tool.toolName,
+ gatewayToolName: `${tool.applicationId}__${tool.toolName}`,
+ displayName: tool.title,
+ risk: "read",
+ decision: "allowed",
+ reasonCode: null,
+ matchedPolicyIds: [],
+ }],
+ },
+ });
+ return client;
+}
+
+function openAndRun(query?: string) {
+ let step = 0;
+ const tick = (attempt: number) => {
+ if (step === 0) {
+ const button = [...document.querySelectorAll("button")].find((item) => item.textContent?.trim() === "Test");
+ if (button) { button.click(); step = 1; }
+ } else {
+ const dialog = document.querySelector('[role="dialog"]');
+ if (query && step === 1) {
+ const input = dialog?.querySelector('input[placeholder=""]') as HTMLInputElement | null;
+ if (input) {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, query);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ step = 2;
+ }
+ }
+ const run = [...(dialog?.querySelectorAll("button") ?? [])].find((item) => item.textContent?.trim() === "Run");
+ if (run && (!query || step === 2)) { run.click(); return; }
+ }
+ if (attempt < 80) window.setTimeout(() => tick(attempt + 1), 50);
+ };
+ tick(0);
+}
+
+function PermissionsTestStory({ result, tool = TOOL, appName = "Asana", query }: {
+ result: ToolConnectionTestCallResult;
+ tool?: ToolCatalogEntry;
+ appName?: string;
+ query?: string;
+}) {
+ const client = useMemo(() => seededClient(tool), [tool]);
+ useEffect(() => {
+ const original = window.fetch.bind(window);
+ window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
+ if (url.includes(`/tool-connections/${CONNECTION}/test-calls`)) {
+ await new Promise((resolve) => window.setTimeout(resolve, 120));
+ return Response.json(result);
+ }
+ return original(input, init);
+ };
+ const timer = window.setTimeout(() => openAndRun(query), 150);
+ return () => { window.clearTimeout(timer); window.fetch = original; };
+ }, [query, result]);
+ return (
+
+
+
undefined}
+ onReviewQuarantined={() => undefined}
+ onRefreshActions={() => undefined}
+ />
+
+
+ );
+}
+
+const meta = {
+ title: "Apps/Action permissions test",
+ parameters: { layout: "fullscreen" },
+} satisfies Meta;
+export default meta;
+type Story = StoryObj;
+
+export const StructuredRows: Story = {
+ name: "Structured rows",
+ render: () => ,
+};
+
+export const StructuredOnly: Story = {
+ name: "Structured data without content blocks",
+ render: () => ,
+};
+
+export const JsonInText: Story = {
+ name: "JSON inside text",
+ render: () => ,
+};
+
+export const NotionWideSearch: Story = {
+ name: "Notion search with long fields",
+ render: () => ,
+};
+
+export const MixedBlocks: Story = {
+ name: "Mixed content blocks",
+ render: () => ,
+};
+
+export const ToolError: Story = {
+ name: "Tool error with raw response",
+ render: () => ,
+};
+
+export const MalformedBlock: Story = {
+ name: "Unexpected block with raw fallback",
+ render: () => ,
+};
diff --git a/ui/storybook/stories/test-tab.stories.tsx b/ui/storybook/stories/test-tab.stories.tsx
deleted file mode 100644
index e3a7f8391d1..00000000000
--- a/ui/storybook/stories/test-tab.stories.tsx
+++ /dev/null
@@ -1,413 +0,0 @@
-import { useEffect, useMemo, useRef } from "react";
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type {
- ToolCatalogEntry,
- ToolConnectionAccessSummary,
- ToolConnectionTestAgent,
- ToolConnectionTestCallResult,
- ToolConnectionTestDecision,
-} from "@paperclipai/shared";
-import { queryKeys } from "@/lib/queryKeys";
-import { TestPanel } from "@/pages/apps/app-detail/TestPanel";
-
-const CONNECTION = "conn-sheets";
-
-type StoryAgent = ToolConnectionTestAgent & {
- effectiveAccess: ToolConnectionAccessSummary;
-};
-
-// ---------------------------------------------------------------------------
-// Catalog (12 actions: 7 read, 5 write) — mirrors the PAP-11348 wireframes.
-// ---------------------------------------------------------------------------
-
-function tool(
- id: string,
- toolName: string,
- title: string,
- description: string,
- read: boolean,
- inputSchema: Record | null = null,
-): ToolCatalogEntry {
- return {
- id,
- companyId: "company-storybook",
- applicationId: "app-sheets",
- connectionId: CONNECTION,
- entryKind: "tool",
- name: toolName,
- toolName,
- title,
- description,
- inputSchema,
- outputSchema: null,
- annotations: null,
- riskLevel: read ? "read" : "write",
- isReadOnly: read,
- isWrite: !read,
- isDestructive: false,
- status: "active",
- addedAt: new Date("2026-06-01T00:00:00Z"),
- version: null,
- versionHash: null,
- schemaHash: null,
- firstSeenAt: new Date("2026-06-01T00:00:00Z"),
- lastSeenAt: new Date("2026-06-01T00:00:00Z"),
- reviewedAt: null,
- reviewedByAgentId: null,
- reviewedByUserId: null,
- createdAt: new Date("2026-06-01T00:00:00Z"),
- updatedAt: new Date("2026-06-01T00:00:00Z"),
- } as ToolCatalogEntry;
-}
-
-const READ_SHEET_SCHEMA = {
- type: "object",
- properties: {
- spreadsheetId: { type: "string", title: "Spreadsheet" },
- sheet: { type: "string", title: "Sheet" },
- range: { type: "string", title: "Range", description: "e.g. A1:F50" },
- },
- required: ["spreadsheetId", "sheet"],
-};
-
-const APPEND_ROW_SCHEMA = {
- type: "object",
- properties: {
- spreadsheetId: { type: "string", title: "Spreadsheet" },
- sheet: { type: "string", title: "Sheet" },
- values: { type: "string", title: "Values", description: "Comma-separated cell values" },
- },
- required: ["spreadsheetId", "sheet", "values"],
-};
-
-const DELETE_ROW_SCHEMA = {
- type: "object",
- properties: {
- spreadsheetId: { type: "string", title: "Spreadsheet" },
- rowNumber: { type: "number", title: "Row number" },
- },
- required: ["spreadsheetId", "rowNumber"],
-};
-
-const CATALOG: ToolCatalogEntry[] = [
- tool("r1", "list_spreadsheets", "List spreadsheets", "See the spreadsheets in this account.", true),
- tool("r2", "read_sheet", "Read a sheet", "Get rows and cell values from a sheet.", true, READ_SHEET_SCHEMA),
- tool("r3", "search_rows", "Search rows", "Find rows that match a query.", true),
- tool("r4", "get_cell", "Get a cell", "Read a single cell value.", true),
- tool("r5", "list_sheets", "List sheets", "See the tabs in a spreadsheet.", true),
- tool("r6", "get_metadata", "Get spreadsheet info", "Read a spreadsheet's title and tabs.", true),
- tool("r7", "describe_columns", "Describe columns", "List the column headers in a sheet.", true),
- tool("w1", "append_row", "Append a row", "Add a new row to the bottom of a sheet.", false, APPEND_ROW_SCHEMA),
- tool("w2", "update_cell", "Update a cell", "Change a single cell value.", false),
- tool("w3", "create_sheet", "Add a sheet", "Create a new tab in a spreadsheet.", false),
- tool("w4", "clear_range", "Clear a range", "Empty the cells in a range.", false),
- tool("w5", "delete_row", "Delete a row", "Remove a row from a sheet permanently.", false, DELETE_ROW_SCHEMA),
-];
-
-function decisionTool(entry: ToolCatalogEntry, decision: ToolConnectionTestDecision) {
- return {
- toolName: entry.toolName,
- gatewayToolName: `sheets__${entry.toolName}`,
- displayName: entry.title,
- risk: (entry.isReadOnly ? "read" : "write") as "read" | "write" | "destructive",
- decision,
- reasonCode: null,
- matchedPolicyIds: [],
- };
-}
-
-// Decisions: 9 allowed (7 read + 2 write), 2 ask first, 1 off.
-const DECISIONS: Record = {
- list_spreadsheets: "allowed",
- read_sheet: "allowed",
- search_rows: "allowed",
- get_cell: "allowed",
- list_sheets: "allowed",
- get_metadata: "allowed",
- describe_columns: "allowed",
- append_row: "ask_first",
- update_cell: "allowed",
- create_sheet: "allowed",
- clear_range: "ask_first",
- delete_row: "off",
-};
-
-function buildAgent(
- id: string,
- name: string,
- decisions: Record,
- orgDepth = 1,
-): StoryAgent {
- const tools = CATALOG.map((entry) => decisionTool(entry, decisions[entry.toolName]));
- return {
- id,
- name,
- role: "engineer",
- title: "Engineer",
- status: "active",
- orgDepth,
- effectiveAccess: {
- connectionId: CONNECTION,
- toolCount: tools.length,
- allowedCount: tools.filter((t) => t.decision === "allowed").length,
- askFirstCount: tools.filter((t) => t.decision === "ask_first").length,
- offCount: tools.filter((t) => t.decision === "off").length,
- lastChangedAt: null,
- lastChangedByAgentId: null,
- lastChangedByName: null,
- tools,
- },
- };
-}
-
-const AGENTS: StoryAgent[] = [
- buildAgent("agent-claude", "ClaudeCoder", DECISIONS, 0),
- buildAgent("agent-codex", "CodexCoder", {
- ...DECISIONS,
- create_sheet: "ask_first",
- clear_range: "off",
- }),
-];
-
-// ---------------------------------------------------------------------------
-// DOM driver — expand a row, fill its fields, press Run.
-// ---------------------------------------------------------------------------
-
-type Step =
- | { kind: "expand"; title: string }
- | { kind: "fill"; values: string[] }
- | { kind: "click"; label: string };
-
-function setInputValue(input: HTMLInputElement, value: string) {
- const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
- setter?.call(input, value);
- input.dispatchEvent(new Event("input", { bubbles: true }));
-}
-
-function runScript(steps: Step[]) {
- let index = 0;
- const tick = (attempt: number) => {
- if (index >= steps.length) return;
- const step = steps[index];
- if (step.kind === "expand") {
- const btn = Array.from(document.querySelectorAll("button")).find((b) =>
- b.textContent?.includes(step.title),
- );
- if (btn) {
- btn.click();
- index += 1;
- window.setTimeout(() => tick(0), 60);
- return;
- }
- } else if (step.kind === "fill") {
- const inputs = Array.from(document.querySelectorAll("input")).filter(
- (i) => i.getAttribute("aria-label") !== "Find an action" && i.getAttribute("aria-label") !== "Search agents",
- );
- if (inputs.length >= step.values.length) {
- step.values.forEach((value, i) => setInputValue(inputs[i] as HTMLInputElement, value));
- index += 1;
- window.setTimeout(() => tick(0), 60);
- return;
- }
- } else if (step.kind === "click") {
- const btn = Array.from(document.querySelectorAll("button")).find(
- (b) => b.textContent?.trim() === step.label,
- );
- if (btn) {
- btn.click();
- index += 1;
- window.setTimeout(() => tick(0), 60);
- return;
- }
- }
- if (attempt < 40) window.setTimeout(() => tick(attempt + 1), 50);
- };
- tick(0);
-}
-
-function seededClient(agents: StoryAgent[]): QueryClient {
- const client = new QueryClient({
- defaultOptions: { queries: { staleTime: Infinity, gcTime: Infinity, retry: false, refetchOnMount: false } },
- });
- client.setQueryData(queryKeys.tools.testAgents(CONNECTION), {
- agents: agents.map(({ effectiveAccess: _effectiveAccess, ...agent }) => agent),
- });
- for (const agent of agents) {
- client.setQueryData(queryKeys.tools.testAgentAccess(CONNECTION, agent.id), {
- access: agent.effectiveAccess,
- });
- }
- return client;
-}
-
-function TestHost({
- script,
- runResult,
- runDelayMs = 120,
- agents = AGENTS,
- quarantined = [],
-}: {
- script?: Step[];
- runResult?: ToolConnectionTestCallResult;
- runDelayMs?: number;
- agents?: StoryAgent[];
- quarantined?: ToolCatalogEntry[];
-}) {
- const client = useMemo(() => seededClient(agents), [agents]);
- const fetchPatched = useRef(false);
-
- // Stub the test-call POST so the run states render without a backend.
- useEffect(() => {
- if (fetchPatched.current) return;
- fetchPatched.current = true;
- const original = window.fetch.bind(window);
- window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
- const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
- if (url.includes("/test-calls")) {
- await new Promise((resolve) => window.setTimeout(resolve, runDelayMs));
- return Response.json(runResult ?? { decision: "allowed", invocationId: "inv-storybook", result: {} });
- }
- return original(input, init);
- };
- return () => {
- window.fetch = original;
- };
- }, [runResult, runDelayMs]);
-
- useEffect(() => {
- if (!script) return;
- const timer = window.setTimeout(() => runScript(script), 150);
- return () => window.clearTimeout(timer);
- }, [script]);
-
- return (
-
-
-
-
-
- );
-}
-
-const meta: Meta = {
- title: "Apps/Test tab (PAP-11350)",
- parameters: { layout: "fullscreen" },
-};
-export default meta;
-
-type Story = StoryObj;
-
-export const Default: Story = {
- name: "Default — grouped actions + access badges",
- render: () => ,
-};
-
-export const AllowedResult: Story = {
- name: "Allowed — result panel",
- render: () => (
-
- ),
-};
-
-export const AskFirstResult: Story = {
- name: "Ask first — sent for approval",
- render: () => (
-
- ),
-};
-
-export const ErrorResult: Story = {
- name: "Error — what the app said + what to try",
- render: () => (
-
- ),
-};
-
-export const RunningState: Story = {
- name: "Running — in-flight card",
- render: () => (
-
- ),
-};
-
-export const OffAction: Story = {
- name: "Off — explanation + open Permissions",
- render: () => ,
-};
-
-// PAP-11404 — Off side panel polish: audit hint + quarantined variant.
-
-const AGENTS_WITH_AUDIT: StoryAgent[] = AGENTS.map((agent, i) =>
- i === 0
- ? {
- ...agent,
- effectiveAccess: {
- ...agent.effectiveAccess,
- lastChangedAt: new Date("2026-06-17T09:00:00Z").toISOString(),
- lastChangedByAgentId: "agent-admin",
- lastChangedByName: "Dotta",
- },
- }
- : agent,
-);
-
-export const OffAuditHint: Story = {
- name: "Off — last-changed audit hint (PAP-11404)",
- render: () => (
-
- ),
-};
-
-const QUARANTINED: ToolCatalogEntry[] = [
- { ...tool("q1", "rename_sheet", "Rename a sheet", "Change a sheet's name.", false), status: "quarantined" } as ToolCatalogEntry,
-];
-
-export const QuarantinedAction: Story = {
- name: "New — quarantined action not yet on (PAP-11404)",
- render: () => (
-
- ),
-};
From 6f2ce27ca76b8ef3b90079a54e8ad00390b6e8cd Mon Sep 17 00:00:00 2001
From: Devin Foley
Date: Thu, 1 Oct 2026 10:00:25 -0700
Subject: [PATCH 8/8] fix(workspaces): prepare checkouts without a local seed
config (#14810)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Task preparation can create an isolated Git worktree and run its
setup script.
> - The Paperclip repository setup script also prepares a seeded
development instance.
> - A server configured through environment variables can have no local
seed config.
> - This stops ordinary task preparation before the agent starts.
> - This pull request prepares checkout dependencies when no seed source
exists, while preserving errors for invalid sources and existing
development instances.
> - Tasks can start without creating or claiming a seeded development
runtime.
## Linked Issues or Issue Description
**What happened?**
A task with the Paperclip repository fails during setup when the host
has no repository-local or default instance config. The automatic
worktree provisioner requires a seed source even when the task only
needs the checkout.
**Expected behavior**
A plain checkout should prepare its dependencies without a local
development database. A missing custom source, invalid source path, or
existing development instance with a missing source should still fail.
Starting a seeded runtime must still require a valid source.
**Steps to reproduce**
1. Run an environment-configured Paperclip server without a local
instance config.
2. Add the Paperclip repository to a project.
3. Start a task that uses an isolated Git worktree without a custom
provision command.
4. Observe the setup error before agent execution.
**Paperclip version or commit**
Reproduced against `0d3e7bf6ac` with a real script subprocess and
workspace realization regression.
**Deployment mode**
Environment-configured server with external PostgreSQL.
**Additional context**
Searched open and closed GitHub PRs and issues. Related work: Refs
#14795 (seed-source diagnostics) and Refs #11733 (source validation).
This change keeps source validation and seed-readiness checks in place.
## What Changed
- Permit dependency setup when the default seed config is absent
(including the Docker image config path) and the worktree has no
development-instance state.
- Keep missing custom configs, invalid paths, and lost sources for
existing instances as errors.
- Create no config, environment file, or seed manifest for a plain
checkout.
- Keep dependency install failures visible and allow normal instance
setup once a source becomes available.
- Cover the setup script, seed-runtime refusal, and automatic server
worktree realization.
- Document the difference between checkout preparation and
seeded-runtime readiness.
## Verification
- Regression tests failed before the fix for absent-source checkout
preparation and dependency setup.
- `bash -n scripts/provision-worktree.sh`
- `node --test scripts/__tests__/provision-worktree-self-heal.test.mjs`
— 34 passed; 1 existing flock-dependent test skipped on macOS.
- Server regression — 2 passed, covering an unset config and the Docker
image default path.
- `pnpm build` — passed.
- `pnpm -r typecheck` — passed.
- All CI checks passed, including the full test shards, build,
typecheck, browser tests, and canary dry run.
- The first local `pnpm test:run` encountered two chat-test failures
because skill discovery selected an unrelated parent directory. Both
tests pass at the PR commit in a clean temporary checkout. The full
local run was not completed; the redundant clean run was stopped after
the complete CI suite passed.
- `git diff --check` and added-line secrets/PII scan passed.
- Greptile: 5/5, no comments. The branch has no merge conflicts.
- No live tenant deployment or task retry was performed.
## Risks
- A new checkout with no implicit seed config now completes dependency
setup. It has no seeded development instance. A runtime request still
fails until a valid source exists.
- Existing instances and custom source paths retain their failure
behavior. The script does not synthesize a source from environment
credentials or copy a live database.
- No schema, API, or task-setting changes. Revert the commit to restore
the previous setup behavior.
## Model Used
OpenAI Codex (GPT-6), with tool-assisted analysis, code edits, and local
tests. The runtime did not expose a verified model variant or
context-window size.
## 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
---
doc/DEVELOPING.md | 5 +-
.../provision-worktree-self-heal.test.mjs | 116 +++++++++++++++-
scripts/provision-worktree.sh | 129 +++++++++++-------
.../src/__tests__/workspace-runtime.test.ts | 37 +++++
4 files changed, 228 insertions(+), 59 deletions(-)
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md
index 983f2a4ca67..2615e61611e 100644
--- a/doc/DEVELOPING.md
+++ b/doc/DEVELOPING.md
@@ -837,8 +837,9 @@ The default `worktree init` still seeds eagerly. A lean worktree (created withou
- `pnpm paperclipai worktree ensure-seeded` performs the deferred seed **exactly once**. It is lock-guarded and idempotent: only a complete `verified` manifest short-circuits it, so it is safe to call repeatedly and from concurrent processes. Managed workspaces derive the source from the control-plane-provided base project workspace when it carries its own `.paperclip/config.json`, and otherwise from the control plane's own registered instance config; either way the workspace's manifest never selects it. Manual worktrees must pass `--from-config`.
- `paperclipai run` calls `ensureWorktreeSeeded` automatically before doctor/boot. Managed runs transparently seed a lean worktree from their registered base workspace; an unmanaged lean worktree must first run `worktree ensure-seeded --from-config `.
-- Managed Paperclip git worktrees default to the repository's `scripts/provision-worktree.sh` when the strategy omits `provisionCommand`, so the isolated config and pending manifest cannot be silently skipped. Runtime startup also runs `scripts/provision-worktree-runtime.sh` automatically when no explicit runtime provision command is configured and the manifest is not verified. Explicitly configured provision commands still take precedence.
-- If the built-in provisioner reports an unavailable seed source config, decide whether the task needs a seeded development instance or only an isolated checkout. A seeded instance needs a canonical config from the registered base workspace or control-plane instance; environment-only server configuration does not provide that file. For a checkout-only worktree, explicitly set the `git_worktree` strategy's `provisionCommand` to `"true"`. This skips setup and does not establish runtime or seed readiness. Repair rejected symlinks or non-regular source files instead of treating those validation failures as a missing prerequisite.
+- Managed Paperclip git worktrees default to the repository's `scripts/provision-worktree.sh` when the strategy omits `provisionCommand`. When a registered source config exists, setup creates the isolated config and pending manifest. Runtime startup also runs `scripts/provision-worktree-runtime.sh` automatically when no explicit runtime provision command is configured and the manifest is not verified. Explicitly configured provision commands still take precedence.
+- An environment-configured server may have no local seed config. If neither the base checkout nor the default control-plane instance has one, a fresh worktree prepares its dependencies without creating a development instance. This also applies when `PAPERCLIP_CONFIG` names the default `$PAPERCLIP_HOME/instances/$PAPERCLIP_INSTANCE_ID/config.json` path, as the Docker image does. Setup creates no config, environment file, or seed manifest and does not claim runtime or seed readiness. A later request for a seeded development runtime still needs a canonical registered source config. Once that source exists, provisioning the checkout again creates the development instance normally.
+- A missing custom `PAPERCLIP_CONFIG`, rejected symlink, or non-regular source file still fails setup. An existing worktree with a config, environment file, or seed state also fails if its source disappears; setup never downgrades that instance to a plain checkout. Repair the source before retrying.
- The built-in deferred seed is recorded as its own terminal `workspace_seed` operation. A zero exit code is not enough for success: the operation succeeds only when `.paperclip/seed-manifest.json` contains complete verified evidence; failed, missing, or malformed manifests produce a failed operation with the seed phase in metadata.
- Worktrees created before lazy seeding shipped may have neither marker. Paperclip adopts them only after their configured database proves a compatible migration journal and the core Paperclip schema; otherwise managed startup creates a pending manifest and performs the normal verified seed. Manual markerless worktrees must provide `--from-config` so the source remains explicit.
diff --git a/scripts/__tests__/provision-worktree-self-heal.test.mjs b/scripts/__tests__/provision-worktree-self-heal.test.mjs
index bff638cdc44..dcedc7f075a 100644
--- a/scripts/__tests__/provision-worktree-self-heal.test.mjs
+++ b/scripts/__tests__/provision-worktree-self-heal.test.mjs
@@ -102,7 +102,7 @@ process.exit(0);
return baseCwd;
}
-function runProvision(baseCwd, { pathPrefix, setupWorktree, setupInstance, existingWorktree } = {}) {
+function runProvision(baseCwd, { pathPrefix, setupWorktree, setupInstance, existingWorktree, env = {} } = {}) {
const worktreeCwd = existingWorktree ?? makeTempDir("paperclip-provision-worktree-");
setupWorktree?.(worktreeCwd);
const worktreesHome = makeTempDir("paperclip-provision-home-");
@@ -121,14 +121,16 @@ function runProvision(baseCwd, { pathPrefix, setupWorktree, setupInstance, exist
PAPERCLIP_HOME: paperclipHome,
PAPERCLIP_PROJECT_WORKSPACE_ID: "project-workspace-1",
PAPERCLIP_SEED_EXPECTED_COMPANY_ID: "company-1",
+ ...(typeof env === "function" ? env(paperclipHome) : env),
},
});
return { result, worktreeCwd, worktreesHome, paperclipHome };
}
-function runRuntimeProvision(baseCwd, worktreeCwd) {
+function runRuntimeProvision(baseCwd, worktreeCwd, { setupInstance } = {}) {
const worktreesHome = makeTempDir("paperclip-provision-runtime-home-");
const paperclipHome = makeInstanceHome();
+ setupInstance?.(paperclipHome);
return spawnSync("bash", [runtimeScript], {
cwd: worktreeCwd,
encoding: "utf8",
@@ -183,22 +185,122 @@ test("uses the base CLI when its import graph boots", () => {
);
});
-test("explains unavailable instance source config without creating target state", () => {
+for (const defaultConfigInEnv of [false, true]) {
+ test(`prepares a plain checkout without a default instance config (image default env: ${defaultConfigInEnv})`, () => {
+ const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0 });
+ const { result, worktreeCwd } = runProvision(baseCwd, {
+ setupInstance: (home) => fs.rmSync(path.join(home, "instances", "default", "config.json")),
+ env: (home) => defaultConfigInEnv ? { PAPERCLIP_CONFIG: path.join(home, "instances", "default", "config.json") } : {},
+ });
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.match(result.stderr, /preparing checkout dependencies without a seeded development instance/);
+ for (const file of ["config.json", ".env", "seed-manifest.json", "seed-pending", "seed-complete"]) {
+ assert.equal(fs.existsSync(path.join(worktreeCwd, ".paperclip", file)), false);
+ }
+ assert.equal(fs.realpathSync(path.join(worktreeCwd, "cli", "node_modules")), path.join(baseCwd, "cli", "node_modules"));
+ assert.deepEqual(readCliInvocations(baseCwd), []);
+ });
+}
+
+test("rejects a missing custom seed source", () => {
const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0 });
const { result, worktreeCwd } = runProvision(baseCwd, {
- setupInstance: (home) => fs.rmSync(path.join(home, "instances", "default", "config.json")),
+ env: { PAPERCLIP_CONFIG: path.join(baseCwd, "missing", "config.json") },
});
assert.notEqual(result.status, 0);
assert.match(result.stderr, /config is unavailable \(control-plane instance\)/);
assert.match(result.stderr, /For a seeded development instance, configure a canonical config/);
- assert.match(result.stderr, /Only for a checkout-only worktree/);
- assert.match(result.stderr, /workspaceStrategy\.provisionCommand to "true"/);
- assert.match(result.stderr, /does not prepare a development runtime/);
assert.equal(fs.existsSync(path.join(worktreeCwd, ".paperclip")), false);
assert.deepEqual(readCliInvocations(baseCwd), []);
});
+test("initializes a previously plain checkout once a registered seed source is available", () => {
+ const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0 });
+ const first = runProvision(baseCwd, {
+ setupInstance: (home) => fs.rmSync(path.join(home, "instances"), { recursive: true }),
+ });
+ assert.equal(first.result.status, 0, first.result.stderr);
+ assert.deepEqual(readCliInvocations(baseCwd), []);
+
+ const second = runProvision(baseCwd, { existingWorktree: first.worktreeCwd });
+ assert.equal(second.result.status, 0, second.result.stderr);
+ assert.equal(readWorktreeConfig(first.worktreeCwd).$meta.source, "fake-cli");
+ assert.equal(JSON.parse(fs.readFileSync(path.join(first.worktreeCwd, ".paperclip", "seed-manifest.json"), "utf8")).state, "pending");
+});
+
+test("a plain checkout without a source is not ready for a seeded runtime", () => {
+ const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0 });
+ fs.mkdirSync(path.join(baseCwd, "scripts"));
+ fs.copyFileSync(script, path.join(baseCwd, "scripts", "provision-worktree.sh"));
+ const setupInstance = (home) => fs.rmSync(path.join(home, "instances"), { recursive: true });
+ const { result, worktreeCwd } = runProvision(baseCwd, { setupInstance });
+ assert.equal(result.status, 0, result.stderr);
+
+ const runtime = runRuntimeProvision(baseCwd, worktreeCwd, { setupInstance });
+ assert.notEqual(runtime.status, 0);
+ assert.match(runtime.stderr, /Worktree config still does not exist after built-in provisioning/);
+ assert.equal(fs.existsSync(path.join(worktreeCwd, ".paperclip", "seed-manifest.json")), false);
+ assert.deepEqual(readCliInvocations(baseCwd), []);
+});
+
+for (const relativePath of ["instances/default/config.json", "instances/default"]) {
+ test(`rejects a dangling implicit source symlink at ${relativePath}`, () => {
+ const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0 });
+ const { result, worktreeCwd } = runProvision(baseCwd, {
+ setupInstance(home) {
+ const sourcePath = path.join(home, relativePath);
+ fs.rmSync(sourcePath, { recursive: true });
+ fs.symlinkSync(path.join(home, "missing"), sourcePath);
+ },
+ });
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /canonical/);
+ assert.equal(fs.existsSync(path.join(worktreeCwd, ".paperclip")), false);
+ assert.deepEqual(readCliInvocations(baseCwd), []);
+ });
+}
+
+for (const file of ["config.json", ".env", "seed-manifest.json", "seed-pending", "seed-complete"]) {
+ test(`does not downgrade an existing development instance with ${file} when its source disappears`, () => {
+ const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0 });
+ const { result, worktreeCwd } = runProvision(baseCwd, {
+ setupInstance: (home) => fs.rmSync(path.join(home, "instances", "default", "config.json")),
+ setupWorktree(root) {
+ fs.mkdirSync(path.join(root, ".paperclip"));
+ fs.writeFileSync(path.join(root, ".paperclip", file), "retained state\n");
+ },
+ });
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /config is unavailable/);
+ assert.equal(fs.readFileSync(path.join(worktreeCwd, ".paperclip", file), "utf8"), "retained state\n");
+ assert.deepEqual(readCliInvocations(baseCwd), []);
+ });
+}
+
+for (const installExit of [0, 42]) {
+ test(`plain checkout dependency provisioning preserves install exit ${installExit}`, () => {
+ const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0 });
+ const bin = makeTempDir("paperclip-checkout-pnpm-");
+ fs.writeFileSync(path.join(bin, "pnpm"), `#!/bin/sh\nprintf '%s\\n' "$*" >> pnpm-calls\nmkdir -p node_modules cli/node_modules\nexit ${installExit}\n`, { mode: 0o700 });
+ const { result, worktreeCwd } = runProvision(baseCwd, {
+ pathPrefix: bin,
+ setupInstance: (home) => fs.rmSync(path.join(home, "instances", "default", "config.json")),
+ setupWorktree(root) {
+ fs.writeFileSync(path.join(root, "package.json"), "{}\n");
+ fs.writeFileSync(path.join(root, "pnpm-lock.yaml"), "lockfileVersion: '9.0'\n");
+ },
+ });
+ assert.equal(result.status, installExit, result.stderr);
+ assert.match(fs.readFileSync(path.join(worktreeCwd, "pnpm-calls"), "utf8"), /^install --prod=false --frozen-lockfile/);
+ assert.equal(fs.existsSync(path.join(worktreeCwd, ".paperclip", "pnpm-install-fingerprint")), installExit === 0);
+ assert.equal(fs.existsSync(path.join(worktreeCwd, ".paperclip", "config.json")), false);
+ assert.equal(fs.existsSync(path.join(worktreeCwd, ".paperclip", "seed-manifest.json")), false);
+ assert.deepEqual(readCliInvocations(baseCwd), []);
+ });
+}
+
test("rejects a dangling base workspace config symlink instead of falling back", () => {
const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0 });
fs.mkdirSync(path.join(baseCwd, ".paperclip"), { recursive: true });
diff --git a/scripts/provision-worktree.sh b/scripts/provision-worktree.sh
index 2418fa3bb06..bb57604c832 100644
--- a/scripts/provision-worktree.sh
+++ b/scripts/provision-worktree.sh
@@ -5,6 +5,7 @@ base_cwd="${PAPERCLIP_WORKSPACE_BASE_CWD:?PAPERCLIP_WORKSPACE_BASE_CWD is requir
worktree_cwd="${PAPERCLIP_WORKSPACE_CWD:?PAPERCLIP_WORKSPACE_CWD is required}"
paperclip_home="${PAPERCLIP_HOME:-$HOME/.paperclip}"
paperclip_instance_id="${PAPERCLIP_INSTANCE_ID:-default}"
+default_source_config_path="$paperclip_home/instances/$paperclip_instance_id/config.json"
paperclip_dir="$worktree_cwd/.paperclip"
worktree_config_path="$paperclip_dir/config.json"
worktree_env_path="$paperclip_dir/.env"
@@ -53,26 +54,52 @@ if [[ ! -e "$source_config_path" && ! -L "$source_config_path" ]]; then
# A base workspace that is a plain checkout carries no instance config of its own.
# Fall back to the control plane's own registered instance config, which is process
# state this workspace cannot rewrite.
- source_config_path="${PAPERCLIP_CONFIG:-$paperclip_home/instances/$paperclip_instance_id/config.json}"
+ source_config_path="${PAPERCLIP_CONFIG:-$default_source_config_path}"
source_config_origin="control-plane instance"
-fi
-if [[ ! -f "$source_config_path" || -L "$source_config_path" ]]; then
- if [[ ! -e "$source_config_path" && ! -L "$source_config_path" ]]; then
- echo "Registered Paperclip seed source config is unavailable ($source_config_origin): $source_config_path" >&2
- echo "For a seeded development instance, configure a canonical config for that registered source before retrying." >&2
- echo 'Only for a checkout-only worktree, explicitly set workspaceStrategy.provisionCommand to "true". This skips setup; it does not prepare a development runtime.' >&2
- else
- echo "Registered Paperclip seed source config is not a canonical file ($source_config_origin): $source_config_path" >&2
- echo "Repair the registered source path; symlinks and non-regular files are not accepted." >&2
+ # Environment-configured servers need no local instance config. A new plain
+ # checkout can still prepare dependencies without inventing a seed source.
+ # The Docker image sets PAPERCLIP_CONFIG to this default even without a file.
+ # Custom sources and existing development instances must still fail closed.
+ if [[ "$source_config_path" == "$default_source_config_path" && ! -e "$source_config_path" && ! -L "$source_config_path" ]]; then
+ source_required=0
+ for target_state in "$worktree_config_path" "$worktree_env_path" "$seed_manifest_path" "$seed_pending_marker_path" "$seed_complete_marker_path"; do
+ if [[ -e "$target_state" || -L "$target_state" ]]; then
+ source_required=1
+ fi
+ done
+ if [[ "$source_required" -eq 0 ]]; then
+ # Do not mistake a broken or aliased parent path for an absent instance.
+ source_parent="$(dirname "$source_config_path")"
+ while [[ ! -e "$source_parent" && ! -L "$source_parent" ]]; do
+ source_parent="$(dirname "$source_parent")"
+ done
+ if [[ ! -d "$source_parent" || -L "$source_parent" || "$(cd "$source_parent" && pwd -P)" != "$source_parent" ]]; then
+ echo "Registered Paperclip seed source config has a non-canonical parent: $source_config_path" >&2
+ exit 1
+ fi
+ echo "No local Paperclip seed source config; preparing checkout dependencies without a seeded development instance." >&2
+ source_config_path=""
+ fi
fi
- exit 1
fi
-canonical_source_dir="$(cd "$(dirname "$source_config_path")" && pwd -P)"
-if [[ "$canonical_source_dir/config.json" != "$source_config_path" ]]; then
- echo "Registered Paperclip seed source config uses a symlink alias: $source_config_path" >&2
- exit 1
+if [[ -n "$source_config_path" ]]; then
+ if [[ ! -f "$source_config_path" || -L "$source_config_path" ]]; then
+ if [[ ! -e "$source_config_path" && ! -L "$source_config_path" ]]; then
+ echo "Registered Paperclip seed source config is unavailable ($source_config_origin): $source_config_path" >&2
+ echo "For a seeded development instance, configure a canonical config for that registered source before retrying." >&2
+ else
+ echo "Registered Paperclip seed source config is not a canonical file ($source_config_origin): $source_config_path" >&2
+ echo "Repair the registered source path; symlinks and non-regular files are not accepted." >&2
+ fi
+ exit 1
+ fi
+ canonical_source_dir="$(cd "$(dirname "$source_config_path")" && pwd -P)"
+ if [[ "$canonical_source_dir/config.json" != "$source_config_path" ]]; then
+ echo "Registered Paperclip seed source config uses a symlink alias: $source_config_path" >&2
+ exit 1
+ fi
+ source_env_path="$(dirname "$source_config_path")/.env"
fi
-source_env_path="$(dirname "$source_config_path")/.env"
mkdir -p "$paperclip_dir"
@@ -619,44 +646,46 @@ main().catch((error) => {
EOF
}
-if [[ -e "$worktree_config_path" && -e "$worktree_env_path" ]] && existing_worktree_config_is_usable; then
- echo "Reusing existing isolated Paperclip worktree config at $worktree_config_path" >&2
-else
- if [[ -e "$worktree_config_path" || -e "$worktree_env_path" ]]; then
- echo "Existing isolated Paperclip worktree config is stale for this host; regenerating." >&2
- fi
- if paperclipai_command_available; then
- if run_isolated_worktree_init; then
- :
- else
- init_exit_code=$?
- if [[ "$init_exit_code" -eq 127 ]]; then
- # Every CLI candidate was unusable (e.g. an unhealthy base install that
- # the repair could not fix); degrade instead of stranding the run.
- echo "No usable paperclipai CLI found; writing isolated fallback config without DB seeding." >&2
- write_fallback_worktree_config
- else
- # A CLI that ran and failed signals a real problem; do not paper over
- # it with an unseeded fallback config.
- echo "paperclipai worktree init failed (exit $init_exit_code); failing provisioning instead of writing an unseeded fallback config." >&2
- exit "$init_exit_code"
- fi
- fi
+if [[ -n "$source_config_path" ]]; then
+ if [[ -e "$worktree_config_path" && -e "$worktree_env_path" ]] && existing_worktree_config_is_usable; then
+ echo "Reusing existing isolated Paperclip worktree config at $worktree_config_path" >&2
else
- echo "paperclipai worktree init unavailable; writing isolated fallback config without DB seeding." >&2
- write_fallback_worktree_config
+ if [[ -e "$worktree_config_path" || -e "$worktree_env_path" ]]; then
+ echo "Existing isolated Paperclip worktree config is stale for this host; regenerating." >&2
+ fi
+ if paperclipai_command_available; then
+ if run_isolated_worktree_init; then
+ :
+ else
+ init_exit_code=$?
+ if [[ "$init_exit_code" -eq 127 ]]; then
+ # Every CLI candidate was unusable (e.g. an unhealthy base install that
+ # the repair could not fix); degrade instead of stranding the run.
+ echo "No usable paperclipai CLI found; writing isolated fallback config without DB seeding." >&2
+ write_fallback_worktree_config
+ else
+ # A CLI that ran and failed signals a real problem; do not paper over
+ # it with an unseeded fallback config.
+ echo "paperclipai worktree init failed (exit $init_exit_code); failing provisioning instead of writing an unseeded fallback config." >&2
+ exit "$init_exit_code"
+ fi
+ fi
+ else
+ echo "paperclipai worktree init unavailable; writing isolated fallback config without DB seeding." >&2
+ write_fallback_worktree_config
+ fi
+ created_worktree_config=1
fi
- created_worktree_config=1
-fi
-# The target config can predate a deployment-mode change on the registered
-# source, and older/fallback CLI writers may default this field independently.
-# Reconcile it after either create or reuse so the final guest config always
-# carries the source's deployment/auth contract without replacing its database.
-reconcile_worktree_deployment_mode
+ # The target config can predate a deployment-mode change on the registered
+ # source, and older/fallback CLI writers may default this field independently.
+ # Reconcile it after either create or reuse so the final guest config always
+ # carries the source's deployment/auth contract without replacing its database.
+ reconcile_worktree_deployment_mode
-if [[ "$created_worktree_config" -eq 1 && ! -e "$seed_manifest_path" && ! -e "$seed_pending_marker_path" && ! -e "$seed_complete_marker_path" ]]; then
- write_seed_pending_manifest
+ if [[ "$created_worktree_config" -eq 1 && ! -e "$seed_manifest_path" && ! -e "$seed_pending_marker_path" && ! -e "$seed_complete_marker_path" ]]; then
+ write_seed_pending_manifest
+ fi
fi
list_base_node_modules_paths() {
diff --git a/server/src/__tests__/workspace-runtime.test.ts b/server/src/__tests__/workspace-runtime.test.ts
index fd0caefa8e1..187135d1959 100644
--- a/server/src/__tests__/workspace-runtime.test.ts
+++ b/server/src/__tests__/workspace-runtime.test.ts
@@ -920,6 +920,43 @@ describe("realizeExecutionWorkspace", () => {
}
});
+ it.each([false, true])("realizes a plain Paperclip checkout without a local seed instance (image default env: %s)", async (defaultConfigInEnv) => {
+ const repoRoot = await createTempRepo();
+ const paperclipHome = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-env-only-home-")));
+ const previousEnv = {
+ PAPERCLIP_HOME: process.env.PAPERCLIP_HOME,
+ PAPERCLIP_CONFIG: process.env.PAPERCLIP_CONFIG,
+ PAPERCLIP_INSTANCE_ID: process.env.PAPERCLIP_INSTANCE_ID,
+ };
+ try {
+ await fs.mkdir(path.join(repoRoot, "scripts"));
+ await fs.copyFile(provisionWorktreeScriptPath, path.join(repoRoot, "scripts", "provision-worktree.sh"));
+ await runGit(repoRoot, ["add", "scripts/provision-worktree.sh"]);
+ await runGit(repoRoot, ["commit", "-m", "Add Paperclip worktree provisioner"]);
+ process.env.PAPERCLIP_HOME = paperclipHome;
+ process.env.PAPERCLIP_INSTANCE_ID = "default";
+ if (defaultConfigInEnv) process.env.PAPERCLIP_CONFIG = path.join(paperclipHome, "instances", "default", "config.json");
+ else delete process.env.PAPERCLIP_CONFIG;
+
+ const workspace = await realizeWorktreeForTest(repoRoot, "HEAD");
+
+ expect(workspace.strategy).toBe("git_worktree");
+ expect(workspace.created).toBe(true);
+ expect(await readGit(workspace.cwd, ["branch", "--show-current"])).toBe(workspace.branchName);
+ for (const file of ["config.json", ".env", "seed-manifest.json", "seed-pending", "seed-complete"]) {
+ expect(existsSync(path.join(workspace.cwd, ".paperclip", file))).toBe(false);
+ }
+ expect(await fs.readdir(paperclipHome)).toEqual([]);
+ } finally {
+ for (const [key, value] of Object.entries(previousEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ await fs.rm(repoRoot, { recursive: true, force: true });
+ await fs.rm(paperclipHome, { recursive: true, force: true });
+ }
+ });
+
it("defaults the repo-provided worktree provisioner for git worktree strategies", async () => {
const repoRoot = await createTempRepo();
await fs.mkdir(path.join(repoRoot, "scripts"), { recursive: true });