mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-27 11:20:42 +01: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
450 lines
17 KiB
TypeScript
450 lines
17 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
|
|
import { RUNTIME_EXPOSURE_APP_PORT_MIN, deriveViteHmrPort } from "@paperclipai/shared";
|
|
|
|
import {
|
|
BrokerClientError,
|
|
type BrokerClient,
|
|
type BrokerExposeResult,
|
|
type BrokerListenerRequest,
|
|
type BrokerOwnedListener,
|
|
type BrokerReserveResult,
|
|
type BrokerRemoveResult,
|
|
} from "./broker-client.js";
|
|
import {
|
|
deprovisionExposure,
|
|
provisionExposure,
|
|
reconcileExposures,
|
|
reserveExposure,
|
|
type ExposureManagerDeps,
|
|
} from "./exposure-manager.js";
|
|
|
|
const RUNTIME_ID = "11111111-2222-4333-8444-555566667777";
|
|
const APP_PORT = RUNTIME_EXPOSURE_APP_PORT_MIN;
|
|
const HMR_PORT = deriveViteHmrPort(APP_PORT);
|
|
const HOSTNAME = "runner-abc.tail-scale.ts.net";
|
|
|
|
const CONFIG = {
|
|
type: "tailscale_https" as const,
|
|
hostname: "auto" as const,
|
|
publicPort: "same" as const,
|
|
includePaperclipViteHmr: true,
|
|
failurePolicy: "fail_closed" as const,
|
|
};
|
|
|
|
interface FakeBrokerScript {
|
|
reserve?: (runtimeId: string, listeners: BrokerListenerRequest[]) => BrokerReserveResult;
|
|
expose?: (runtimeId: string, handle: string) => BrokerExposeResult;
|
|
remove?: (runtimeId: string, handle: string) => BrokerRemoveResult;
|
|
list?: () => BrokerOwnedListener[];
|
|
}
|
|
|
|
interface FakeBrokerCalls {
|
|
reserve: Array<{ runtimeId: string; listeners: BrokerListenerRequest[] }>;
|
|
expose: Array<{ runtimeId: string; handle: string }>;
|
|
remove: Array<{ runtimeId: string; handle: string }>;
|
|
list: number;
|
|
}
|
|
|
|
function fakeBroker(script: FakeBrokerScript): { broker: BrokerClient; calls: FakeBrokerCalls } {
|
|
const calls: FakeBrokerCalls = { reserve: [], expose: [], remove: [], list: 0 };
|
|
const broker: BrokerClient = {
|
|
async reserve(runtimeId, listeners) {
|
|
calls.reserve.push({ runtimeId, listeners });
|
|
if (!script.reserve) throw new BrokerClientError("internal_error", "no reserve script");
|
|
return script.reserve(runtimeId, listeners);
|
|
},
|
|
async expose(runtimeId, handle) {
|
|
calls.expose.push({ runtimeId, handle });
|
|
if (!script.expose) throw new BrokerClientError("internal_error", "no expose script");
|
|
return script.expose(runtimeId, handle);
|
|
},
|
|
async remove(runtimeId, handle) {
|
|
calls.remove.push({ runtimeId, handle });
|
|
if (!script.remove) throw new BrokerClientError("internal_error", "no remove script");
|
|
return script.remove(runtimeId, handle);
|
|
},
|
|
async list() {
|
|
calls.list += 1;
|
|
return script.list ? script.list() : [];
|
|
},
|
|
};
|
|
return { broker, calls };
|
|
}
|
|
|
|
const HANDLE = "handle-abcdef1234567890";
|
|
|
|
describe("reserveExposure", () => {
|
|
it("reserves the exact app + HMR pair before startup", async () => {
|
|
const { broker, calls } = fakeBroker({
|
|
reserve: () => ({ handle: HANDLE, reservedPorts: [APP_PORT, HMR_PORT] }),
|
|
});
|
|
const result = await reserveExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
config: CONFIG,
|
|
appPort: APP_PORT,
|
|
});
|
|
expect(calls.reserve).toEqual([{
|
|
runtimeId: RUNTIME_ID,
|
|
listeners: [
|
|
{ purpose: "app", port: APP_PORT },
|
|
{ purpose: "vite_hmr", port: HMR_PORT },
|
|
],
|
|
}]);
|
|
expect(result.handle).toBe(HANDLE);
|
|
expect(result.status.state).toBe("pending");
|
|
});
|
|
|
|
it("releases a malformed reservation response and fails closed", async () => {
|
|
const { broker, calls } = fakeBroker({
|
|
reserve: () => ({ handle: HANDLE, reservedPorts: [APP_PORT] }),
|
|
remove: () => ({ removedPorts: [] }),
|
|
});
|
|
const result = await reserveExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
config: CONFIG,
|
|
appPort: APP_PORT,
|
|
});
|
|
expect(result.status.state).toBe("failed");
|
|
expect(result.handle).toBeNull();
|
|
expect(calls.remove).toEqual([{ runtimeId: RUNTIME_ID, handle: HANDLE }]);
|
|
});
|
|
});
|
|
|
|
function deps(broker: BrokerClient, probeHealth: () => Promise<boolean>): ExposureManagerDeps {
|
|
return { broker, probeHealth, now: () => "2026-08-11T00:00:00.000Z" };
|
|
}
|
|
|
|
describe("provisionExposure loopback diagnosis (PAP-17256)", () => {
|
|
it("fails before touching the broker when a listener is provably off-loopback", async () => {
|
|
const { broker, calls } = fakeBroker({
|
|
expose: () => ({ handle: HANDLE, publicPorts: [APP_PORT, HMR_PORT] }),
|
|
});
|
|
const seen: number[][] = [];
|
|
const result = await provisionExposure(
|
|
{
|
|
...deps(broker, async () => true),
|
|
diagnoseListenerBinds: async (ports) => {
|
|
seen.push(ports);
|
|
return `port ${APP_PORT} is bound to 0.0.0.0 instead of loopback only`;
|
|
},
|
|
},
|
|
{ runtimeId: RUNTIME_ID, config: CONFIG, handle: HANDLE, hostname: HOSTNAME, appPort: APP_PORT },
|
|
);
|
|
|
|
// Both the app port and its HMR companion are diagnosed, because the broker
|
|
// gates on both and either one can be the wildcard bind.
|
|
expect(seen).toEqual([[APP_PORT, HMR_PORT]]);
|
|
expect(calls.expose).toHaveLength(0);
|
|
expect(result.status.state).toBe("failed");
|
|
// The persisted code stays the broker's own vocabulary so retry/cleanup
|
|
// matching is unchanged; the reason rides alongside.
|
|
expect(result.status.lastError).toBe("listener_ownership_mismatch");
|
|
expect(result.errorDetail).toContain("0.0.0.0");
|
|
// The reservation handle survives so the caller can still tear the lease down.
|
|
expect(result.handle).toBe(HANDLE);
|
|
});
|
|
|
|
it("exposes normally when the diagnosis finds nothing wrong", async () => {
|
|
const { broker, calls } = fakeBroker({
|
|
expose: () => ({ handle: HANDLE, publicPorts: [APP_PORT, HMR_PORT] }),
|
|
});
|
|
const result = await provisionExposure(
|
|
{ ...deps(broker, async () => true), diagnoseListenerBinds: async () => null },
|
|
{ runtimeId: RUNTIME_ID, config: CONFIG, handle: HANDLE, hostname: HOSTNAME, appPort: APP_PORT },
|
|
);
|
|
expect(calls.expose).toHaveLength(1);
|
|
expect(result.status.state).toBe("ready");
|
|
expect(result.errorDetail ?? null).toBeNull();
|
|
});
|
|
|
|
it("surfaces the broker's own reason alongside its code", async () => {
|
|
const { broker } = fakeBroker({
|
|
expose: () => {
|
|
throw new BrokerClientError(
|
|
"listener_ownership_mismatch",
|
|
`listener on ${APP_PORT} is not loopback-only`,
|
|
);
|
|
},
|
|
});
|
|
const result = await provisionExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
config: CONFIG,
|
|
handle: HANDLE,
|
|
hostname: HOSTNAME,
|
|
appPort: APP_PORT,
|
|
});
|
|
expect(result.status.lastError).toBe("listener_ownership_mismatch");
|
|
expect(result.errorDetail).toBe(`listener on ${APP_PORT} is not loopback-only`);
|
|
});
|
|
|
|
it("does not repeat the code as a reason when the broker adds nothing", async () => {
|
|
const { broker } = fakeBroker({
|
|
expose: () => {
|
|
throw new BrokerClientError("cli_timeout", "cli_timeout");
|
|
},
|
|
});
|
|
const result = await provisionExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
config: CONFIG,
|
|
handle: HANDLE,
|
|
hostname: HOSTNAME,
|
|
appPort: APP_PORT,
|
|
});
|
|
expect(result.status.lastError).toBe("cli_timeout");
|
|
expect(result.errorDetail).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe("provisionExposure", () => {
|
|
it("exposes app + HMR and reports ready once the HTTPS probe validates", async () => {
|
|
const { broker, calls } = fakeBroker({
|
|
expose: () => ({ handle: "handle-abcdef1234567890", publicPorts: [APP_PORT, HMR_PORT] }),
|
|
});
|
|
const { status, handle } = await provisionExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
config: CONFIG,
|
|
handle: HANDLE,
|
|
hostname: HOSTNAME,
|
|
appPort: APP_PORT,
|
|
});
|
|
|
|
expect(calls.expose).toHaveLength(1);
|
|
expect(calls.expose).toEqual([{ runtimeId: RUNTIME_ID, handle: HANDLE }]);
|
|
expect(status.state).toBe("ready");
|
|
expect(status.publicUrl).toBe(`https://${HOSTNAME}:${APP_PORT}`);
|
|
expect(status.hostname).toBe(HOSTNAME);
|
|
expect(status.listeners).toHaveLength(2);
|
|
expect(status.brokerRef).toBe(RUNTIME_ID);
|
|
expect(status.lastError).toBeNull();
|
|
expect(handle).toBe("handle-abcdef1234567890");
|
|
});
|
|
|
|
it("omits the HMR listener when HMR is not requested", async () => {
|
|
const { broker, calls } = fakeBroker({
|
|
expose: () => ({ handle: "handle-abcdef1234567890", publicPorts: [APP_PORT] }),
|
|
});
|
|
const { status } = await provisionExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
config: { ...CONFIG, includePaperclipViteHmr: false },
|
|
handle: HANDLE,
|
|
hostname: HOSTNAME,
|
|
appPort: APP_PORT,
|
|
});
|
|
expect(calls.expose).toEqual([{ runtimeId: RUNTIME_ID, handle: HANDLE }]);
|
|
expect(status.listeners).toEqual([{ purpose: "app", publicPort: APP_PORT, targetPort: APP_PORT }]);
|
|
expect(status.state).toBe("ready");
|
|
});
|
|
|
|
it("fails closed without calling the broker when the app port is out of range", async () => {
|
|
const { broker, calls } = fakeBroker({});
|
|
const { status, handle } = await provisionExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
config: CONFIG,
|
|
handle: HANDLE,
|
|
hostname: HOSTNAME,
|
|
appPort: 3100, // primary app port — never eligible
|
|
});
|
|
expect(calls.expose).toHaveLength(0);
|
|
expect(status.state).toBe("failed");
|
|
expect(handle).toBe(HANDLE);
|
|
});
|
|
|
|
it("fails when the broker rejects the expose request", async () => {
|
|
const { broker } = fakeBroker({
|
|
expose: () => {
|
|
throw new BrokerClientError("port_not_allowlisted", "denied");
|
|
},
|
|
});
|
|
const { status, handle } = await provisionExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
config: CONFIG,
|
|
handle: HANDLE,
|
|
hostname: HOSTNAME,
|
|
appPort: APP_PORT,
|
|
});
|
|
expect(status.state).toBe("failed");
|
|
expect(status.lastError).toBe("port_not_allowlisted");
|
|
expect(status.listeners).toHaveLength(2);
|
|
expect(handle).toBe(HANDLE);
|
|
});
|
|
|
|
it("tears the mapping back down and fails when returned ports do not match", async () => {
|
|
const { broker, calls } = fakeBroker({
|
|
expose: () => ({ handle: "handle-abcdef1234567890", publicPorts: [APP_PORT] }), // missing HMR
|
|
remove: () => ({ removedPorts: [APP_PORT] }),
|
|
});
|
|
const { status, handle } = await provisionExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
config: CONFIG,
|
|
handle: HANDLE,
|
|
hostname: HOSTNAME,
|
|
appPort: APP_PORT,
|
|
});
|
|
expect(status.state).toBe("failed");
|
|
expect(status.lastError).toMatch(/unexpected public ports/);
|
|
expect(calls.remove).toHaveLength(1); // best-effort rollback
|
|
expect(handle).toBe(HANDLE);
|
|
});
|
|
|
|
it("fail-closed: keeps the handle but reports failed when the HTTPS probe does not validate", async () => {
|
|
const { broker } = fakeBroker({
|
|
expose: () => ({ handle: "handle-abcdef1234567890", publicPorts: [APP_PORT, HMR_PORT] }),
|
|
});
|
|
const { status, handle } = await provisionExposure(deps(broker, async () => false), {
|
|
runtimeId: RUNTIME_ID,
|
|
config: CONFIG,
|
|
handle: HANDLE,
|
|
hostname: HOSTNAME,
|
|
appPort: APP_PORT,
|
|
});
|
|
expect(status.state).toBe("failed");
|
|
expect(status.publicUrl).toBeNull();
|
|
expect(status.listeners).toHaveLength(2); // attempted mapping still surfaced
|
|
expect(status.lastError).toMatch(/health probe/);
|
|
// Handle retained so the caller can retry or clean up the dangling mapping.
|
|
expect(handle).toBe("handle-abcdef1234567890");
|
|
});
|
|
|
|
it("fail-closed: treats a probe that throws as unhealthy", async () => {
|
|
const { broker } = fakeBroker({
|
|
expose: () => ({ handle: "handle-abcdef1234567890", publicPorts: [APP_PORT, HMR_PORT] }),
|
|
});
|
|
const { status } = await provisionExposure(
|
|
deps(broker, async () => {
|
|
throw new Error("cert error");
|
|
}),
|
|
{ runtimeId: RUNTIME_ID, config: CONFIG, handle: HANDLE, hostname: HOSTNAME, appPort: APP_PORT },
|
|
);
|
|
expect(status.state).toBe("failed");
|
|
});
|
|
});
|
|
|
|
describe("deprovisionExposure", () => {
|
|
it("is a no-op removal when no handle was ever recorded", async () => {
|
|
const { broker, calls } = fakeBroker({});
|
|
const { status, quarantinedPorts } = await deprovisionExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
handle: null,
|
|
ports: [APP_PORT, HMR_PORT],
|
|
});
|
|
expect(calls.remove).toHaveLength(0);
|
|
expect(status.state).toBe("removed");
|
|
expect(quarantinedPorts).toEqual([]);
|
|
});
|
|
|
|
it("removes cleanly with a handle", async () => {
|
|
const { broker, calls } = fakeBroker({ remove: () => ({ removedPorts: [APP_PORT, HMR_PORT] }) });
|
|
const { status, quarantinedPorts } = await deprovisionExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
handle: "handle-abcdef1234567890",
|
|
ports: [APP_PORT, HMR_PORT],
|
|
});
|
|
expect(calls.remove).toHaveLength(1);
|
|
expect(status.state).toBe("removed");
|
|
expect(quarantinedPorts).toEqual([]);
|
|
});
|
|
|
|
it("treats an already-gone mapping as removed (idempotent)", async () => {
|
|
const { broker } = fakeBroker({
|
|
remove: () => {
|
|
throw new BrokerClientError("invalid_handle", "gone");
|
|
},
|
|
});
|
|
const { status, quarantinedPorts } = await deprovisionExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
handle: "handle-abcdef1234567890",
|
|
ports: [APP_PORT, HMR_PORT],
|
|
});
|
|
expect(status.state).toBe("removed");
|
|
expect(quarantinedPorts).toEqual([]);
|
|
});
|
|
|
|
it("quarantines ports and reports cleanup_pending on an ambiguous cleanup failure", async () => {
|
|
const { broker } = fakeBroker({
|
|
remove: () => {
|
|
throw new BrokerClientError("cli_error", "tailscale serve failed");
|
|
},
|
|
});
|
|
const { status, quarantinedPorts } = await deprovisionExposure(deps(broker, async () => true), {
|
|
runtimeId: RUNTIME_ID,
|
|
handle: "handle-abcdef1234567890",
|
|
ports: [APP_PORT, HMR_PORT, APP_PORT],
|
|
});
|
|
expect(status.state).toBe("cleanup_pending");
|
|
expect(status.lastError).toBe("cli_error");
|
|
expect(quarantinedPorts).toEqual([APP_PORT, HMR_PORT]); // deduped
|
|
});
|
|
});
|
|
|
|
describe("reconcileExposures", () => {
|
|
it("adopts owned mappings that are still desired", async () => {
|
|
const { broker, calls } = fakeBroker({
|
|
list: () => [
|
|
{ runtimeId: RUNTIME_ID, port: APP_PORT, purpose: "app" },
|
|
{ runtimeId: RUNTIME_ID, port: HMR_PORT, purpose: "vite_hmr" },
|
|
],
|
|
});
|
|
const result = await reconcileExposures(deps(broker, async () => true), {
|
|
desiredRuntimeIds: new Set([RUNTIME_ID]),
|
|
handlesByRuntimeId: new Map(),
|
|
});
|
|
expect(result.adopted).toEqual([RUNTIME_ID]);
|
|
expect(result.removedOrphanPorts).toEqual([]);
|
|
expect(calls.remove).toHaveLength(0);
|
|
});
|
|
|
|
it("removes an orphaned owned mapping when a handle is available", async () => {
|
|
const orphan = "99999999-2222-4333-8444-555566667777";
|
|
const { broker, calls } = fakeBroker({
|
|
list: () => [{ runtimeId: orphan, port: APP_PORT, purpose: "app" }],
|
|
remove: () => ({ removedPorts: [APP_PORT] }),
|
|
});
|
|
const result = await reconcileExposures(deps(broker, async () => true), {
|
|
desiredRuntimeIds: new Set([RUNTIME_ID]),
|
|
handlesByRuntimeId: new Map([[orphan, "handle-abcdef1234567890"]]),
|
|
});
|
|
expect(result.removedOrphanPorts).toEqual([APP_PORT]);
|
|
expect(calls.remove).toEqual([{ runtimeId: orphan, handle: "handle-abcdef1234567890" }]);
|
|
expect(result.unremovableOrphans).toEqual([]);
|
|
});
|
|
|
|
it("never mutates an orphan it has no handle for (no remove call)", async () => {
|
|
const orphan = "99999999-2222-4333-8444-555566667777";
|
|
const { broker, calls } = fakeBroker({
|
|
list: () => [{ runtimeId: orphan, port: APP_PORT, purpose: "app" }],
|
|
});
|
|
const result = await reconcileExposures(deps(broker, async () => true), {
|
|
desiredRuntimeIds: new Set([RUNTIME_ID]),
|
|
handlesByRuntimeId: new Map(),
|
|
});
|
|
expect(calls.remove).toHaveLength(0);
|
|
expect(result.unremovableOrphans).toEqual([orphan]);
|
|
expect(result.removedOrphanPorts).toEqual([]);
|
|
});
|
|
|
|
it("records non-fatal errors without aborting reconciliation", async () => {
|
|
const orphanA = "aaaaaaaa-2222-4333-8444-555566667777";
|
|
const orphanB = "bbbbbbbb-2222-4333-8444-555566667777";
|
|
const { broker } = fakeBroker({
|
|
list: () => [
|
|
{ runtimeId: orphanA, port: APP_PORT, purpose: "app" },
|
|
{ runtimeId: orphanB, port: APP_PORT + 1, purpose: "app" },
|
|
],
|
|
remove: (runtimeId) => {
|
|
if (runtimeId === orphanA) throw new BrokerClientError("cli_error", "boom");
|
|
return { removedPorts: [APP_PORT + 1] };
|
|
},
|
|
});
|
|
const result = await reconcileExposures(deps(broker, async () => true), {
|
|
desiredRuntimeIds: new Set(),
|
|
handlesByRuntimeId: new Map([
|
|
[orphanA, "handle-aaaaaaaaaaaaaaaa"],
|
|
[orphanB, "handle-bbbbbbbbbbbbbbbb"],
|
|
]),
|
|
});
|
|
expect(result.errors).toEqual([{ runtimeId: orphanA, code: "cli_error" }]);
|
|
expect(result.removedOrphanPorts).toEqual([APP_PORT + 1]);
|
|
});
|
|
});
|