Files
PaperClipAI/server/src/http/server.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

229 lines
12 KiB
TypeScript

import { once } from "node:events";
import dns from "node:dns";
import { mkdtemp, rm } from "node:fs/promises";
import { networkInterfaces, tmpdir } from "node:os";
import { join } from "node:path";
import { request } from "node:http";
import { afterEach, describe, expect, it, vi } from "vitest";
import express from "express";
import { DurablePrpControlPlane } from "../vendor/paperclip-runner/index.js";
import { registerRunnerPrpAuthority, runnerPrpWebSocketInternals } from "../realtime/runner-prp-ws.js";
import { resolveLocalRuntimeApiUrl } from "../runtime-api.js";
import { createPaperclipHttpServer } from "./server.js";
import { privateHostnameGuard } from "../middleware/private-hostname-guard.js";
async function guardedNativeRead(bindHost: string, configuredHost = bindHost) {
const app = express();
app.use(privateHostnameGuard({ enabled: true, bindHost: configuredHost, allowedHostnames: [] }));
app.get("/api/native-read", (req, res) => {
res.status(req.header("authorization") === "Bearer synthetic-readonly-run-token" ? 200 : 401).json({ readonly: true });
});
const server = createPaperclipHttpServer(app, { apiUrl: "https://advertised.example.test" });
try {
server.listen(0, bindHost);
await once(server, "listening");
const url = `${resolveLocalRuntimeApiUrl()}/api/native-read`;
const authenticated = await fetch(url, { headers: { Authorization: "Bearer synthetic-readonly-run-token" } });
expect(authenticated.status).toBe(200);
expect(await authenticated.json()).toEqual({ readonly: true });
const unauthenticated = await fetch(url);
expect(unauthenticated.status).toBe(401);
await unauthenticated.body?.cancel();
} finally {
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
}
}
describe("Paperclip HTTP server runner transport", () => {
afterEach(() => {
runnerPrpWebSocketInternals.resetForTests();
vi.restoreAllMocks();
vi.unstubAllEnvs();
});
it("registers native runner authority without a separate startup call", async () => {
const server = createPaperclipHttpServer((_req, res) => res.end("ok"), {
apiUrl: "http://127.0.0.1:3210",
});
const handleUpgrade = vi.fn();
const runId = "00000000-0000-4000-8000-000000000777";
server.listen(0, "127.0.0.1");
await once(server, "listening");
const origin = resolveLocalRuntimeApiUrl();
const authority = await registerRunnerPrpAuthority({
companyId: "company-1", runId,
authority: { handleUpgrade } as unknown as DurablePrpControlPlane,
});
expect(authority.connectUrl).toBe(`${origin.replace("http:", "ws:")}/api/runner/v1/connect/${runId}`);
await authority.release();
await new Promise<void>(resolve => server.close(() => resolve()));
});
it("serves HTTP and rejects an unregistered runner over the real listener", async () => {
const server = createPaperclipHttpServer((_req, res) => res.end("ready"), {
apiUrl: "http://127.0.0.1:3210",
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
const address = server.address();
if (!address || typeof address === "string") throw new Error("Listener not bound");
const origin = `http://127.0.0.1:${address.port}`;
try {
expect(await (await fetch(origin)).text()).toBe("ready");
const status = await new Promise<number | undefined>((resolve, reject) => {
const req = request(`${origin}/api/runner/v1/connect/00000000-0000-4000-8000-000000000778`, {
headers: { connection: "Upgrade", upgrade: "websocket" },
}, res => { res.resume(); resolve(res.statusCode); });
req.on("error", reject);
req.setTimeout(1000, () => req.destroy(new Error("Runner upgrade was not handled")));
req.end();
});
expect(status).toBe(404);
} finally {
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
}
});
it("refuses native endpoints before listen and after close despite advertised fallback URLs", async () => {
vi.stubEnv("PAPERCLIP_API_URL", "https://advertised.example.test");
vi.stubEnv("PAPERCLIP_LISTEN_HOST", "controller.example.test");
vi.stubEnv("PAPERCLIP_LISTEN_PORT", "3210");
const server = createPaperclipHttpServer((_req, res) => res.end("ready"), {
apiUrl: "https://advertised.example.test",
});
const binding = { companyId: "company-1", runId: "00000000-0000-4000-8000-000000000779",
authority: {} as DurablePrpControlPlane };
expect(() => resolveLocalRuntimeApiUrl()).toThrow();
await expect(registerRunnerPrpAuthority(binding)).rejects.toThrow();
server.listen(0, "127.0.0.1");
await once(server, "listening");
try {
expect(resolveLocalRuntimeApiUrl()).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/);
} finally {
await new Promise<void>(resolve => server.close(() => resolve()));
}
expect(() => resolveLocalRuntimeApiUrl()).toThrow();
await expect(registerRunnerPrpAuthority(binding)).rejects.toThrow();
expect(process.env.PAPERCLIP_API_URL).toBe("https://advertised.example.test");
});
it("uses the actual numeric bind for bearer REST and PRP without a second hostname lookup", async () => {
const hostname = "controller-bind.example.test";
let lookups = 0;
vi.spyOn(dns, "lookup").mockImplementation(((host, options, callback) => {
if (host !== hostname || typeof options !== "object" || options.all !== true) {
throw new Error("Expected only the listener's all-address lookup");
}
// node:net's listen path requests all addresses; dns.lookup's overloaded
// declaration otherwise contextualizes this callback as its IPv4 form.
const lookedUp = callback as (error: NodeJS.ErrnoException | null, addresses?: dns.LookupAddress[]) => void;
lookups++;
if (lookups > 1) return lookedUp(Object.assign(new Error("Unexpected second DNS authority"), { code: "ENOTFOUND" }));
lookedUp(null, [{ address: "127.0.0.1", family: 4 }]);
}) as typeof dns.lookup);
vi.stubEnv("PAPERCLIP_API_URL", "https://advertised.example.test");
vi.stubEnv("PAPERCLIP_LISTEN_HOST", hostname);
vi.stubEnv("PAPERCLIP_LISTEN_PORT", "1");
const server = createPaperclipHttpServer((req, res) => {
res.statusCode = req.headers.authorization === "Bearer synthetic-run-token" ? 200 : 401;
res.end("local-controller");
}, { apiUrl: "https://advertised.example.test" });
const directory = await mkdtemp(join(tmpdir(), "paperclip-bound-prp-"));
const runId = "00000000-0000-4000-8000-000000000780";
const authority = new DurablePrpControlPlane({ stateDirectory: directory,
identity: { runnerInstanceId: "bound-runner", environmentLeaseId: "bound-lease", normalizedSessionId: "bound-session", runId, turnId: "bound-turn", itemId: "bound-item" },
expectedRunnerVersion: "0.3.0", expectedRunnerDigest: `sha256:${"a".repeat(64)}` });
let registration: Awaited<ReturnType<typeof registerRunnerPrpAuthority>> | undefined;
try {
server.listen(0, hostname);
await once(server, "listening");
const address = server.address();
if (!address || typeof address === "string") throw new Error("Expected a TCP bind");
const expected = `http://127.0.0.1:${address.port}`;
expect(resolveLocalRuntimeApiUrl()).toBe(expected);
expect(await (await fetch(resolveLocalRuntimeApiUrl(), { headers: { Authorization: "Bearer synthetic-run-token" } })).text()).toBe("local-controller");
registration = await registerRunnerPrpAuthority({ companyId: "company-1", runId, authority });
expect(registration.connectUrl).toBe(`${expected.replace("http:", "ws:")}/api/runner/v1/connect/${runId}`);
const upgraded = await new Promise<number | undefined>((resolve, reject) => {
const req = request(registration!.connectUrl.replace("ws:", "http:"), { headers: {
Connection: "Upgrade", Upgrade: "websocket", "Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
} });
req.once("upgrade", (res, socket) => { socket.destroy(); resolve(res.statusCode); });
req.once("response", res => { res.resume(); resolve(res.statusCode); });
req.once("error", reject);
req.setTimeout(1000, () => req.destroy(new Error("PRP upgrade unavailable")));
req.end();
});
expect(upgraded).toBe(101);
expect(lookups).toBe(1);
expect(process.env.PAPERCLIP_API_URL).toBe("https://advertised.example.test");
} finally {
await registration?.release();
await authority.stop();
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
await rm(directory, { recursive: true, force: true });
}
});
it.each([
["0.0.0.0", "127.0.0.1"], ["::", "[::1]"], ["::1", "[::1]"],
])("uses matching loopback for a real %s bind", async (host, connectHost) => {
const server = createPaperclipHttpServer((_req, res) => res.end("bound"), { apiUrl: "https://advertised.example.test" });
server.listen(0, host);
await once(server, "listening");
try {
const address = server.address();
if (!address || typeof address === "string") throw new Error("Expected TCP bind");
expect(resolveLocalRuntimeApiUrl()).toBe(`http://${connectHost}:${address.port}`);
expect(await (await fetch(resolveLocalRuntimeApiUrl())).text()).toBe("bound");
} finally {
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
}
});
it("fails closed for unavailable or nonnumeric bound addresses and competing listeners", async () => {
const first = createPaperclipHttpServer((_req, res) => res.end("first"), { apiUrl: "http://ignored.example.test" });
const second = createPaperclipHttpServer((_req, res) => res.end("second"), { apiUrl: "http://ignored.example.test" });
first.listen(0, "127.0.0.1");
await once(first, "listening");
try {
const address = vi.spyOn(first, "address");
for (const unavailable of [null, "/tmp/not-tcp.sock", { address: "changed.example.test", family: "IPv4", port: 3210 }]) {
address.mockReturnValueOnce(unavailable);
expect(() => resolveLocalRuntimeApiUrl()).toThrow();
}
second.listen(0, "127.0.0.1");
await once(second, "listening");
expect(() => resolveLocalRuntimeApiUrl()).toThrow("local_runtime_api_listener_ambiguous");
await expect(registerRunnerPrpAuthority({ companyId: "company-1", runId: "00000000-0000-4000-8000-000000000781", authority: {} as DurablePrpControlPlane }))
.rejects.toThrow("local_runtime_api_listener_ambiguous");
} finally {
await Promise.all([first, second].map(server => new Promise<void>(resolve => server.close(() => resolve()))));
}
});
it.each(["127.0.0.1", "::1", "::ffff:127.0.0.1"])("routes a guarded native read through the real %s listener", async host => {
await guardedNativeRead(host);
});
it("routes a guarded native read after a configured hostname binds a local interface", async context => {
const address = Object.values(networkInterfaces()).flatMap(entries => entries ?? [])
.find(entry => !entry.internal && entry.family === "IPv4" && !entry.address.startsWith("127."))?.address;
if (!address) { context.skip(); return; }
const hostname = "guarded-controller.example.test";
let lookups = 0;
vi.spyOn(dns, "lookup").mockImplementation(((host, options, callback) => {
if (host !== hostname || typeof options !== "object" || options.all !== true) throw new Error("Unexpected lookup in local fixture");
const lookedUp = callback as (error: NodeJS.ErrnoException | null, addresses?: dns.LookupAddress[]) => void;
if (++lookups !== 1) throw new Error("Repeated hostname lookup in local fixture");
lookedUp(null, [{ address, family: 4 }]);
}) as typeof dns.lookup);
await guardedNativeRead(hostname);
expect(lookups).toBe(1);
});
});