mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-10 12:07:09 +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
260 lines
11 KiB
TypeScript
260 lines
11 KiB
TypeScript
/**
|
|
* Opt-in LIVE exercise of the PAP-17158 in-place HTTPS backfill.
|
|
*
|
|
* Unlike `workspace-runtime.test.ts`, which drives the backfill through an
|
|
* injected broker fake, this test uses the production exposure dependencies: the
|
|
* real Unix-socket broker client, real Tailscale MagicDNS resolution, and a real
|
|
* cert-validating HTTPS probe. It is the check that the fail-closed lifecycle
|
|
* actually terminates in a browser-trusted `https://<node>.<tailnet>.ts.net:<port>`
|
|
* URL rather than only in a mock's return value.
|
|
*
|
|
* It is skipped unless BOTH hold, because it mutates host-level Tailscale serve
|
|
* state and must never run in CI:
|
|
*
|
|
* - `PAPERCLIP_LIVE_BROKER_EXERCISE=1`
|
|
* - the broker socket exists (`PAPERCLIP_TAILSCALE_BROKER_SOCKET` or the default)
|
|
*
|
|
* Run it on a broker-provisioned host with:
|
|
*
|
|
* PAPERCLIP_LIVE_BROKER_EXERCISE=1 pnpm --filter @paperclipai/server exec \
|
|
* vitest run src/__tests__/workspace-runtime-https-live-exercise.test.ts
|
|
*
|
|
* The caller must be the broker's configured service UID/GID and its listeners
|
|
* must run as `BROKER_RUNTIME_UID`, or the broker correctly refuses to publish.
|
|
*/
|
|
import { randomUUID } from "node:crypto";
|
|
import fs from "node:fs/promises";
|
|
import net from "node:net";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import {
|
|
companies,
|
|
createDb,
|
|
projectWorkspaces,
|
|
projects,
|
|
workspaceRuntimeServices,
|
|
type Db,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
getEmbeddedPostgresTestSupport,
|
|
startEmbeddedPostgresTestDatabase,
|
|
} from "./helpers/embedded-postgres.js";
|
|
import {
|
|
reconcilePersistedRuntimeServicesOnStartup,
|
|
resetRuntimeServicesForTests,
|
|
startRuntimeServicesForWorkspaceControl,
|
|
stopRuntimeServicesForProjectWorkspace,
|
|
type RealizedExecutionWorkspace,
|
|
} from "../services/workspace-runtime.ts";
|
|
|
|
const DEFAULT_BROKER_SOCKET = "/run/paperclip-tailscale-broker/broker.sock";
|
|
const brokerSocketPath = process.env.PAPERCLIP_TAILSCALE_BROKER_SOCKET ?? DEFAULT_BROKER_SOCKET;
|
|
|
|
async function brokerSocketPresent() {
|
|
try {
|
|
return (await fs.stat(brokerSocketPath)).isSocket();
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
const optedIn = process.env.PAPERCLIP_LIVE_BROKER_EXERCISE === "1";
|
|
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
|
const live = optedIn && embeddedPostgresSupport.supported && (await brokerSocketPresent());
|
|
|
|
if (optedIn && !live) {
|
|
console.warn(
|
|
`[PAP-17158] live exercise opted in but skipped: broker socket at ${brokerSocketPath} `
|
|
+ `present=${await brokerSocketPresent()}, embeddedPostgres=${embeddedPostgresSupport.supported}`,
|
|
);
|
|
}
|
|
|
|
(live ? describe : describe.skip)("PAP-17158 live HTTPS backfill exercise", () => {
|
|
let db: Db;
|
|
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
|
|
beforeAll(async () => {
|
|
tempDb = await startEmbeddedPostgresTestDatabase("pap17158-live");
|
|
db = createDb(tempDb.connectionString);
|
|
}, 60_000);
|
|
|
|
afterAll(async () => {
|
|
await resetRuntimeServicesForTests();
|
|
await tempDb?.stop?.();
|
|
}, 60_000);
|
|
|
|
it("upgrades a pre-existing HTTP workspace in place to a browser-trusted HTTPS URL", async () => {
|
|
const workspaceRoot = await fs.mkdtemp(path.join(os.tmpdir(), "pap17158-live-"));
|
|
const paperclipHome = await fs.mkdtemp(path.join(os.tmpdir(), "pap17158-live-home-"));
|
|
const previousHome = process.env.PAPERCLIP_HOME;
|
|
const previousInstance = process.env.PAPERCLIP_INSTANCE_ID;
|
|
const previousMode = process.env.PAPERCLIP_MANAGED_RUNTIME_HTTPS;
|
|
process.env.PAPERCLIP_HOME = paperclipHome;
|
|
process.env.PAPERCLIP_INSTANCE_ID = `pap17158-live-${randomUUID()}`;
|
|
|
|
// An ephemeral legacy port rather than the real template's 45439, so this
|
|
// never contends with the live workspace runtime on the same host.
|
|
const reservePort = async () => {
|
|
for (let attempt = 0; attempt < 100; attempt += 1) {
|
|
const probe = net.createServer();
|
|
await new Promise<void>((resolve) => probe.listen(0, "127.0.0.1", resolve));
|
|
const address = probe.address();
|
|
const port = typeof address === "object" && address ? address.port : null;
|
|
await new Promise<void>((resolve, reject) => probe.close((e) => (e ? reject(e) : resolve())));
|
|
if (port && port <= 55_535 && (port < 42_000 || port > 42_999)) return port;
|
|
}
|
|
throw new Error("failed to reserve a legacy port outside the broker range");
|
|
};
|
|
|
|
const companyId = randomUUID();
|
|
const projectId = randomUUID();
|
|
const projectWorkspaceId = randomUUID();
|
|
const legacyPort = await reservePort();
|
|
// Serves 200 at /api/health on the app port and its HMR companion, loopback
|
|
// only — the shape the broker's /proc ownership proof requires.
|
|
const command =
|
|
"node -e \"const http=require('node:http');const p=Number(process.env.PORT);"
|
|
+ "for(const q of [p,p+10000])http.createServer((req,res)=>{res.writeHead(200,{'content-type':'application/json'});"
|
|
+ "res.end(JSON.stringify({status:'ok',port:q}))}).listen(q,'127.0.0.1');setInterval(()=>{},1000)\"";
|
|
const workspaceRuntime = {
|
|
services: [
|
|
{
|
|
name: "paperclip-dev",
|
|
command,
|
|
port: legacyPort,
|
|
// Pre-feature block: backend URL only, no exposure declaration.
|
|
expose: { type: "url", urlTemplate: "http://127.0.0.1:{{port}}" },
|
|
readiness: {
|
|
type: "http",
|
|
urlTemplate: "http://127.0.0.1:{{port}}/api/health",
|
|
timeoutSec: 20,
|
|
intervalMs: 100,
|
|
},
|
|
lifecycle: "shared",
|
|
reuseScope: "project_workspace",
|
|
stopPolicy: { type: "manual" },
|
|
},
|
|
],
|
|
};
|
|
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Paperclip",
|
|
issuePrefix: `L${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false,
|
|
});
|
|
await db.insert(projects).values({
|
|
id: projectId,
|
|
companyId,
|
|
name: "PAP-17158 live exercise",
|
|
status: "in_progress",
|
|
});
|
|
await db.insert(projectWorkspaces).values({
|
|
id: projectWorkspaceId,
|
|
companyId,
|
|
projectId,
|
|
name: "Primary",
|
|
sourceType: "local_path",
|
|
cwd: workspaceRoot,
|
|
isPrimary: true,
|
|
metadata: {
|
|
runtimeConfig: { workspaceRuntime, desiredState: "running", serviceStates: { "0": "running" } },
|
|
},
|
|
});
|
|
|
|
const evidence: Record<string, unknown> = {};
|
|
try {
|
|
// ---- Before: the workspace as it exists today, plain HTTP. ----
|
|
process.env.PAPERCLIP_MANAGED_RUNTIME_HTTPS = "off";
|
|
const before = await startRuntimeServicesForWorkspaceControl({
|
|
db,
|
|
actor: { id: null, name: "Paperclip", companyId },
|
|
issue: null,
|
|
workspace: {
|
|
baseCwd: workspaceRoot,
|
|
source: "project_primary",
|
|
projectId,
|
|
workspaceId: projectWorkspaceId,
|
|
repoUrl: null,
|
|
repoRef: "HEAD",
|
|
strategy: "project_primary",
|
|
cwd: workspaceRoot,
|
|
branchName: null,
|
|
worktreePath: null,
|
|
warnings: [],
|
|
created: false,
|
|
} satisfies RealizedExecutionWorkspace,
|
|
config: { workspaceRuntime, desiredState: "running", serviceStates: { "0": "running" } },
|
|
adapterEnv: {},
|
|
});
|
|
const runtimeServiceId = before[0]?.id;
|
|
expect(runtimeServiceId).toBeTruthy();
|
|
const [httpRow] = await db.select().from(workspaceRuntimeServices);
|
|
expect(httpRow.exposure).toBeNull();
|
|
evidence.beforeUrl = httpRow.url;
|
|
evidence.beforePort = httpRow.port;
|
|
expect(String(httpRow.url)).toMatch(/^http:\/\//);
|
|
await expect(fetch(`http://127.0.0.1:${legacyPort}/api/health`)).resolves.toMatchObject({ ok: true });
|
|
|
|
// ---- Deploy: production exposure deps, automatic default on. ----
|
|
await resetRuntimeServicesForTests(); // restores the real broker client
|
|
delete process.env.PAPERCLIP_MANAGED_RUNTIME_HTTPS;
|
|
|
|
const result = await reconcilePersistedRuntimeServicesOnStartup(db);
|
|
evidence.reconcile = result;
|
|
expect(result.backfilled).toBe(1);
|
|
expect(result.restartFailed).toBe(0);
|
|
|
|
// ---- After: same row, real cert-validated HTTPS URL. ----
|
|
const afterRows = await db.select().from(workspaceRuntimeServices);
|
|
expect(afterRows).toHaveLength(1);
|
|
const httpsRow = afterRows[0]!;
|
|
expect(httpsRow.id).toBe(runtimeServiceId);
|
|
evidence.afterUrl = httpsRow.url;
|
|
evidence.afterPort = httpsRow.port;
|
|
evidence.afterExposureState = httpsRow.exposure?.state;
|
|
expect(httpsRow.status).toBe("running");
|
|
expect(httpsRow.exposure?.state).toBe("ready");
|
|
expect(String(httpsRow.url)).toMatch(/^https:\/\/.+\.ts\.net:\d+$/);
|
|
expect(httpsRow.port).toBeGreaterThanOrEqual(42_000);
|
|
expect(httpsRow.port).toBeLessThanOrEqual(42_999);
|
|
|
|
// Strict TLS, no relaxed verification: this is the whole point.
|
|
const probe = await fetch(`${httpsRow.url}/api/health`, { redirect: "error" });
|
|
expect(probe.ok).toBe(true);
|
|
evidence.liveProbeStatus = probe.status;
|
|
|
|
// The old HTTP backend is gone, not merely shadowed.
|
|
await expect(fetch(`http://127.0.0.1:${legacyPort}/api/health`)).rejects.toThrow();
|
|
|
|
// ---- Repeat: idempotent, no churn. ----
|
|
await resetRuntimeServicesForTests();
|
|
const second = await reconcilePersistedRuntimeServicesOnStartup(db);
|
|
expect(second.backfilled).toBe(0);
|
|
const [repeatRow] = await db.select().from(workspaceRuntimeServices);
|
|
expect(repeatRow.port).toBe(httpsRow.port);
|
|
expect(repeatRow.url).toBe(httpsRow.url);
|
|
evidence.repeatUrl = repeatRow.url;
|
|
} finally {
|
|
// eslint-disable-next-line no-console
|
|
console.log("[PAP-17158 live exercise]", JSON.stringify(evidence, null, 2));
|
|
// Deprovisions the broker lease as well as the backend process.
|
|
await stopRuntimeServicesForProjectWorkspace({
|
|
db,
|
|
projectWorkspaceId,
|
|
workspaceCwd: workspaceRoot,
|
|
}).catch((error) => console.error("[PAP-17158] teardown failed", error));
|
|
await resetRuntimeServicesForTests();
|
|
await fs.rm(paperclipHome, { recursive: true, force: true });
|
|
await fs.rm(workspaceRoot, { recursive: true, force: true });
|
|
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME;
|
|
else process.env.PAPERCLIP_HOME = previousHome;
|
|
if (previousInstance === undefined) delete process.env.PAPERCLIP_INSTANCE_ID;
|
|
else process.env.PAPERCLIP_INSTANCE_ID = previousInstance;
|
|
if (previousMode === undefined) delete process.env.PAPERCLIP_MANAGED_RUNTIME_HTTPS;
|
|
else process.env.PAPERCLIP_MANAGED_RUNTIME_HTTPS = previousMode;
|
|
}
|
|
}, 180_000);
|
|
});
|