mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-23 09:07:46 +02:00
<!-- Simplified Technical English (ASD-STE100). --> > **Stacked pull request.** This targets #11524. Merge #11524 first. Review only the second commit, `feat(runtime): managed Tailscale HTTPS lifecycle...`. ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip starts and supervises managed runtime services, so an agent's branch can be previewed while the agent works > - The previous pull request added the host broker, the shared contract, and the database columns, but no code used them > - A managed runtime can only be exposed over HTTPS if it holds a stable loopback port pair for the whole life of the service. The current control path cannot promise this: two controls can race the same execution workspace, a stranded control can stay `running` forever, and a start can adopt a port it does not own > - This pull request adds the HTTPS lifecycle and the control-path hardening that the lifecycle depends on > - The benefit is that a managed preview becomes reachable from another device, and a managed control now always reaches a terminal state ## Linked Issues or Issue Description No public GitHub issue exists. The change follows the feature request template. **Subsystem affected** Managed workspace runtime services, workspace operations, the execution workspace routes, and the workspace runtime UI. **Problem or motivation** A managed runtime service is reachable only on loopback, so a preview cannot be opened from a phone or a second computer. Exposing it safely needs an exclusively held port pair. Three existing gaps block that. Overlapping controls can race the same workspace. A control whose owner dies stays `running` and blocks the lane forever. Port allocation does not confirm that the process holding a port is the process Paperclip spawned. **Proposed solution** Add the exposure lifecycle on top of the broker from #11524: reserve before spawn, expose after readiness, validate the public URL, and remove on stop. In the same change, make managed controls mutually exclusive per workspace, give each control a durable issue-owned lease and a terminal state, and verify port ownership before use. **Alternatives considered** - Add HTTPS exposure without the control hardening. This was rejected because a raced or stranded control makes exposure point at the wrong process. - Guard the lane with an in-memory lock only. This was rejected because the lock does not survive a server restart, so the lane can be lost or double-claimed. - Trust the requested bind address. This was rejected because a checkout that predates managed HTTPS overwrites `PAPERCLIP_BIND` from its own `--bind` argument, and then binds the wildcard address. **Roadmap alignment** This completes the managed workspace runtime capability that already exists. It adds no new product surface beyond the HTTPS link. **Additional context** This is the second of three pull requests. The third adds central mediation of leased port pairs. ## What Changed Exposure lifecycle: - Add the server-side broker client and the exposure lifecycle manager. The manager reserves the mapping before spawn, exposes after backend readiness, validates the public URL, and removes the mapping on stop. - Default managed worktree runtimes to `tailscale_https`, read exposure intent from legacy `expose` blocks, and backfill runtimes that are still HTTP-only. - Verify listener ownership for the app port and its Vite HMR companion before the broker is asked to expose anything. An unrelated listener on either port fails the start closed. - Force the loopback bind through argv instead of environment hints. Leave a non-Paperclip service's `--bind` argument alone. - Probe loopback for readiness instead of the public URL, and give Vite HMR its own loopback-bound server in middleware mode. - Preserve operator-declared Serve mappings across the managed lifecycle, so cleanup never removes a mapping that Paperclip did not create. - Name which listener predicate denied an expose, so an operator can act on the message. Control-path hardening: - Make `start`, `stop`, `restart`, and job `run` mutually exclusive per execution workspace. An overlap gets `409 workspace_runtime_control_in_progress`, and authorization is still checked first. - Take a durable exclusivity lease on the execution workspace, owned by the controlling issue. A different issue gets `409 workspace_runtime_lease_conflict` before any operation is recorded. Board and operator actions bypass the lease. - Give every control a terminal state. Each control stamps its owning process and pid, heartbeats while it runs, and has a wall-clock ceiling. Recovery of a stranded control uses a compare-and-swap on `updated_at`, so a live owner is never stolen. - Bound readiness probes, verify allocated port ownership on POSIX and Windows, harden sibling port allocation, and reconcile desired runtimes on server startup. - Surface exposure state and bounded runtime errors in the workspace runtime UI. - Record the new behavior in `doc/DEVELOPING.md`. ## Verification Focused checks, all run on this branch: - `npx tsc --noEmit -p server/tsconfig.json` — 139 errors, exactly the count on `master`. All 139 come from the unbuilt `@paperclipai/plugin-sdk` package. - `pnpm --filter @paperclipai/ui typecheck` — clean. - Server suites, 177 tests pass across 9 files: `workspace-runtime.test.ts`, `workspace-runtime-leases.test.ts`, `workspace-runtime-control-recovery.test.ts`, `execution-workspace-runtime-control-conflict.test.ts`, `execution-workspace-runtime-lease-route.test.ts`, `workspace-operations-reconciliation.test.ts`, `workspace-runtime-start-terminality.test.ts`, `app-hmr-port.test.ts`, and `workspace-runtime-ready-comment.test.ts`. - Exposure unit suites, 77 tests pass: `src/services/runtime-exposure/` and `workspace-runtime-exposure-backfill.test.ts`. - UI: `WorkspaceRuntimeControls.test.tsx` and `WorkspaceServiceControlBar.test.tsx` — 34 tests pass. **One suite is red on the development host and is expected to be green in CI.** `server/src/services/workspace-runtime-exposure.test.ts` has 10 failures on the machine used to write this branch. The cause is host contamination, not the code. That machine already runs an HTTPS canary that holds ports 42000, 42001, 52000, and 52001 on a tailnet address. The suite allocates from the same range, so the new listener-ownership check correctly reports: ``` listener_ownership_mismatch — port 42000 is bound to 100.123.243.20, 127.0.0.1, fd7a:115c:a1e0:0:0:0:dd3a:f314 ... instead of loopback only ``` A CI runner has no listener on those ports, so the check sees loopback only and the suite passes. Please confirm this from the CI result on this pull request rather than from a local run on a host that already exposes a managed runtime. This is a real weakness of the current test fixture, and the third pull request in the series removes it by allocating the pair through a central mediator instead of a stubbed availability check. `workspace-runtime-https-live-exercise.test.ts` needs a live `tailscale` host and was not run locally. ## Risks - This is the behavior-bearing pull request of the three, so it carries the most risk. - Two new `409` responses appear on managed control routes. A caller that assumed a control always starts must handle a conflict. Board and operator actions are deliberately exempt, so an agent lease cannot lock an operator out. - Managed worktree runtimes now default to `tailscale_https`. If the host has no working broker, the start fails closed and reports the exposure failure instead of silently serving plain HTTP. This is intended, and it is the reason the failure message names the denying predicate. - Startup reconciliation touches persisted runtime rows. It is scoped to desired state and does not resurrect a service that never came up. - The lease has a 30-minute time to live and explicit release paths, so a crashed owner cannot hold a lane forever. - No migration runs in this pull request. The tables and columns land in #11524. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. ## Model Used Claude Opus 5 (`claude-opus-5`), 1M context window, extended thinking, with tool use and code execution. ## 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, with the one host-contaminated suite explained above - [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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
162 lines
6.9 KiB
TypeScript
162 lines
6.9 KiB
TypeScript
import { setTimeout as delay } from "node:timers/promises";
|
|
import { afterEach, describe, expect, it } from "vitest";
|
|
import {
|
|
RUNTIME_SERVICE_READINESS_PROBE_TIMEOUT_MS,
|
|
allocateRuntimeServicePort,
|
|
claimRuntimeServiceBindPort,
|
|
resetRuntimeServicePortReservationsForTests,
|
|
waitForRuntimeServiceReadiness,
|
|
} from "../services/workspace-runtime.js";
|
|
|
|
/**
|
|
* Regression fixture for the adverse report on PAP-17207: two exclusive isolated workspaces
|
|
* asked for the same configured app/HMR pair at the same moment. One lane came up healthy,
|
|
* the loser was reallocated onto a port owned by an unrelated listener, and its managed start
|
|
* never reached a terminal state — leaving an active operation that rejected managed cleanup.
|
|
*
|
|
* The two mechanisms that produced the non-terminality are covered here:
|
|
* 1. a readiness probe against a socket that accepts but never answers, and
|
|
* 2. concurrent allocation handing the same port to two starts.
|
|
*/
|
|
describe("managed runtime start terminality", () => {
|
|
afterEach(() => {
|
|
resetRuntimeServicePortReservationsForTests();
|
|
});
|
|
|
|
const hangingService = {
|
|
readiness: { type: "http", timeoutSec: 1, intervalMs: 50 },
|
|
} as Record<string, unknown>;
|
|
|
|
it("fails a readiness check whose probes never answer instead of hanging forever", async () => {
|
|
let probes = 0;
|
|
const abortedProbes: string[] = [];
|
|
/** Accepts the request and only ever settles when the caller aborts, like a foreign listener. */
|
|
const neverAnsweringFetch = (async (_url: string | URL | Request, init?: RequestInit) => {
|
|
probes += 1;
|
|
return await new Promise<Response>((_resolve, reject) => {
|
|
init?.signal?.addEventListener("abort", () => {
|
|
abortedProbes.push(String(init?.signal?.reason ?? "aborted"));
|
|
reject(new Error("The operation was aborted due to timeout"));
|
|
});
|
|
});
|
|
}) as unknown as typeof fetch;
|
|
|
|
const startedAt = Date.now();
|
|
await expect(
|
|
waitForRuntimeServiceReadiness({
|
|
service: hangingService,
|
|
serviceName: "app",
|
|
command: "pnpm dev",
|
|
url: "http://127.0.0.1:45439/",
|
|
readinessUrl: null,
|
|
fetchImpl: neverAnsweringFetch,
|
|
}),
|
|
).rejects.toThrow(/Readiness check failed for http:\/\/127\.0\.0\.1:45439\//);
|
|
const elapsedMs = Date.now() - startedAt;
|
|
|
|
expect(probes).toBeGreaterThan(0);
|
|
expect(abortedProbes.length).toBeGreaterThan(0);
|
|
// Terminal well inside the 1s readiness budget plus one probe budget.
|
|
expect(elapsedMs).toBeLessThan(1_000 + RUNTIME_SERVICE_READINESS_PROBE_TIMEOUT_MS);
|
|
});
|
|
|
|
it("negative control: an unbounded probe loop never terminalizes the same start", async () => {
|
|
// This is the shape of the code that shipped: `fetch` with no abort signal, so the
|
|
// deadline at the top of the loop is never re-evaluated once a probe parks.
|
|
const legacyWait = async () => {
|
|
const deadline = Date.now() + 1_000;
|
|
while (Date.now() < deadline) {
|
|
await new Promise<never>(() => {});
|
|
await delay(50);
|
|
}
|
|
throw new Error("Readiness check failed");
|
|
};
|
|
|
|
const settled = await Promise.race([
|
|
legacyWait().then(() => "settled").catch(() => "settled"),
|
|
delay(1_500).then(() => "still-hanging"),
|
|
]);
|
|
expect(settled).toBe("still-hanging");
|
|
});
|
|
|
|
it("stops probing as soon as the readiness budget is spent", async () => {
|
|
let probes = 0;
|
|
const refusingFetch = (async () => {
|
|
probes += 1;
|
|
throw new Error("connect ECONNREFUSED 127.0.0.1:45439");
|
|
}) as unknown as typeof fetch;
|
|
|
|
await expect(
|
|
waitForRuntimeServiceReadiness({
|
|
service: { readiness: { type: "http", timeoutSec: 1, intervalMs: 200 } },
|
|
url: "http://127.0.0.1:45439/",
|
|
readinessUrl: null,
|
|
fetchImpl: refusingFetch,
|
|
}),
|
|
).rejects.toThrow(/ECONNREFUSED/);
|
|
// ~1s budget at a 200ms interval: a bounded handful of probes, never an unbounded spin.
|
|
expect(probes).toBeGreaterThan(1);
|
|
expect(probes).toBeLessThan(12);
|
|
});
|
|
|
|
it("hands two concurrent starts distinct ports even when the kernel repeats a candidate", async () => {
|
|
// The kernel really does hand the same ephemeral port to two `listen(0)` probes once the
|
|
// first probe socket has closed, which is exactly the reallocation collision in the report.
|
|
const candidates = [49871, 49871, 49871, 49872];
|
|
let index = 0;
|
|
const probe = async () => candidates[Math.min(index++, candidates.length - 1)]!;
|
|
const portOwnerLookup = async () => null;
|
|
|
|
const [first, second] = await Promise.all([
|
|
allocateRuntimeServicePort({ probe, portOwnerLookup }),
|
|
allocateRuntimeServicePort({ probe, portOwnerLookup }),
|
|
]);
|
|
|
|
expect(first).not.toBe(second);
|
|
expect(new Set([first, second])).toEqual(new Set([49871, 49872]));
|
|
});
|
|
|
|
it("skips a candidate port that a live process already owns", async () => {
|
|
const candidates = [49881, 49882];
|
|
let index = 0;
|
|
const probe = async () => candidates[Math.min(index++, candidates.length - 1)]!;
|
|
const portOwnerLookup = async (port: number) => (port === 49881 ? 4242 : null);
|
|
|
|
await expect(allocateRuntimeServicePort({ probe, portOwnerLookup })).resolves.toBe(49882);
|
|
// The rejected candidate must not stay reserved, or later starts would leak allocations.
|
|
await expect(
|
|
allocateRuntimeServicePort({ probe: async () => 49881, portOwnerLookup: async () => null }),
|
|
).resolves.toBe(49881);
|
|
});
|
|
|
|
it("refuses a configured port a sibling start is already claiming", () => {
|
|
// The reported collision was on a *configured* app/HMR pair, not an auto-allocated one:
|
|
// both lanes read the pair as free because neither had bound or persisted a row yet.
|
|
expect(claimRuntimeServiceBindPort(42003, null)).toBe(true);
|
|
expect(claimRuntimeServiceBindPort(42003, null)).toBe(false);
|
|
// The HMR companion is claimed independently, so a lane can lose on either port.
|
|
expect(claimRuntimeServiceBindPort(42004, null)).toBe(true);
|
|
expect(claimRuntimeServiceBindPort(42004, null)).toBe(false);
|
|
});
|
|
|
|
it("never lets a start be refused by its own allocation", async () => {
|
|
// An auto-allocated port arrives already reserved by this start, and its identity port can
|
|
// resolve to that same value. Treating that as a sibling's claim would fail the start on its
|
|
// own reservation.
|
|
const held = await allocateRuntimeServicePort({
|
|
probe: async () => 49901,
|
|
portOwnerLookup: async () => null,
|
|
});
|
|
expect(held).toBe(49901);
|
|
expect(claimRuntimeServiceBindPort(49901, held)).toBe(true);
|
|
// A different start still loses against that held reservation.
|
|
expect(claimRuntimeServiceBindPort(49901, null)).toBe(false);
|
|
});
|
|
|
|
it("fails terminally rather than looping when no free port can be found", async () => {
|
|
await expect(
|
|
allocateRuntimeServicePort({ probe: async () => 49891, portOwnerLookup: async () => 99 }),
|
|
).rejects.toThrow(/Could not allocate a free loopback port/);
|
|
});
|
|
});
|