Files
PaperClipAI/packages/shared/src/workspace-commands.ts
T
DottaandPaperclip b51112798f feat(apps): improve gateway and workspace connection UX (#12340)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - App connections must work in both the operator UI and agent tool
gateway.
> - The first stack layer adds secure remote connections.
> - Operators still need clear setup, test, and recovery states.
> - This pull request adds the gateway behavior and the workspace
connection experience.
> - The benefit is a connection flow that is easier to understand and
recover.

## Linked Issues or Issue Description

Refs #11965

This is stack 2 of 11. It depends on stack 1 and replaces another
reviewable part of #11965.

## What Changed

- Improve remote tool gateway connection behavior.
- Add clearer app setup, test, and recovery states.
- Add focused server and UI tests for the new paths.
- Keep the diff isolated from later identity and catalog work.
- Stabilize DNS-pinned remote HTTP protocol fixtures and the
managed-runtime public-origin fixture for this independently tested
layer.

## Verification

- `pnpm -r typecheck`
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/tool-access-service.test.ts` (150 passed)
- `pnpm test:run`
- `pnpm check:token-gates`
- `pnpm build`

## Risks

- Gateway errors now surface through new user-facing states.
- A stale connection can require a new setup attempt.
- The change does not add a database migration.
- The injected HTTP transport and public URL are test-only fixtures;
production DNS pinning and runtime behavior are unchanged.

> I checked `ROADMAP.md`. This stack continues the existing app
connection work from #11965 and does not duplicate another planned item.

## Model Used

OpenAI Codex, GPT-5. The runtime model ID and context window were not
exposed. The model used reasoning, 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
- [x] My branch name describes the change and contains no internal
Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-08-29 12:08:32 -05:00

243 lines
7.8 KiB
TypeScript

import type { WorkspaceCommandDefinition, WorkspaceRuntimeService } from "./types/workspace-runtime.js";
import { forceLoopbackBindInCommand } from "./runtime-exposure/loopback-bind.js";
type WorkspaceRuntimeServiceMatchCandidate =
& Pick<WorkspaceRuntimeService, "configIndex" | "serviceName" | "command" | "cwd">
& Pick<Partial<WorkspaceRuntimeService>, "exposure" | "port">;
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function readNonEmptyString(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function readConfiguredPort(value: unknown): number | null {
if (isRecord(value) && value.type === "auto") return null;
const candidate = isRecord(value) ? value.value : value;
return typeof candidate === "number"
&& Number.isInteger(candidate)
&& candidate > 0
&& candidate <= 65_535
? candidate
: null;
}
function slugify(value: string | null | undefined) {
const normalized = (value ?? "")
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "");
return normalized.length > 0 ? normalized : null;
}
function deriveWorkspaceCommandId(input: {
kind: WorkspaceCommandDefinition["kind"];
explicitId: string | null;
name: string;
index: number;
}) {
const explicitId = slugify(input.explicitId);
if (explicitId) return explicitId;
const nameSlug = slugify(input.name);
return nameSlug ? `${input.kind}:${nameSlug}` : `${input.kind}:${input.index + 1}`;
}
function buildWorkspaceCommandDefinition(input: {
entry: Record<string, unknown>;
kind: WorkspaceCommandDefinition["kind"];
sourceKey: WorkspaceCommandDefinition["source"]["key"];
sourceIndex: number;
serviceIndex: number | null;
fallbackName: string;
}): WorkspaceCommandDefinition {
return {
id: deriveWorkspaceCommandId({
kind: input.kind,
explicitId: readNonEmptyString(input.entry.id),
name:
readNonEmptyString(input.entry.name)
?? readNonEmptyString(input.entry.label)
?? readNonEmptyString(input.entry.title)
?? input.fallbackName,
index: input.sourceIndex,
}),
name:
readNonEmptyString(input.entry.name)
?? readNonEmptyString(input.entry.label)
?? readNonEmptyString(input.entry.title)
?? input.fallbackName,
kind: input.kind,
command: readNonEmptyString(input.entry.command),
cwd: readNonEmptyString(input.entry.cwd),
port: readConfiguredPort(input.entry.port),
lifecycle:
input.kind === "service"
? input.entry.lifecycle === "ephemeral"
? "ephemeral"
: "shared"
: null,
serviceIndex: input.serviceIndex,
disabledReason: readNonEmptyString(input.entry.disabledReason),
rawConfig: { ...input.entry },
source: {
type: "paperclip",
key: input.sourceKey,
index: input.sourceIndex,
},
};
}
function uniqueWorkspaceCommandId(
seen: Set<string>,
commandId: string,
sourceKey: WorkspaceCommandDefinition["source"]["key"],
sourceIndex: number,
) {
if (!seen.has(commandId)) {
seen.add(commandId);
return commandId;
}
const fallbackId = `${commandId}-${sourceKey}-${sourceIndex + 1}`;
seen.add(fallbackId);
return fallbackId;
}
function readCommandEntries(
workspaceRuntime: Record<string, unknown> | null | undefined,
key: "commands" | "services" | "jobs",
) {
const raw = workspaceRuntime?.[key];
return Array.isArray(raw) ? raw.filter((entry): entry is Record<string, unknown> => isRecord(entry)) : [];
}
export function listWorkspaceCommandDefinitions(
workspaceRuntime: Record<string, unknown> | null | undefined,
): WorkspaceCommandDefinition[] {
if (!workspaceRuntime) return [];
const commandEntries = readCommandEntries(workspaceRuntime, "commands");
const seenIds = new Set<string>();
let nextServiceIndex = 0;
const finalize = (command: WorkspaceCommandDefinition) => ({
...command,
id: uniqueWorkspaceCommandId(seenIds, command.id, command.source.key, command.source.index),
});
if (commandEntries.length > 0) {
return commandEntries.map((entry, index) =>
finalize(buildWorkspaceCommandDefinition({
entry,
kind: entry.kind === "job" ? "job" : "service",
sourceKey: "commands",
sourceIndex: index,
serviceIndex: entry.kind === "job" ? null : nextServiceIndex++,
fallbackName: entry.kind === "job" ? `Job ${index + 1}` : `Service ${index + 1}`,
})));
}
const serviceDefinitions = readCommandEntries(workspaceRuntime, "services").map((entry, index) =>
finalize(buildWorkspaceCommandDefinition({
entry,
kind: "service",
sourceKey: "services",
sourceIndex: index,
serviceIndex: nextServiceIndex++,
fallbackName: `Service ${index + 1}`,
})));
const jobDefinitions = readCommandEntries(workspaceRuntime, "jobs").map((entry, index) =>
finalize(buildWorkspaceCommandDefinition({
entry,
kind: "job",
sourceKey: "jobs",
sourceIndex: index,
serviceIndex: null,
fallbackName: `Job ${index + 1}`,
})));
return [...serviceDefinitions, ...jobDefinitions];
}
export function listWorkspaceServiceCommandDefinitions(
workspaceRuntime: Record<string, unknown> | null | undefined,
) {
return listWorkspaceCommandDefinitions(workspaceRuntime).filter((command) => command.kind === "service");
}
export function findWorkspaceCommandDefinition(
workspaceRuntime: Record<string, unknown> | null | undefined,
workspaceCommandId: string | null | undefined,
) {
const normalizedId = readNonEmptyString(workspaceCommandId);
if (!normalizedId) return null;
return listWorkspaceCommandDefinitions(workspaceRuntime).find((command) => command.id === normalizedId) ?? null;
}
export function scoreWorkspaceRuntimeServiceMatch(
command: Pick<WorkspaceCommandDefinition, "serviceIndex" | "name" | "command" | "cwd" | "port">,
runtimeService: WorkspaceRuntimeServiceMatchCandidate,
) {
const exposedCommandMatches = Boolean(
command.command
&& runtimeService.command
&& runtimeService.exposure?.provider === "tailscale_https"
&& runtimeService.command === forceLoopbackBindInCommand(command.command),
);
if (
command.command
&& runtimeService.command
&& runtimeService.command !== command.command
&& !exposedCommandMatches
) {
return -1;
}
if (command.port !== null && runtimeService.port != null && runtimeService.port !== command.port) {
return -1;
}
if (command.serviceIndex !== null && runtimeService.configIndex !== null && runtimeService.configIndex !== undefined) {
if (runtimeService.configIndex !== command.serviceIndex) return -1;
return 100 + (command.port !== null && runtimeService.port === command.port ? 8 : 0);
}
let score = 0;
if (command.port !== null && runtimeService.port === command.port) score += 8;
if (runtimeService.serviceName === command.name) score += 4;
if ((runtimeService.command ?? null) === (command.command ?? null)) score += 4;
if (
command.cwd
&& runtimeService.cwd
&& (runtimeService.cwd === command.cwd || runtimeService.cwd.endsWith(`/${command.cwd}`))
) {
score += 2;
}
return score;
}
export function matchWorkspaceRuntimeServiceToCommand<
T extends WorkspaceRuntimeServiceMatchCandidate,
>(
command: Pick<WorkspaceCommandDefinition, "serviceIndex" | "name" | "command" | "cwd" | "port">,
runtimeServices: T[] | null | undefined,
) {
let bestMatch: T | null = null;
let bestScore = -1;
for (const runtimeService of runtimeServices ?? []) {
const score = scoreWorkspaceRuntimeServiceMatch(command, runtimeService);
if (score > bestScore) {
bestMatch = runtimeService;
bestScore = score;
}
}
return bestScore > 0 ? bestMatch : null;
}