Files
PaperClipAI/tests/runner-e2e/chat-stories.ts
T
DottaandPaperclip 27d35314be feat: connect experimental Cursor Cloud to native Runner (#18069)
## Thinking Path

> - Paperclip helps people manage AI agents at work.
> - Native Runner owns execution and task authority.
> - Operators need an explicit native Cursor Cloud choice.
> - Tools/files need company, task, session and run scope.
> - This connects setup and lifecycle to Runner Core.
> - Legacy agents retain their selected runtime/history.

## Linked Issues or Issue Description

Depends on #18068. Managed-only API placement and API-owned Stop
containment are in #18310. Refs #5664, #11803, #17299, and #17471. No
duplicate native integration was found.

## What Changed

- Add explicit native setup, Test, saved settings and dispatch with
no-prompt account/catalog/callback checks.
- Scope MCP to company, agent, task, session and run through
authenticated HTTPS. Register verified artifacts/work products; preserve
unpriced accounting, completion and budgets.
- Connect Question/Plan continuation, cold handoff and admitted fresh
sessions; recheck waiting admission under the task lock.
- Present audited Stop intent while preserving physical containment
proof; bound typed Stop metadata. Preserve title edits through
preference/navigation readiness.
- Select one live/history representation per run to prevent duplicate
settled cards. Integrate upstream task/read-state/retry/schema contracts
and repair two test fixtures.

## Verification

Core #18068 merged normally as `3910352c923a`. Product head
`5a60f541c982` has passing repository CI/build/browser checks, including
required `ci / verify` and `ci / e2e`, plus a fresh exact-head Greptile
5/5 review with zero unresolved threads. Two non-required external app
checks remain pending: Paperclip Review is queued waiting for its
assigned agent; Superagent Security Scan is reviewing the diff. These
are not claimed completed. The normal merge endpoint enforces the
repository rules; no policy or status override is used. The dependent
Top PR is addressing its fresh deferred-Stop review finding.

Product `5a60f541c982` passed 270 UI and 20 selected
Cloud/native/disk-full tests, UI/server typechecks, tokens and maps.
Top’s clean normal merge passed tokens/maps/diff checks; its matrix is
pending. Earlier receipts retain Core’s 47 Rust, 4 compiled-native
retirement and 19 settlement controls, normal Runner build, and runtime
9af build/recursive typecheck. Reproduced loading/shutdown CI fixture
failures passed 7/7 browser and 121/121 unit tests, including a
broken-unsubscribe negative control. No timeout/oracle was relaxed.

The actual-parent restack adopts 75 mainline paths, including
schema/permission and generic runtime changes, beyond the prior two
fixture repairs and client projection fix. The full difference from
hosted `9af1a5de42a2` is therefore larger than four files; backend
source also differs. The merged config-read checks match Core391, and
the Cursor placement/runtime/relay/selection modules match frozen9af;
selected affected regressions pass. Paid proof keeps its actual 9af
source/image identity. The separately tested live/history card fix is
not claimed deployed on that host.

On 9af, original saved settings survived reopening and fresh no-prompt
Test authenticated catalog/model/binding; no new Save is claimed. Fresh
Linux admission passed. With `claude-sonnet-4-5`, Artifact downloaded
exact 27 bytes and matched 121 canonical identities in complete
S3-served history. First Stop’s strict quiet FAILED on a 10.373-second
gap despite independent cancellation/no late artifact. One targeted
unchanged-sampler retry retained all 24 samples: 35.076 seconds quiet /
maximum gap 4.584 seconds, 67 ordered canonical identities, and separate
CANCELLED/artifact-absent status after the original 180-second deadline.
The pre-reload duplicate settled card is disclosed. Exact-ID cleanup for
the three new provider agents is awaiting authorization, so full grades
and the fresh Artifact’s post-cleanup download remain blocked. A
historical deleted-provider artifact was newly downloaded on 9af;
original F226 Question/Plan/reconnect and cleanup proof keep their
identities.

Retained failures: stale fixture 132/133; E8 48/135 with 87 reset-hook
failures; Mac 17 SQL failures/skips; earlier
title/startup/custody/Stop/deletion failures with unknown causes/bounded
recoveries; `dea023` Stop’s warning/50 duplicate identities; pre-repair
ACK and original Core CI failures. WSP’s 251-assertion, 7/8-suite
attempt failed physical PostgreSQL teardown; the unchanged wrapper rerun
passed 128. Retry alone establishes no cause or full local-suite pass.
All paid attempts remain recorded; vendor dollar cost is UNKNOWN.

## Risks

Experimental: Cursor independently acknowledges neither the effective
model nor instruction digest before the first prompt. Explicit values
are submitted and checked through behavior; unpriced provider dollar
cost stays UNKNOWN.

Callbacks need authenticated reachable HTTPS. Scope, revocation,
budgets, completion and cleanup remain authoritative. Operator Stop
intent is separate from physical containment. Saved legacy agents retain
their selected runtime. Prior shared title-save/deletion failures remain
disclosed.

## Model Used

OpenAI Codex, GPT-6 family, assisted with reasoning, repository tools,
code execution, browser verification, and delegated code review. The
serving model’s exact API ID and context window are not exposed. No
value is inferred from the model catalog.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used and the limits of available model
metadata
- [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 linked public issues or described the issue in this PR
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] My branch describes the change and contains no internal ticket ID
- [x] I have run the scoped local tests reported above; pending gates
are stated separately
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation
- [x] I have considered and documented the risks
- [x] All required CI gates pass on the current head
- [x] Fresh Greptile is 5/5 with no unresolved findings on the current
head
- [x] I will address all reviewer comments before requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-03 09:01:39 -06:00

172 lines
11 KiB
TypeScript

import { expect } from "@playwright/test";
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { sendChatMessage, type ChatFlowInput, type ChatIssue, type ChatRun } from "./chat-flow.js";
import { setSettingsToggle } from "./settings-toggle.js";
import { resolveDefaultAgentWorkspaceDir } from "../../server/src/home-paths.js";
type Comment = { id: string; body: string; authorAgentId?: string; createdByRunId?: string };
type Context = {
input: ChatFlowInput; marker: string; issue(): ChatIssue;
idle(count: number): Promise<void>; allRuns(): Promise<ChatRun[]>; comments(): Promise<Comment[]>;
};
/** Seed only the disabled setting; the browser performs the user's opt-in. */
export async function enableChatThroughSettings(input: ChatFlowInput) {
await input.api.patch("/api/instance/settings/experimental", { enableAgentChat: false, enableClassicTaskInterface: false });
await setChatEnabled(input, true);
}
async function setChatEnabled(input: ChatFlowInput, enabled: boolean) {
await input.page.goto(`/${input.fixtures.company.issuePrefix}/company/settings/instance/experimental`, { waitUntil: "domcontentloaded" });
const toggle = input.page.getByRole("switch", { name: "Toggle agent chat experimental setting" });
await setSettingsToggle(toggle, enabled);
await expect.poll(async () => (await input.api.get<{ enableAgentChat: boolean }>("/api/instance/settings/experimental")).enableAgentChat).toBe(enabled);
}
export function assertInterruptedChat(input: {
first: string; followup: string; reference: string; marker: string; issueId: string;
boundaryRun: ChatRun; activeAtFollowup: ChatRun; comments: Comment[]; runs: ChatRun[];
revisedPlan?: string;
}) {
expect(input.boundaryRun.status).toBe("running");
expect(input.activeAtFollowup).toMatchObject({ id: input.boundaryRun.id, status: "running" });
for (const message of [input.first, input.followup]) {
expect(input.comments.filter(comment => !comment.authorAgentId && comment.body === message)).toHaveLength(1);
}
const replies = input.comments.filter(comment => comment.authorAgentId);
const final = replies.at(-1)!;
expect(final).toBeTruthy();
expect(final.body).toContain(input.reference);
expect(final.body).toContain(input.marker);
expect(replies.filter(reply => reply.body.includes(input.marker))).toHaveLength(1);
expect(input.runs.length).toBeGreaterThanOrEqual(1);
expect(input.runs.length).toBeLessThanOrEqual(2);
expect(input.runs.every(run => run.status === "succeeded" && run.runtimeMode === "native")).toBe(true);
expect(new Set(input.runs.map(run => run.id)).size).toBe(input.runs.length);
expect(input.runs.every(run => run.agentId === input.boundaryRun.agentId && run.contextSnapshot?.issueId === input.issueId)).toBe(true);
expect(final.authorAgentId).toBe(input.boundaryRun.agentId);
const responseRun = input.runs.length === 1
? input.boundaryRun
: input.runs.find(run => run.id !== input.boundaryRun.id)!;
expect(final.createdByRunId).toBe(responseRun.id);
expect(input.runs.some(run => run.id === input.boundaryRun.id)).toBe(true);
if (input.revisedPlan !== undefined) {
const body = input.revisedPlan.trim().replace(/^```(?:json)?\s*/, "").replace(/\s*```$/, "");
expect(JSON.parse(body)).toEqual({ launchDay: "Friday", reference: input.reference, revision: input.marker });
}
}
export async function publishChatBrief(gate: string, content: string) {
const staging = `${gate}.${randomUUID()}.tmp`;
try {
await writeFile(staging, content, { encoding: "utf8", flag: "wx" });
await rename(staging, gate);
} finally {
await rm(staging, { force: true });
}
}
export async function prepareChatBrief(workspacePath: string, nonce: string, timeoutMs = 120_000) {
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 300_000) throw new Error("Brief wait must be bounded between 1 and 300000ms");
await mkdir(workspacePath, { recursive: true });
const gate = path.join(workspacePath, `chat-brief-${nonce}.txt`);
const ready = `${gate}.waiting`;
const scriptPath = path.join(workspacePath, `wait-for-brief-${nonce}.cjs`);
const script = `const fs=require("node:fs");fs.writeFileSync(${JSON.stringify(ready)},"waiting");const end=Date.now()+${timeoutMs};const timer=setInterval(()=>{if(fs.existsSync(${JSON.stringify(gate)})){console.log(fs.readFileSync(${JSON.stringify(gate)},"utf8"));clearInterval(timer)}else if(Date.now()>end){clearInterval(timer);process.exitCode=1}},100);`;
await writeFile(scriptPath, script, "utf8");
return { gate, ready, scriptPath };
}
export async function runChatInterruption(context: Context & { refreshIssue(): Promise<void> }) {
const { input, marker, idle, allRuns, comments } = context;
// Unprojected host /tmp files are intentionally hidden from native Codex.
// These projectless chats use the normal agent-home workspace, not the
// harness's separate project fixture directory. Keep the asset inside it.
const agentWorkspace = resolveDefaultAgentWorkspaceDir(input.fixtures.agent.id);
const relative = path.relative(path.dirname(input.workspacePath), agentWorkspace);
if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("Chat fixture workspace escaped the isolated instance");
const { gate, ready, scriptPath } = await prepareChatBrief(agentWorkspace, input.nonce);
const reference = `BRIEF${randomUUID().replaceAll("-", "")}`;
// Real provider tool execution waits on an ordinary fixture file. No runner
// hooks, provider results, database records, or task outcomes are fabricated.
// Keep JavaScript in a seeded fixture file: rich-text input serializes raw
// operators as Markdown escapes, which should not alter a timing fixture.
const command = `node ${scriptPath}`;
const first = `Our launch is planned for Monday. First run this bounded command to wait for the brief reference file I am supplying: ${command}\nAfter it returns, acknowledge the reference from the file here. This is discussion only; do not create projects or tasks.`;
const revise = input.execution.task.id === "revise-while-running";
const followup = revise
? `Change the launch day to Friday. Save the plan on this conversation as JSON with exactly launchDay, reference (from the brief file), and revision ("${marker}"). Then reply here with the brief reference and ${marker}. Do not create projects or execution tasks.`
: `After reading the brief, reply here with its reference and ${marker}. Keep this in the current conversation; do not create projects or tasks.`;
let boundaryRun: ChatRun | undefined;
let activeAtFollowup: ChatRun | undefined;
try {
await sendChatMessage(input.page, first);
await expect.poll(async () => {
if (await readFile(ready, "utf8").catch(() => "") !== "waiting") return false;
boundaryRun = (await allRuns()).find(run => run.status === "running");
return Boolean(boundaryRun);
}, { timeout: 120_000 }).toBe(true);
expect(boundaryRun!.contextSnapshot?.paperclipWorkspace).toMatchObject({ cwd: agentWorkspace });
await context.refreshIssue();
await sendChatMessage(input.page, followup);
await expect.poll(async () => (await comments()).filter(comment => !comment.authorAgentId && comment.body === followup).length,
{ timeout: 30_000 }).toBe(1);
activeAtFollowup = await input.api.get<ChatRun>(`/api/heartbeat-runs/${boundaryRun!.id}`);
await input.evidence("chat-interruption-boundary.json", { first, followup, boundaryRun, activeAtFollowup, comments: await comments() });
expect(activeAtFollowup.status, "Follow-up must persist while the first provider run is active").toBe("running");
await publishChatBrief(gate, reference);
await expect.poll(async () => (await comments()).filter(comment => comment.authorAgentId).at(-1)?.body ?? "", { timeout: 240_000 }).toContain(marker);
await idle(1); // Providers may queue a new run or steer the current run.
const plan = revise ? await input.api.get<{ body: string }>(`/api/issues/${context.issue().id}/documents/plan`) : undefined;
const evidence = { first, followup, reference, marker, issueId: context.issue().id, boundaryRun: boundaryRun!, activeAtFollowup,
comments: await comments(), runs: await allRuns(), ...(plan ? { revisedPlan: plan.body } : {}) };
await input.evidence("chat-interruption.json", evidence);
assertInterruptedChat(evidence);
expect(await input.api.get(`/api/companies/${input.fixtures.company.id}/issues`)).toEqual([]);
expect(await input.api.get(`/api/companies/${input.fixtures.company.id}/projects`)).toEqual([]);
} finally {
// Always release a provider that is still waiting, including failed UI runs.
await publishChatBrief(gate, reference);
const chatPath = `/api/companies/${input.fixtures.company.id}/chats/${input.fixtures.agent.id}`;
const current = await input.api.get<ChatIssue | null>(chatPath).catch(() => null);
await input.evidence("chat-interruption-state.json", {
issue: current,
runs: await allRuns().catch(error => ({ readError: String(error) })),
comments: current ? await input.api.get(`/api/issues/${current.id}/comments?order=asc`).catch(error => ({ readError: String(error) })) : [],
plan: current && revise ? await input.api.get(`/api/issues/${current.id}/documents/plan`).catch(error => ({ readError: String(error) })) : null,
});
}
}
export async function runChatSettingsLifecycle(context: Context) {
const { input, idle, comments, allRuns, marker } = context;
const remembered = `REMEMBER${marker}`;
const route = `/${input.fixtures.company.issuePrefix}/chats/${input.fixtures.agent.id}`;
await sendChatMessage(input.page, `Remember ${remembered} in this conversation. Acknowledge only; no tasks or projects.`);
await idle(1);
const before = { issue: context.issue(), comments: await comments(), runs: await allRuns() };
await setChatEnabled(input, false);
// Full document navigation clears the client query cache. Unlike SPA
// navigation, this verifies the disabled entry page without cached history.
await input.page.goto(route, { waitUntil: "domcontentloaded" });
await expect(input.page.getByText(/Agent Chat is disabled/)).toBeVisible();
const blocked = await input.api.request.post(`/api/issues/${before.issue.id}/comments`, { data: { body: `DISABLED${marker}` } });
expect(blocked.status()).toBe(404);
expect(await comments()).toEqual(before.comments);
expect((await allRuns()).map(run => ({ id: run.id, status: run.status })))
.toEqual(before.runs.map(run => ({ id: run.id, status: run.status })));
await setChatEnabled(input, true);
await input.page.goto(route, { waitUntil: "domcontentloaded" });
await sendChatMessage(input.page, `What reference did I ask you to remember? Reply with it and ${marker}. No new work.`);
await idle(2);
expect(context.issue().id).toBe(before.issue.id);
expect(context.issue().conversationSessionGeneration).toBe(before.issue.conversationSessionGeneration);
const reply = (await comments()).filter(comment => comment.authorAgentId).at(-1)?.body ?? "";
expect(reply).toContain(remembered);
expect(reply).toContain(marker);
expect(await input.api.get(`/api/companies/${input.fixtures.company.id}/issues`)).toEqual([]);
await input.evidence("chat-settings-lifecycle.json", { before, after: { issue: context.issue(), comments: await comments(), runs: await allRuns() } });
}