Files
PaperClipAI/server/src/services/runtime-exposure/exposure-manager.ts
T
Dotta 4c349fe6b7 feat(runtime): managed Tailscale HTTPS lifecycle, durable runtime leases, and bounded control recovery (#11525)
<!-- 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
2026-08-17 06:23:33 -04:00

400 lines
14 KiB
TypeScript

/**
* Runtime exposure lifecycle orchestrator for the `tailscale_https` mode.
*
* Owns the exposure state machine independently of the backend process
* lifecycle (PAP-17049 plan, PAP-17050 verdict). A backend can be running and
* healthy while its HTTPS exposure is still `pending`, `failed`, or
* `cleanup_pending`. This module never touches Tailscale directly — it drives
* the least-privilege broker through an injected {@link BrokerClient} and an
* injected external HTTPS health probe, so every branch is unit-testable
* against a fake broker with no sockets, no CLI, and no certificates.
*
* Invariants enforced here (in addition to the broker's own controls):
* - fail-closed: a configured HTTPS preview is never reported `ready` unless an
* external, normally-validating HTTPS probe succeeds.
* - same-number: only the app port and its derived HMR companion are exposed.
* - idempotent stop/cleanup: a missing/already-removed lease is success, not an
* error; genuine cleanup failures quarantine the ports and never reuse them.
* - reconcile touches only Paperclip-owned mappings the broker reports; it can
* never mutate an unknown/manual mapping or the primary `:443` route (the
* broker's `list` never returns those, and remove requires an owned handle).
*/
import type { RuntimeExposureConfigInput, RuntimeExposureStatus } from "@paperclipai/shared";
import {
buildRuntimeExposureHealthUrl,
buildRuntimeExposureUrl,
deriveViteHmrPort,
isRuntimeExposureAppPort,
} from "@paperclipai/shared";
import {
BrokerClientError,
type BrokerClient,
type BrokerListenerRequest,
} from "./broker-client.js";
/** Injected seams — all side effects live behind these for testability. */
export interface ExposureManagerDeps {
broker: BrokerClient;
/** External HTTPS probe; must reject/return false on cert or connection error. */
probeHealth: (healthUrl: string) => Promise<boolean>;
/** ISO timestamp source. Injected so tests are deterministic. */
now: () => string;
/**
* Optional operator-facing diagnosis of the about-to-be-exposed listeners,
* returning null when nothing is provably wrong (PAP-17256).
*
* This does not replace the broker's own loopback gate and cannot loosen it —
* it runs first only so a wildcard bind fails with the port and address named
* instead of a bare `listener_ownership_mismatch`.
*/
diagnoseListenerBinds?: (ports: number[]) => Promise<string | null>;
}
export interface ProvisionInput {
runtimeId: string;
config: RuntimeExposureConfigInput;
/** Broker-issued reservation handle persisted before the backend starts. */
handle: string;
/** Resolved Tailscale node DNS hostname (the manager does not resolve it). */
hostname: string;
/** Loopback app port already allocated in the dedicated range. */
appPort: number;
}
export interface ProvisionResult {
status: RuntimeExposureStatus;
/**
* Server-only lease handle required to later remove the mapping. NEVER
* serialized to the UI or embedded in {@link RuntimeExposureStatus}; persist
* it in a server-private store. Null when nothing was exposed.
*/
handle: string | null;
/**
* Human-readable elaboration of {@link RuntimeExposureStatus.lastError}, when
* one is available (PAP-17256).
*
* Deliberately NOT folded into the persisted status: `lastError` stays the
* broker's stable machine code so the retry/cleanup vocabularies keep matching
* on it. This rides alongside so the caller can put the reason in the failure
* the operator actually reads.
*/
errorDetail?: string | null;
}
export interface ReserveInput {
runtimeId: string;
config: RuntimeExposureConfigInput;
appPort: number;
}
/** Reserve the app/HMR pair before the backend binds either listener. */
export async function reserveExposure(
deps: ExposureManagerDeps,
input: ReserveInput,
): Promise<ProvisionResult> {
const status = baseStatus(deps.now());
if (!isRuntimeExposureAppPort(input.appPort)) {
status.state = "failed";
status.lastError = "app port outside dedicated runtime exposure range";
return { status, handle: null };
}
const requested = buildListenerRequests(input.config, input.appPort);
status.listeners = requested.map((listener) => ({
purpose: listener.purpose,
publicPort: listener.port,
targetPort: listener.port,
}));
status.brokerRef = input.runtimeId;
try {
const result = await deps.broker.reserve(input.runtimeId, requested);
const requestedPorts = new Set(requested.map((listener) => listener.port));
const returnedPorts = new Set(result.reservedPorts);
if (requestedPorts.size !== returnedPorts.size || ![...requestedPorts].every((port) => returnedPorts.has(port))) {
await safeRemove(deps.broker, input.runtimeId, result.handle);
status.state = "failed";
status.lastError = "broker returned unexpected reserved ports";
return { status, handle: null };
}
return { status, handle: result.handle };
} catch (error) {
status.state = "failed";
status.lastError = brokerErrorCode(error);
return { status, handle: null };
}
}
export interface DeprovisionInput {
runtimeId: string;
/** Server-persisted lease handle, or null if none was ever recorded. */
handle: string | null;
/** Ports previously exposed for this runtime (for quarantine on failure). */
ports: number[];
}
export interface DeprovisionResult {
status: RuntimeExposureStatus;
/** Ports that must be quarantined (never reused) after an ambiguous cleanup. */
quarantinedPorts: number[];
}
/** Broker error codes that mean "the mapping is already gone" — cleanup is a no-op. */
const ALREADY_GONE_CODES: ReadonlySet<string> = new Set([
"invalid_handle",
"listener_not_owned",
"listener_ownership_mismatch",
]);
function baseStatus(now: string): RuntimeExposureStatus {
return {
provider: "tailscale_https",
state: "pending",
publicUrl: null,
hostname: null,
listeners: [],
brokerRef: null,
lastError: null,
updatedAt: now,
};
}
/** Build the broker listener request list from a validated exposure config. */
export function buildListenerRequests(
config: RuntimeExposureConfigInput,
appPort: number,
): BrokerListenerRequest[] {
const listeners: BrokerListenerRequest[] = [{ purpose: "app", port: appPort }];
if (config.includePaperclipViteHmr) {
listeners.push({ purpose: "vite_hmr", port: deriveViteHmrPort(appPort) });
}
return listeners;
}
/**
* Provision (or re-provision) the HTTPS exposure for one runtime service.
* Idempotent at the broker level: a repeated call for a still-valid mapping
* simply re-exposes and re-probes. Always returns a fully-formed status; the
* caller persists both the status and the returned server-only handle.
*/
export async function provisionExposure(
deps: ExposureManagerDeps,
input: ProvisionInput,
): Promise<ProvisionResult> {
const now = deps.now();
const status = baseStatus(now);
status.hostname = input.hostname;
if (!isRuntimeExposureAppPort(input.appPort)) {
status.state = "failed";
status.lastError = "app port outside dedicated runtime exposure range";
return { status, handle: input.handle };
}
const requested = buildListenerRequests(input.config, input.appPort);
status.listeners = requested.map((listener) => ({
purpose: listener.purpose,
publicPort: listener.port,
targetPort: listener.port,
}));
status.brokerRef = input.runtimeId;
// Explain a provable off-loopback bind before the broker denies it, so the
// failure names the port and the address instead of only the code.
if (deps.diagnoseListenerBinds) {
const violation = await deps.diagnoseListenerBinds(requested.map((listener) => listener.port));
if (violation) {
status.state = "failed";
status.lastError = "listener_ownership_mismatch";
return { status, handle: input.handle, errorDetail: violation };
}
}
let handle: string;
let publicPorts: number[];
try {
const result = await deps.broker.expose(input.runtimeId, input.handle);
handle = result.handle;
publicPorts = result.publicPorts;
} catch (error) {
status.state = "failed";
status.lastError = brokerErrorCode(error);
return { status, handle: input.handle, errorDetail: brokerErrorDetail(error) };
}
// The broker must return exactly the ports we asked for (same-number). A
// mismatch is a contract violation: tear the mapping back down and fail.
const requestedPorts = new Set(requested.map((l) => l.port));
const returnedPorts = new Set(publicPorts);
if (requestedPorts.size !== returnedPorts.size || ![...requestedPorts].every((p) => returnedPorts.has(p))) {
await safeRemove(deps.broker, input.runtimeId, handle);
status.state = "failed";
status.lastError = "broker returned unexpected public ports";
return { status, handle };
}
// Reflect the attempted mapping regardless of health so the UI can show what
// was provisioned even while probing.
// fail-closed: never report ready until an external, cert-validating probe
// succeeds. Keep the handle so the caller can retry or clean up.
const healthUrl = buildRuntimeExposureHealthUrl(input.hostname, input.appPort);
let healthy = false;
try {
healthy = await deps.probeHealth(healthUrl);
} catch {
healthy = false;
}
if (!healthy) {
status.state = "failed";
status.publicUrl = null;
status.lastError = "external HTTPS health probe did not validate";
return { status, handle };
}
status.state = "ready";
status.publicUrl = buildRuntimeExposureUrl(input.hostname, input.appPort);
status.lastError = null;
return { status, handle };
}
/**
* Tear down the HTTPS exposure for one runtime service. Idempotent: a null or
* already-gone handle resolves to `removed` with no quarantine. A genuine
* cleanup failure resolves to `cleanup_pending` and quarantines the ports.
*/
export async function deprovisionExposure(
deps: ExposureManagerDeps,
input: DeprovisionInput,
): Promise<DeprovisionResult> {
const now = deps.now();
const status = baseStatus(now);
status.state = "removed";
if (input.handle === null) {
// Nothing the server knows to remove — treat as already cleaned up.
return { status, quarantinedPorts: [] };
}
try {
await deps.broker.remove(input.runtimeId, input.handle);
return { status, quarantinedPorts: [] };
} catch (error) {
const code = brokerErrorCode(error);
if (ALREADY_GONE_CODES.has(code)) {
// The mapping is already gone; cleanup is complete and safe.
return { status, quarantinedPorts: [] };
}
// Ambiguous failure: we cannot prove the mapping is gone. Quarantine the
// ports so they are never reused, and surface cleanup_pending.
status.state = "cleanup_pending";
status.lastError = code;
return { status, quarantinedPorts: [...new Set(input.ports)] };
}
}
export interface ReconcileInput {
/** Runtimes whose exposure SHOULD remain. Everything else owned is an orphan. */
desiredRuntimeIds: ReadonlySet<string>;
/** Every server-persisted lease handle, keyed by runtimeId (desired + orphaned). */
handlesByRuntimeId: ReadonlyMap<string, string>;
}
export interface ReconcileResult {
/** Owned+desired runtimes confirmed present in the broker's mapping. */
adopted: string[];
/** Ports removed because their runtime is no longer desired. */
removedOrphanPorts: number[];
/**
* Orphaned owned runtimes we could NOT remove because no handle was persisted.
* Reported for operator/broker-side quarantine; the manager never fabricates a
* handle and never touches a mapping it cannot prove ownership of.
*/
unremovableOrphans: string[];
/** Non-fatal per-runtime removal errors during reconciliation. */
errors: Array<{ runtimeId: string; code: string }>;
}
/**
* Startup / periodic reconciliation. Adopts owned mappings that are still
* desired and removes owned mappings that are not. The broker's `list` only
* ever returns Paperclip-owned listeners, so unknown/manual mappings and the
* primary `:443` route are structurally out of scope here — they can never be
* enumerated, adopted, or removed by this routine.
*/
export async function reconcileExposures(
deps: ExposureManagerDeps,
input: ReconcileInput,
): Promise<ReconcileResult> {
const result: ReconcileResult = {
adopted: [],
removedOrphanPorts: [],
unremovableOrphans: [],
errors: [],
};
const owned = await deps.broker.list();
// Group owned ports by runtimeId.
const portsByRuntime = new Map<string, number[]>();
for (const listener of owned) {
const ports = portsByRuntime.get(listener.runtimeId) ?? [];
ports.push(listener.port);
portsByRuntime.set(listener.runtimeId, ports);
}
for (const [runtimeId, ports] of portsByRuntime) {
if (input.desiredRuntimeIds.has(runtimeId)) {
result.adopted.push(runtimeId);
continue;
}
// Orphan: owned by us but no longer desired.
const handle = input.handlesByRuntimeId.get(runtimeId);
if (!handle) {
result.unremovableOrphans.push(runtimeId);
continue;
}
try {
const removed = await deps.broker.remove(runtimeId, handle);
result.removedOrphanPorts.push(...removed.removedPorts);
} catch (error) {
const code = brokerErrorCode(error);
if (ALREADY_GONE_CODES.has(code)) {
// Already gone — reconciled, count its ports as removed for reporting.
result.removedOrphanPorts.push(...ports);
} else {
result.errors.push({ runtimeId, code });
}
}
}
return result;
}
/** Best-effort remove used on rollback paths; swallows broker errors. */
async function safeRemove(broker: BrokerClient, runtimeId: string, handle: string): Promise<void> {
try {
await broker.remove(runtimeId, handle);
} catch {
/* best effort — the outer flow has already decided to fail */
}
}
function brokerErrorCode(error: unknown): string {
if (error instanceof BrokerClientError) return error.code;
return "internal_error";
}
/**
* The broker's own explanation of a denial, when it adds anything to the code.
*
* The wire protocol already carries it (`BrokerClientError.message`, e.g.
* "listener on 42003 is not loopback-only"); dropping it is what made
* `listener_ownership_mismatch` unactionable in PAP-17254.
*/
function brokerErrorDetail(error: unknown): string | null {
if (!(error instanceof BrokerClientError)) {
return error instanceof Error ? error.message : null;
}
const message = error.message.trim();
return message && message !== error.code ? message : null;
}