Files
paperclip/tests/e2e/connection-intents.spec.ts
T
DottaandPaperclip 96bf004a79 fix: use persisted state for lifecycle continuation and retry budgets (#13888)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Its control plane decides when a task can continue, wait, stop, or
complete.
> - Legacy continuation could change when an agent changed its wording
without changing task state.
> - Shared attempt counts also let repair and infrastructure retries
affect each other's limits.
> - This pull request uses persisted state and separate, bounded
allowances for these decisions.
> - If automatic repair stops, the task explains what happened and
offers a guarded retry.
> - Paired tests and real-provider evaluations verify that Stop,
approvals, ownership, and spending limits remain authoritative.

## Linked Issues or Issue Description

Related work: Refs #13761, Refs #11126, Refs #13610. These cover
obsolete continuation dispatch and retry storms. Open and closed issues
and PRs were searched for related lifecycle, continuation, and retry
work.

**What happened?**
Legacy continuation depended on English wording and progress heuristics.
Repair, failure retry, and productive continuation could consume shared
counts. When bounded repair stopped, the task showed a technical
recovery message without a clear next action.

**Expected behavior**
Persisted disposition and owned execution paths determine the next
action. Missing disposition prompts bounded agent repair. Explicit work
mode determines planning mode. Narrative changes and raw activity counts
cannot replenish allowances. An exhausted repair shows a readable
notice. An explicit retry checks current controls and preserves the
assigned agent.

**Steps to reproduce**
Run `pnpm test:lifecycle-baseline`. The paired probes keep structured
state constant while varying completion, planning, blocker, and progress
prose. Run the explicit `lifecycle-baseline` and
`continuation-accounting` Product E2E suites for real-provider coverage.
In Storybook, open **Design previews / Recovery notice** to inspect the
production component's normal, pending, acknowledged, unavailable,
failure, and mobile states.

## What Changed

- Hide the image attachment button, icon, and drop/paste hint in answer
composers. Image paste and drop support remains available.
- Merge current master and retain both browser regression sets. Use a
production-stamped service worker in the offline recovery browser
fixture.
- Share one state-based legacy continuation decision across immediate,
delayed, and recovered dispatch. Bind bounded repairs to their source
run and episode.
- Remove title and description wording from work-mode authority. Agents
can still write requested plans in execution mode.
- Persist separate failure-retry and productive-continuation counters.
Disposition repair and resource waits cannot consume or reset those
allowances.
- Validate delayed repair identity, then recheck current gates before
provider dispatch. Fence native startup cancellation.
- Show **Agent needs attention**, a plain-language explanation, **Retry
agent**, and expandable details in both task interfaces. Report request
progress, acknowledgement, and errors inline.
- Store typed recovery notice metadata. Recognize older active notices
only through exact stored action and run IDs. Notice text never grants
retry authority.
- Use the existing recovery-action endpoint for retry. Recheck current
action, status, owner, agent availability, dependencies, active runs,
pending questions and confirmations, approvals, pause controls, and
budget. Duplicate requests do not wake twice.
- Add component, page, route, database, contract, and Storybook
coverage. Keep the scenario inventory and executable evals here.
Historical reports and snapshots live in the [commit-pinned
paperclip-evals
archive](https://github.com/paperclipai/paperclip-evals/blob/ce3e5afcd4a1184650f586a2b5b8be5874c66c8b/experiments/2026-09-lifecycle-authority/README.md).
- Preserve unsaved project fields while the same project URL changes to
its canonical alias. Do not reuse data across projects or companies.
This separate fix addresses the repeated repository-editor browser
failure without changing the browser test.
- Keep the development service worker from intercepting Vite module
reloads. Update the connection-intent browser fixture to record progress
and completion through the agent API.

## Verification

Merge preparation on September 25, commit
`c1e8e4b7ddd9fbc4913ed55ce21b8e12906c2f97`:

- Merged master `bd2030932` and resolved the browser test-list conflict
by keeping both sets of regressions.
- Deterministic lifecycle baseline: 1,090/1,090 assertions passed; no
failures, skips, or missing selected evidence. Unit 423, runner 184,
database integration 397, grading 86.
- Browser support: 17/17 passed. The offline recovery test first failed
with an unstamped development worker, then passed with the production
stamp. Its assertions are unchanged.
- Focused interaction UI and offline fallback tests: 19/19 passed.
Verified the custom-answer composer in Storybook: no attachment controls
or hint; entering an answer enables Next.
- Recursive typecheck, production build, token gates, and diff checks
passed. The worktree is clean. No new real-provider campaign was run.
- Current CI and review: [Current PR CI
passed](https://github.com/paperclipai/paperclip/actions/runs/36166011243):
55 successful checks and two optional Storybook skips. Greptile scored
this exact commit 5/5. Hiding the question attachment controls is an
intentional UI change; paste/drop remains available.

Earlier recovery UI verification, commit
`21be0fec0e90e86b6d662b8ee4831847cd041cdb`:

- Recursive typecheck, production build, token gates, and diff checks
passed.
- Focused UI coverage: 338 tests passed across six suites (336 before
the interaction guard, with the two affected suites rerun at 149 passed
after it). Covers both task interfaces, the real page mutation,
pending/error acknowledgement, stale state, and unavailable controls.
- Recovery database integration: 352 tests passed before the interaction
guard. The complete recovery-action and mutation-route suites passed 181
tests after it. The two new pending question/confirmation regressions
failed before the fix and passed afterward, including
resolved-interaction controls. Shared validator suite: 31 passed. E2E
catalog suites: 34 passed.
- Browser inspection passed for light/dark themes, mobile layout,
expandable details, pending retry, acknowledgement, failure, and
disabled retry. Storybook renders the production component; its request
is simulated.
- The broad local run hit two chat callback-order wait failures and was
stopped after all CI unit/database/runner shards passed. Both local
failures passed when rerun without the competing full-suite process.
- CI exposed a repeated project-repository draft-loss race during
canonical redirects. A new unit regression failed before the fix; all
nine project-page tests now pass, including controls for other projects
and companies. Both unchanged repository browser tests passed against a
fresh local server. UI typecheck, production UI build, and token gates
passed after this fix.
- [Earlier PR CI
passed](https://github.com/paperclipai/paperclip/actions/runs/36072486798)
on `21be0fec0e90e86b6d662b8ee4831847cd041cdb`: 55 successful checks, two
optional Storybook skips, and no failed or pending checks. The
repository browser shard passed with the production fix. Greptile is 5/5
on this exact commit with no unresolved review threads. The PR is
mergeable.

Historical, source-qualified lifecycle evidence:

- Lifecycle baseline: 1,074 assertions. Native session coverage: 447
tests. Product E2E support: 515 tests. Browser support: 11 tests. Full
earlier verification is retained in the archive.
- [Real-provider campaign: 8/8 passed, zero
retries](https://d1p6rlowie26tp.cloudfront.net/runner-e2e/campaigns/gha-35881382080-1/index.html),
source `e88d210417280140b44a36449027290adcb1aeaa`. Evidence and cleanup
checks passed. This includes deliberately exhausted repair cases that
correctly remain blocked; it does not mean every task finished Done.
This campaign predates the recovery UI change.
- Archive migration verified all 16 original JSON files byte-for-byte
and all 24 checksum entries. App tests do not need private archive
access. [Archive PR
#27](https://github.com/paperclipai/paperclip-evals/pull/27) is merged.

## Risks

- Agents that omit durable disposition receive at most two repair
attempts by default. Prose-only completion exposes missing state rather
than silently changing scheduling.
- A retry is an explicit board action. The server rechecks current
controls. A successful response confirms the task returned to To do; it
does not claim that the provider has already started.
- Existing notice metadata remains valid. Only older active notices with
matching structured evidence receive the new UI. Historical notices
without that evidence keep their existing rendering. No schema migration
is required.
- Old run records require conservative retry accounting. Tests cover old
counters, alternating retry lanes, restarts, and exhausted repairs.
- Historical snapshots require private `paperclip-evals` access. The app
index retains public campaign links. Live campaigns qualify specific
sources and scenarios; no new real-provider campaign has run for the
recovery UI commit.

> This fixes existing lifecycle and recovery behavior and does not
duplicate planned core work.

## Model Used

OpenAI GPT-6 through Codex assisted implementation, reasoning, code
execution, and review. The exact serving model ID and context window are
not exposed in this task. Historical real-provider evaluations used
Codex model `gpt-5.6-sol`, separately from the implementation assistant.

## 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 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>
2026-09-25 15:28:11 -07:00

407 lines
14 KiB
TypeScript

import { expect, test, type APIRequestContext } from "@playwright/test";
import { createServer, type Server } from "node:http";
import { listenOnFetchAllowedPort } from "./fetch-allowed-port";
type Json = Record<string, unknown>;
type Seed = { companyId: string; prefix: string };
type Agent = { id: string; name: string };
async function json<T = Json>(
response: Awaited<ReturnType<APIRequestContext["get"]>>,
): Promise<T> {
expect(
response.ok(),
`${response.url()} failed ${response.status()}: ${await response.text()}`,
).toBe(true);
return (await response.json()) as T;
}
async function newCompany(request: APIRequestContext): Promise<Seed> {
const company = await json<{ id: string; issuePrefix: string }>(
await request.post("/api/companies", {
data: { name: `Connection intent E2E ${Date.now()}` },
}),
);
return { companyId: company.id, prefix: company.issuePrefix };
}
async function createAgent(
request: APIRequestContext,
companyId: string,
name: string,
): Promise<Agent> {
return await json<Agent>(
await request.post(`/api/companies/${companyId}/agents`, {
data: {
name,
role: "qa",
title: "Connection intent fixture agent",
capabilities: "Exercises deterministic connection intent wiring.",
adapterType: "process",
adapterConfig: {
command: process.execPath,
args: ["--input-type=module", "-e", "process.exit(0)"],
},
},
}),
);
}
async function startFakeProvider() {
const captures: Array<{ method: string; toolName: string | null }> = [];
const server: Server = createServer(async (req, res) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const payload = JSON.parse(
Buffer.concat(chunks).toString("utf8") || "{}",
) as {
id?: string | number;
method?: string;
params?: { name?: string };
};
captures.push({
method: String(payload.method ?? "<unknown>"),
toolName: payload.params?.name ?? null,
});
res.writeHead(200, { "Content-Type": "application/json" });
if (payload.method === "tools/list") {
res.end(
JSON.stringify({
jsonrpc: "2.0",
id: payload.id ?? null,
result: {
tools: [
{
name: "notion:list_pages",
title: "List fixture pages",
description:
"Reads deterministic pages from the fake Notion provider.",
inputSchema: {
type: "object",
properties: {},
additionalProperties: false,
},
},
],
},
}),
);
return;
}
if (payload.method === "tools/call") {
res.end(
JSON.stringify({
jsonrpc: "2.0",
id: payload.id ?? null,
result: {
content: [{ type: "text", text: "Fixture page inventory" }],
},
}),
);
return;
}
res.end(
JSON.stringify({ jsonrpc: "2.0", id: payload.id ?? null, result: {} }),
);
});
const port = await listenOnFetchAllowedPort(server);
return {
url: `http://127.0.0.1:${port}/`,
captures,
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
};
}
function connectionAwareScript(connectionId: string) {
return `
const post = async (url, body, token = process.env.PAPERCLIP_RUNTIME_TOOLS_TOKEN) => {
const response = await fetch(url, {
method: "POST",
headers: { authorization: \`Bearer \${token}\`, "content-type": "application/json" },
body: JSON.stringify(body)
});
if (!response.ok) throw new Error(\`\${response.status}: \${await response.text()}\`);
return await response.json();
};
const apiHeaders = { authorization: \`Bearer \${process.env.PAPERCLIP_API_KEY}\`, "content-type": "application/json", "x-paperclip-run-id": process.env.PAPERCLIP_RUN_ID };
const runResponse = await fetch(\`\${process.env.PAPERCLIP_API_URL}/api/heartbeat-runs/\${process.env.PAPERCLIP_RUN_ID}\`, { headers: apiHeaders });
if (!runResponse.ok) throw new Error(await runResponse.text());
const run = await runResponse.json();
const issueId = process.env.PAPERCLIP_TASK_ID ?? run.contextSnapshot.issueId;
if (!issueId) throw new Error("Missing task binding");
const search = await post(process.env.PAPERCLIP_RUNTIME_TOOLS_CONNECTIONS_SEARCH_URL, { query: "notion" });
const notion = search.results.find((result) => result.service === "notion");
if (!notion) throw new Error("Notion was not advertised");
if (notion.state !== "ready") {
const requested = await post(process.env.PAPERCLIP_RUNTIME_TOOLS_CONNECTION_REQUEST_URL, { service: notion.service });
if (requested.state !== "needs_user_action") throw new Error("Expected a user-action request");
const comment = await fetch(\`\${process.env.PAPERCLIP_API_URL}/api/issues/\${issueId}/comments\`, {
method: "POST",
headers: apiHeaders,
body: JSON.stringify({ body: "Requested Notion access through the connection card." })
});
if (!comment.ok) throw new Error(await comment.text());
console.log("waiting for connection intent");
process.exit(0);
}
const sessionResponse = await fetch(\`\${process.env.PAPERCLIP_API_URL}/api/tool-gateway/sessions\`, {
method: "POST",
headers: apiHeaders,
body: JSON.stringify({ runId: process.env.PAPERCLIP_RUN_ID, ttlMs: 60000 })
});
if (!sessionResponse.ok) throw new Error(await sessionResponse.text());
const session = await sessionResponse.json();
const toolsResponse = await fetch(\`\${process.env.PAPERCLIP_API_URL}/api/tool-gateway/tools\`, {
headers: { "x-paperclip-tool-gateway-token": session.token }
});
const tools = await toolsResponse.json();
const tool = tools.find((entry) => entry.connectionId === ${JSON.stringify(connectionId)} && entry.upstreamToolName === "notion:list_pages");
if (!tool) throw new Error("Continuation did not receive the installed Notion tool");
const call = await fetch(\`\${process.env.PAPERCLIP_API_URL}/api/tool-gateway/tools/call\`, {
method: "POST",
headers: { "x-paperclip-tool-gateway-token": session.token, "content-type": "application/json" },
body: JSON.stringify({ tool: tool.name, parameters: {} })
});
if (!call.ok) throw new Error(await call.text());
console.log(await call.text());
// Successful tool use must end with a durable task disposition.
const completion = await fetch(\`\${process.env.PAPERCLIP_API_URL}/api/issues/\${issueId}\`, {
method: "PATCH",
headers: apiHeaders,
body: JSON.stringify({ status: "done", comment: "Read the requested Notion page inventory." })
});
if (!completion.ok) throw new Error(await completion.text());
`;
}
function escapeRegExp(value: string) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
async function waitForAgentRun(
request: APIRequestContext,
companyId: string,
agentId: string,
) {
let terminalRun: { id: string; status: string } | null = null;
await expect
.poll(
async () => {
const runs = await json<Array<{ id: string; status: string }>>(
await request.get(
`/api/companies/${companyId}/heartbeat-runs?agentId=${agentId}&limit=10`,
),
);
terminalRun =
runs.find((run) => !["queued", "running"].includes(run.status)) ??
null;
return terminalRun?.status ?? null;
},
{ timeout: 45_000 },
)
.toBe("succeeded");
if (!terminalRun)
throw new Error("Agent run completed without a run receipt");
return terminalRun;
}
test("store setup and task connection intent share one fake provider through continuation", async ({
page,
request,
}) => {
test.setTimeout(180_000);
const provider = await startFakeProvider();
try {
const seed = await newCompany(request);
const holder = await createAgent(
request,
seed.companyId,
"Existing access holder",
);
// Entry point one: connect and test the provider through the Connections store.
await page.goto(`/${seed.prefix}/apps`);
await expect(page.getByRole("heading", { name: "Connectors" })).toBeVisible({
timeout: 30_000,
});
const customConnector = page
.getByRole("list", { name: "Connector list" })
.getByRole("listitem")
.filter({ hasText: "Connect your own tool" });
await customConnector.getByRole("button", { name: "Connect", exact: true }).click();
await customConnector.getByRole("button", { name: "Connect your own MCP server" }).click();
await page
.getByPlaceholder("https://example.com/actions")
.fill(provider.url);
await page.getByRole("button", { name: "Continue" }).click();
await page.getByRole("button", { name: "Save and continue" }).click();
await page.getByRole("button", { name: /Check link/i }).click();
// A no-auth read-only provider can complete the access/install defaults in
// one commit. Other methods exercise the same intermediate steps in the
// shared-flow component suite.
await expect(page.getByRole("heading", { name: /is ready/i })).toBeVisible({
timeout: 30_000,
});
const connections = await json<{
connections: Array<{ id: string; name: string; config: Json }>;
}>(await request.get(`/api/companies/${seed.companyId}/tools/connections`));
expect(connections.connections).toHaveLength(1);
const connection = connections.connections[0]!;
const connectionId = connection.id;
await json(
await request.patch(`/api/tool-connections/${connectionId}`, {
data: {
config: {
...connection.config,
url: provider.url,
sourceTemplateKey: "notion",
},
},
}),
);
await json(
await request.put(`/api/tool-connections/${connectionId}/installs`, {
data: {
installs: [{ targetType: "agent", targetId: holder.id }],
},
}),
);
await page.goto(`/${seed.prefix}/apps/${connectionId}/permissions`);
const actionRow = page.locator("[data-action-id]").filter({ hasText: "List fixture pages" });
await actionRow.getByRole("button", { name: "Test", exact: true }).click();
await expect(
page.getByRole("heading", { name: "Test List fixture pages" }),
).toBeVisible({ timeout: 30_000 });
await page.getByRole("button", { name: "Run", exact: true }).click();
await expect(page.getByText("Fixture page inventory")).toBeVisible({
timeout: 30_000,
});
const callsBeforeContinuation = provider.captures.filter(
(capture) => capture.method === "tools/call" && capture.toolName === "notion:list_pages",
).length;
// Entry point two: a scripted agent requests Notion, then the same shared
// provider is reused from the task dialog and appears in the fresh run.
const scout = await createAgent(
request,
seed.companyId,
"Connection requester",
);
await json(
await request.patch(`/api/agents/${scout.id}`, {
data: {
adapterType: "process",
adapterConfig: {
command: process.execPath,
args: [
"--input-type=module",
"-e",
connectionAwareScript(connectionId),
],
},
replaceAdapterConfig: true,
},
}),
);
const issue = await json<{ id: string; identifier: string }>(
await request.post(`/api/companies/${seed.companyId}/issues`, {
data: {
title: "Read our Notion pages",
status: "in_progress",
assigneeAgentId: scout.id,
},
}),
);
// Assigning an in-progress task is the production wake path. Waiting for
// that run avoids creating a second artificial request from an explicit
// heartbeat invocation.
const firstRun = await waitForAgentRun(request, seed.companyId, scout.id);
const taskUrl = `/${seed.prefix}/issues/${issue.identifier}`;
await page.goto(taskUrl);
await expect(
page.getByText("Connection requester needs Notion"),
).toBeVisible({ timeout: 30_000 });
await page.getByRole("button", { name: "Connect / Use existing" }).click();
await expect(
page.getByRole("heading", { name: "Use an existing connection" }),
).toBeVisible();
await page
.getByRole("button", { name: new RegExp(escapeRegExp(connection.name)) })
.click();
await expect(page.getByText("Notion connected")).toBeVisible({
timeout: 30_000,
});
await expect(page).toHaveURL(new RegExp(`${taskUrl}$`));
await expect(
page
.getByTestId("connection-intent-focus-target")
.filter({ hasText: "Notion connected" }),
).toBeFocused();
expect(await page.locator("body").innerText()).not.toMatch(
/\/authorize\?|authorizationUrl/,
);
await expect
.poll(
async () => {
const runs = await json<Array<{ id: string; status: string }>>(
await request.get(
`/api/companies/${seed.companyId}/heartbeat-runs?agentId=${scout.id}&limit=10`,
),
);
return runs.find((run) => run.id !== firstRun.id)?.status ?? null;
},
{ timeout: 45_000 },
)
.toBe("succeeded");
await expect
.poll(() =>
provider.captures.filter(
(capture) =>
capture.method === "tools/call" &&
capture.toolName === "notion:list_pages",
).length,
)
.toBe(callsBeforeContinuation + 1);
const completedIssue = await json<{ status: string }>(
await request.get(`/api/issues/${issue.id}`),
);
expect(completedIssue.status).toBe("done");
const finalRuns = await json<Array<{ id: string; status: string }>>(
await request.get(`/api/companies/${seed.companyId}/heartbeat-runs?agentId=${scout.id}&limit=10`),
);
expect(finalRuns).toHaveLength(2);
expect(finalRuns.every((run) => run.status === "succeeded")).toBe(true);
const interactions = await json<Array<{ kind: string; status: string }>>(
await request.get(`/api/issues/${issue.id}/interactions`),
);
const connectionIntents = interactions.filter(
(interaction) => interaction.kind === "connection_intent",
);
expect(
connectionIntents.filter(
(interaction) => interaction.status === "accepted",
),
).toHaveLength(1);
expect(
connectionIntents.filter(
(interaction) => interaction.status === "pending",
),
).toHaveLength(0);
expect(
connectionIntents.every((interaction) =>
["accepted", "expired"].includes(interaction.status),
),
).toBe(true);
expect(holder.id).not.toBe(scout.id);
} finally {
await provider.close();
}
});