Files
PaperClipAI/tests/runner-e2e/cursor-cloud-stop-observation.test.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

137 lines
9.8 KiB
TypeScript

import { createHash } from "node:crypto";
import { afterEach, expect, it, vi } from "vitest";
import { CursorCloudClient, type CursorCloudSseEvent } from "../../packages/paperclip-runner/src/drivers/cursor-cloud/cloud-client.js";
import { cursorCloudStopTask } from "./cursor-cloud-cases.js";
import { CursorCloudStopCommandObserver, CursorCloudStopCommandTracker, readPendingCursorCloudStopExecution } from "./cursor-cloud-stop-observation.js";
const localRunId = "local-run", agentId = "bc-11111111-1111-4111-8111-111111111111", nativeRunId = "run-22222222-2222-4222-8222-222222222222";
const filename = "cursor-cloud-after-stop-nonce.txt";
const command = "sleep 180 && printf 'MUST_NOT_APPEAR\\n' > '/artifacts/" + filename + "'";
const digest = createHash("sha256").update(command).digest("hex");
const pending = { callId: "delayed-command", toolName: "run_terminal_cmd", commandSha256: digest };
const event = (type: string, executionId: string, seq: number) => ({ runId: localRunId, seq, protocolSchemaVersion: 1, payload: { prpEvent: {
schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", runId: localRunId, eventType: `tool.execution.${type}`,
payload: { schema: "paperclip.tool.execution.v1", executionId, transport: "builtin", name: "run_terminal_cmd", status: type === "completed" ? "succeeded" : "running" },
} } });
const native = (status: string, callId = pending.callId, requestedCommand = command): CursorCloudSseEvent => ({ event: "tool_call", data: { callId, name: pending.toolName, status, args: { command: requestedCommand } } });
const observers: CursorCloudStopCommandObserver[] = [];
afterEach(async () => { await Promise.all(observers.splice(0).map(observer => observer.close())); vi.restoreAllMocks(); });
async function wireObserver(deadlineAt = Date.now() + 60_000) {
let writer: ReadableStreamDefaultController<Uint8Array> | undefined, signal: AbortSignal | undefined, sequence = 0;
const cancelled = vi.fn();
const fetcher = vi.fn<typeof fetch>(async (resource, init) => {
expect(String(resource)).toBe(`https://api.cursor.com/v1/agents/${agentId}/runs/${nativeRunId}/stream`);
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer fixture-key");
signal = init?.signal ?? undefined;
return new Response(new ReadableStream<Uint8Array>({ start(controller) {
writer = controller;
signal?.addEventListener("abort", () => { try { controller.error(new Error("owned observation aborted")); } catch {} }, { once: true });
}, cancel: cancelled }), { headers: { "content-type": "text/event-stream" } });
});
const observer = new CursorCloudStopCommandObserver({ client: new CursorCloudClient({ apiKey: "fixture-key", fetch: fetcher }), agentId, runId: nativeRunId, artifactName: filename, deadlineAt });
observers.push(observer);
await vi.waitFor(() => expect(writer).toBeDefined());
return { observer, fetcher, cancelled, signal: () => signal, send(value: CursorCloudSseEvent) {
writer!.enqueue(new TextEncoder().encode(`id: ${++sequence}\nevent: ${value.event}\ndata: ${JSON.stringify(value.data)}\n\n`));
}, lose() { writer!.error(new Error("native stream disconnected")); } };
}
it("rejects a completed setup tool while the Cloud run remains active", () => {
expect(readPendingCursorCloudStopExecution([event("started", "setup", 1), event("completed", "setup", 2)], localRunId)).toBeUndefined();
});
it("requires native evidence of the exact delayed command", () => {
expect(readPendingCursorCloudStopExecution([event("started", "setup", 1)], localRunId, pending)).toBeUndefined();
});
it("matches exact native SSE command identity to persisted facade events after completed setup", async () => {
const f = await wireObserver();
f.send(native("running", "setup", "pwd")); f.send(native("completed", "setup", "pwd")); f.send(native("running"));
await vi.waitFor(() => expect(f.observer.pending()).toEqual(pending));
const rows = [event("started", "setup", 1), event("completed", "setup", 2), event("started", pending.callId, 3)];
expect(readPendingCursorCloudStopExecution(rows, localRunId, f.observer.pending())).toBe(pending.callId);
expect(f.fetcher).toHaveBeenCalledTimes(1);
expect(JSON.stringify(f.observer.pending())).not.toContain(command);
});
it("rejects a native completion racing the final Stop recheck before its persisted completion arrives", async () => {
const f = await wireObserver(), rows = [event("started", pending.callId, 1)];
f.send(native("running")); await vi.waitFor(() => expect(f.observer.pending()).toEqual(pending));
expect(readPendingCursorCloudStopExecution(rows, localRunId, f.observer.pending())).toBe(pending.callId);
f.send(native("completed")); await vi.waitFor(() => expect(f.observer.pending()).toBeUndefined());
expect(readPendingCursorCloudStopExecution(rows, localRunId, f.observer.pending())).toBeUndefined();
f.send(native("running"));
await new Promise(resolve => setImmediate(resolve));
expect(f.observer.pending()).toBeUndefined();
});
it("rejects a persisted completion even when the native observer has not received it yet", () => {
expect(readPendingCursorCloudStopExecution([event("started", pending.callId, 1), event("completed", pending.callId, 2)], localRunId, pending)).toBeUndefined();
});
it.each(["owner", "schema", "source", "tool", "changed-repeat", "terminal"])("rejects mismatched or settled %s execution evidence", reason => {
const row = event("started", pending.callId, 1), rows = [row];
if (reason === "owner") row.runId = "foreign";
if (reason === "schema") row.protocolSchemaVersion = 2;
if (reason === "source") row.payload.prpEvent.sourceKind = "provider";
if (reason === "tool") row.payload.prpEvent.payload.name = "different-tool";
if (reason === "changed-repeat") { const changed = event("started", pending.callId, 2); changed.payload.prpEvent.payload.name = "different-tool"; rows.push(changed); }
if (reason === "terminal") row.payload.prpEvent.eventType = "turn.completed";
expect(readPendingCursorCloudStopExecution(rows, localRunId, pending)).toBeUndefined();
});
it.each([command + " &", command.replace("180", "1"), command.replace(filename, "unrelated.txt"), "echo " + command,
command.replace("/artifacts/", "../"), command.replace("/artifacts/", "/artifacts/../"), command + "; true"])("rejects commands outside the exact foreground fixture: %s", value => {
const tracker = new CursorCloudStopCommandTracker(filename, nativeRunId); tracker.consume(native("running", pending.callId, value));
expect(tracker.pending()).toBeUndefined();
});
it("fails closed when the native observation stream is lost after command admission", async () => {
const f = await wireObserver(); f.send(native("running")); await vi.waitFor(() => expect(f.observer.pending()).toEqual(pending));
f.lose(); await vi.waitFor(() => expect(() => f.observer.pending()).toThrow("stream was lost"));
});
it("clears pending commands on the exact native terminal result", async () => {
const f = await wireObserver(); f.send(native("running")); await vi.waitFor(() => expect(f.observer.pending()).toEqual(pending));
f.send({ event: "result", data: { runId: nativeRunId, status: "FINISHED" } });
await vi.waitFor(() => expect(f.observer.pending()).toBeUndefined());
});
it("fails closed on a foreign run frame and closes its owned stream", async () => {
const f = await wireObserver(); f.send({ event: "status", data: { runId: "run-33333333-3333-4333-8333-333333333333", status: "RUNNING" } });
await vi.waitFor(() => expect(() => f.observer.pending()).toThrow("stream was lost"));
await f.observer.close(); expect(f.cancelled).toHaveBeenCalledTimes(1);
});
it("aborts its attempt-owned observer at the existing fixture deadline", async () => {
const f = await wireObserver(Date.now() + 100);
await vi.waitFor(() => expect(() => f.observer.pending()).toThrow("deadline expired"));
expect(f.signal()?.aborted).toBe(true);
});
it("rejects expired observation before opening a native stream", () => {
const streamRun = vi.fn();
expect(() => new CursorCloudStopCommandObserver({ client: { streamRun }, agentId, runId: nativeRunId, artifactName: filename, deadlineAt: Date.now() - 1 })).toThrow("deadline expired");
expect(streamRun).not.toHaveBeenCalled();
});
it("admits the actual Stop prompt command after substituting only its documented output directory", () => {
const prompt = cursorCloudStopTask.buildPrompt("nonce");
const requested = prompt.split("with that directory: ")[1]!.split(". Do not add a wrapper")[0]!.replace("/ABSOLUTE_OUTPUT_DIRECTORY", "/artifacts");
expect(requested).toBe(command);
const tracker = new CursorCloudStopCommandTracker(filename, nativeRunId);
tracker.consume(native("running", pending.callId, requested));
expect(tracker.pending()).toEqual(pending);
});
it("matches the observed argument-free running frame followed by the same command's argument update", async () => {
const f = await wireObserver();
f.send({ event: "tool_call", data: { callId: pending.callId, name: pending.toolName, status: "running" } });
f.send(native("running"));
await vi.waitFor(() => expect(f.observer.pending()).toEqual(pending));
const rows = [event("started", pending.callId, 1), event("started", pending.callId, 2)];
expect(readPendingCursorCloudStopExecution(rows, localRunId, f.observer.pending())).toBe(pending.callId);
});
it("accepts a route-owned status frame without a repeated native run ID", () => {
const tracker = new CursorCloudStopCommandTracker(filename, nativeRunId);
tracker.consume({ event: "status", data: { status: "RUNNING" } });
tracker.consume(native("running"));
expect(tracker.pending()).toEqual(pending);
});
it("settles a route-owned result without a repeated native run ID", () => {
const tracker = new CursorCloudStopCommandTracker(filename, nativeRunId);
tracker.consume(native("running"));
tracker.consume({ event: "result", data: { status: "FINISHED" } });
expect(tracker.pending()).toBeUndefined();
});