Files
PaperClipAI/ui/src/components/WorkspaceRuntimeControls.tsx
T
Devin Foley 7b91fe9ea7 Hide host-path and execution-engine surfaces in managed-sandbox-only mode (#12293)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - An instance can turn on the `enableManagedSandboxOnly` feature,
which hides the local environment and runs every agent in the
platform-managed environment
> - That feature already gated the environment pickers, the onboarding
wizard, and the server-side run selection, but many other screens still
showed absolute paths on the execution host and still let the user pick
an execution engine
> - On such an instance those controls name a filesystem the user cannot
reach; a path written there is stored and then ignored, which reads as a
broken control
> - This pull request hides the remaining host-path and execution-engine
surfaces behind the same feature, adds a server rule that refuses a
project-workspace path write while the feature is on, and closes a
related route gap in the isolated-workspace pages
> - The benefit is that a managed instance shows no host path and no
folder picker anywhere, and a write that carries a path now fails with a
clear message instead of being silently discarded

## Linked Issues or Issue Description

No public issue exists. The description below follows
`.github/ISSUE_TEMPLATE/enhancement.yml`.

**What existing behavior does this improve?**

The `enableManagedSandboxOnly` instance feature, and the UI surfaces
that show
a host filesystem path: project properties, the new-project dialog, the
project
workspace and execution workspace detail pages, the workspace and task
cards,
plugin local folders, and the agent configuration form with its
per-adapter
fields. It also improves route gating for `enableIsolatedWorkspaces`.

**Subsystem affected**

Cross-cutting (`ui/` and `server/`).

**Current behavior**

When `enableManagedSandboxOnly` is on, the local environment disappears
from the
environment pickers and the server refuses to run an agent on the local
host.
Everything else stays visible. A user still sees:

- the project "Local folder" row, its absolute path, and the
Set/Change/Clear buttons
- the "Local folder" field and its "Choose" folder picker in the
new-project dialog
- the "Local path" field and fact row on a project workspace
- the "Paths" and "Lifecycle commands" groups on an execution workspace
- the working directory on workspace cards, task properties, and runtime
service rows
- the plugin "Local folders" section
- "Working directory (deprecated)", "Command", "Execution engine",
"ACP server command", "ACP state directory", and "Agent instructions
file" in
  the agent configuration form

A path typed into any of these names a filesystem no agent on the
instance uses.
The project workspace API also accepts a `cwd` write and stores it.

Separately, `/workspaces`, `/execution-workspaces/*`, and
`/projects/:projectId/workspaces/:workspaceId` render for anyone who
types or
bookmarks the URL, even with `enableIsolatedWorkspaces` off. Only the
sidebar
entry reads that flag.

**Proposed behavior**

With `enableManagedSandboxOnly` on, none of those surfaces render. A
project
whose codebase came from a managed checkout keeps its one-line
"Paperclip-managed folder." label and shows no path. The non-path
controls stay:
repo URL, branch, service URL, port, command output, ACP session mode,
ACP
non-interactive permissions, Codex fast mode, and the sandbox toggles.

The project-workspace create and patch routes, and the nested workspace
on
project create, answer `422` with
"This instance runs agents only in the platform-managed environment;
local
folders are not configurable." when the payload carries a non-null
`cwd`.
A `cwd: null` write still passes, so an instance that just turned the
feature on
can clear a stale path.

With `enableIsolatedWorkspaces` off, the three workspace route groups
redirect to
the dashboard.

**Reason and benefit**

A control that cannot do anything is worse than a missing control: the
user fills
it in, saves, and gets no error and no effect. The server rule turns
that silent
no-op into a clear refusal. The route gate stops a feature that an
instance has
turned off from staying reachable by URL, which is the same standard the
Cases,
Pipelines, and hidden-settings pages already meet.

**Breaking changes**

None for a default instance: both flags are off by default for
self-hosted and
managed instances, so nothing changes unless an operator turns them on.
Stored
`adapterConfig` values are never cleared, so turning the feature off
restores
every previous value.

## What Changed

- Add `ui/src/hooks/useManagedSandboxOnly.ts`, modelled on
`useAppsEnabled`, for
components that do not already read the experimental settings. It
exposes
`hideHostPaths`, which fails closed while the settings query is in
flight, so
a cold cache never flashes a host path before the policy resolves.
Components
that keep their own settings read compute the same gate from
`isFetched`.
- Add `managedSandboxOnly` to `AdapterConfigFieldsProps` and populate it
where
`AgentConfigForm` builds the adapter field props. Resolve the effective
instructions-file gate once as `hideInstructionsFile || hideHostPaths`,
so
  every adapter hides that path field with no per-adapter edit.
- Hide under the flag: the project "Local folder" block and its
absolute-path
  edit panel (a managed checkout keeps its label, without the path); the
new-project "Local folder" field; the project-workspace "Local path"
field and
fact row; the execution-workspace "Paths" and "Lifecycle commands"
groups; the
working directory on the workspace summary card, the task workspace
card, the
task properties "Folder" row, and the runtime service rows; the plugin
"Local
folders" section; "Working directory (deprecated)" and "Command" in the
agent
form; and the per-adapter "Execution engine", "ACP server command", and
"ACP state directory" for `claude_local`, `codex_local`, and
`gemini_local`.
- Drop two working-directory fallbacks that had no gate to read: the
close-workspace
dialog now falls back to "No additional details", and the reuse-existing
  workspace label and picker subtitle fall back to a neutral phrase.
- Refuse a non-null `cwd` with `422` on `POST /projects/:id/workspaces`,
`PATCH /projects/:id/workspaces/:workspaceId`, and the nested workspace
on
  `POST /companies/:companyId/projects`, following the
  `assertNoAgentHostWorkspaceCommandMutation` precedent on those routes.
- Add `IsolatedWorkspacesRouteGate` and wrap the `/workspaces`,
`/execution-workspaces/*`, and
`/projects/:projectId/workspaces/:workspaceId`
  routes with it.
- Leave the SSH "Remote workspace path" and the workspace file browser
alone,
  with a comment explaining why.

## Verification

Automated:

- `pnpm --filter @paperclipai/ui exec vitest run` — 479 of 480 files
pass
(4455 of 4456 tests). The one failure is `OnboardingWizard.test.tsx >
renders
instead of throwing when the browser denies storage access`, which also
fails
  on `origin/master` and is unrelated to this change.
- `pnpm --filter @paperclipai/server exec vitest run project workspace
instance-settings`
— 45 of 50 files pass. Four files fail on macOS for reasons unrelated to
this
  change: `workspace-instance-cleanup`, `workspace-runtime`,
  `execution-workspace-runtime-control-conflict`, and
  `workspace-runtime-exposure` compare `/var/...` against the resolved
`/private/var/...` or bind real ports. The same files fail on a clean
`master`
  checkout on the same machine.
- `pnpm --filter @paperclipai/ui typecheck`
- `tsc --noEmit` in `server/` (after
`pnpm --filter @paperclipai/plugin-sdk ensure-build-deps`). The package
`typecheck` script also builds the Rust runner, which needs `cargo`; it
is not
  installed on the machine that ran this.

New and extended tests:

- `ui/src/adapters/managed-sandbox-only-config-fields.test.tsx` — the
three
adapters drop the execution engine, the ACP paths, the instructions-file
path,
and every "Choose" button when the flag is on, and keep the non-path
controls.
- `ui/src/components/AgentConfigForm.render.test.tsx` — flag-on and
flag-off
renders for the working directory, the command, the engine, the ACP
paths, and
  the resolved adapter field props.
- `ui/src/components/ProjectProperties.managed-sandbox.test.tsx`,
  `ui/src/components/NewProjectDialog.managed-sandbox.test.tsx`,
  `ui/src/pages/ProjectWorkspaceDetail.test.tsx`,
  `ui/src/components/ProjectWorkspaceSummaryCard.test.tsx`,
  `ui/src/components/WorkspaceRuntimeControls.test.tsx`.
- `ui/src/components/IsolatedWorkspacesRouteGate.test.tsx` — redirect
when off,
  render when on, and render nothing while the flag query is in flight.
- "Still loading" cases for the project properties, the new-project
dialog, the
workspace summary card, the runtime service rows, and the agent
configuration
form, each asserting that no host path renders before the policy
resolves.
-
`server/src/__tests__/project-workspace-managed-sandbox-routes.test.ts`
— the
  `422` on all three write paths, the `cwd: null` pass-through, and the
  flag-off pass-through.

Manual check to reproduce: turn on Managed Environment Only in instance
experimental settings, then open a project, the new-project dialog, an
agent's
configuration, and a workspace page. No path, folder icon, or "Choose"
button
appears. Turn the setting off and each control returns with its stored
value.

No documentation change was needed. The operator-facing text for both
settings
lives in the feature catalog entry, which already states the contract
this pull
request now enforces across the UI.

## Risks

- Low. Both flags default to off, so a default instance is unchanged.
- The hidden fields are presentation only. No stored `adapterConfig`
value is
cleared, because an import carries adapter configuration written on
another
instance and clearing it would break that flow. Turning the setting off
shows
  every previous value again.
- The `422` is the one behavior change for an API caller, and only while
the
setting is on. `cwd: null` still passes so a stale path can be cleared.
- The route gate renders nothing until the flag query settles, so an
instance
with isolated workspaces on never flashes a redirect. An instance with
the
  feature off now redirects a bookmarked workspace URL to the dashboard.
- Every host-path guard fails closed while the settings query is in
flight, so a
default instance shows those controls a moment later than before on a
cold
load. That is the safe direction: the alternative flashes a path a
managed
  instance must never show.
- Two path surfaces stay on purpose, each with a comment: the SSH
"Remote
workspace path" is a path on the user's own remote host, and the
workspace file
browser shows workspace-relative paths. The instance Adapters page also
keeps
its "Local path" install option, since that page is an instance-admin
surface
the hosting operator can already hide through the hidden-settings
mechanism.

## Model Used

Claude (Anthropic), Claude Opus, 1M context window, extended thinking,
agentic
tool use through Claude Code.

## 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
- [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
2026-08-27 11:59:14 -07:00

692 lines
25 KiB
TypeScript

import type {
WorkspaceCommandDefinition,
RuntimeExposureStatus,
WorkspaceRuntimeControlTarget,
WorkspaceRuntimeService,
} from "@paperclipai/shared";
import {
listWorkspaceCommandDefinitions,
matchWorkspaceRuntimeServiceToCommand,
} from "@paperclipai/shared";
import { Activity, ExternalLink, Loader2, Play, RotateCcw, Square } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useManagedSandboxOnly } from "@/hooks/useManagedSandboxOnly";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { timeAgo } from "@/lib/timeAgo";
import type {
WorkspaceServiceControlAction,
WorkspaceServiceControlEntry,
} from "@/components/WorkspaceServiceControlBar";
export type WorkspaceRuntimeAction = "start" | "stop" | "restart" | "run";
export type WorkspaceRuntimeControlRequest = WorkspaceRuntimeControlTarget & {
action: WorkspaceRuntimeAction;
};
export type WorkspaceRuntimeControlItem = {
key: string;
title: string;
kind: "service" | "job";
statusLabel: string;
lifecycle: "shared" | "ephemeral" | null;
healthStatus: "unknown" | "healthy" | "unhealthy" | null;
exposure: RuntimeExposureStatus | null;
command: string | null;
cwd: string | null;
port: number | null;
url: string | null;
canStart: boolean;
canRun: boolean;
workspaceCommandId?: string | null;
runtimeServiceId?: string | null;
serviceIndex?: number | null;
disabledReason?: string | null;
};
export type WorkspaceRuntimeControlSections = {
services: WorkspaceRuntimeControlItem[];
jobs: WorkspaceRuntimeControlItem[];
otherServices: WorkspaceRuntimeControlItem[];
};
type LegacyWorkspaceRuntimeControlItem = WorkspaceRuntimeControlItem & {
status?: string | null;
};
type WorkspaceRuntimeControlsProps = {
sections: WorkspaceRuntimeControlSections;
items?: never;
isPending?: boolean;
pendingRequest?: WorkspaceRuntimeControlRequest | null;
serviceEmptyMessage?: string;
jobEmptyMessage?: string;
emptyMessage?: never;
disabledHint?: string | null;
onAction: (request: WorkspaceRuntimeControlRequest) => void;
className?: string;
square?: boolean;
} | {
sections?: never;
items: LegacyWorkspaceRuntimeControlItem[];
isPending?: boolean;
pendingRequest?: WorkspaceRuntimeControlRequest | null;
serviceEmptyMessage?: never;
jobEmptyMessage?: never;
emptyMessage?: string;
disabledHint?: string | null;
onAction: (request: WorkspaceRuntimeControlRequest) => void;
className?: string;
square?: boolean;
};
export function hasRunningRuntimeServices(
runtimeServices: Array<{ status: string }> | null | undefined,
) {
return (runtimeServices ?? []).some((service) => service.status === "starting" || service.status === "running");
}
function buildServiceItem(
command: WorkspaceCommandDefinition,
runtimeService: WorkspaceRuntimeService | null,
canStartServices: boolean,
): WorkspaceRuntimeControlItem {
return {
key: `command:${command.id}:${runtimeService?.id ?? "idle"}`,
title: command.name,
kind: "service",
statusLabel: runtimeService?.status ?? "stopped",
lifecycle: runtimeService?.lifecycle ?? command.lifecycle,
healthStatus: runtimeService?.healthStatus ?? "unknown",
exposure: runtimeService?.exposure ?? null,
command: runtimeService?.command ?? command.command,
cwd: runtimeService?.cwd ?? command.cwd,
port: runtimeService?.port ?? null,
url: runtimeService?.url ?? null,
canStart: canStartServices && !command.disabledReason,
canRun: false,
workspaceCommandId: command.id,
runtimeServiceId: runtimeService?.id ?? null,
serviceIndex: command.serviceIndex,
disabledReason: command.disabledReason,
};
}
function buildJobItem(
command: WorkspaceCommandDefinition,
canRunJobs: boolean,
): WorkspaceRuntimeControlItem {
return {
key: `command:${command.id}`,
title: command.name,
kind: "job",
statusLabel: "run once",
lifecycle: null,
healthStatus: null,
exposure: null,
command: command.command,
cwd: command.cwd,
port: null,
url: null,
canStart: false,
canRun: canRunJobs && !command.disabledReason && Boolean(command.command),
workspaceCommandId: command.id,
runtimeServiceId: null,
serviceIndex: null,
disabledReason: command.disabledReason ?? (!command.command ? "This job is missing a command." : null),
};
}
export function buildWorkspaceRuntimeControlSections(input: {
runtimeConfig: Record<string, unknown> | null | undefined;
runtimeServices: WorkspaceRuntimeService[] | null | undefined;
canStartServices: boolean;
canRunJobs?: boolean;
}): WorkspaceRuntimeControlSections {
const commands = listWorkspaceCommandDefinitions(input.runtimeConfig);
const runtimeServices = [...(input.runtimeServices ?? [])];
const matchedRuntimeServiceIds = new Set<string>();
const services: WorkspaceRuntimeControlItem[] = [];
const jobs: WorkspaceRuntimeControlItem[] = [];
for (const command of commands) {
if (command.kind === "job") {
jobs.push(buildJobItem(command, input.canRunJobs ?? input.canStartServices));
continue;
}
const runtimeService = matchWorkspaceRuntimeServiceToCommand(command, runtimeServices);
if (runtimeService) matchedRuntimeServiceIds.add(runtimeService.id);
services.push(buildServiceItem(command, runtimeService, input.canStartServices));
}
const otherServices = runtimeServices
.filter((runtimeService) =>
!matchedRuntimeServiceIds.has(runtimeService.id)
&& (runtimeService.status === "provisioning"
|| runtimeService.status === "starting"
|| runtimeService.status === "running"))
.map((runtimeService) => ({
key: `runtime:${runtimeService.id}`,
title: runtimeService.serviceName,
kind: "service" as const,
statusLabel: runtimeService.status,
lifecycle: runtimeService.lifecycle,
healthStatus: runtimeService.healthStatus,
exposure: runtimeService.exposure ?? null,
command: runtimeService.command ?? null,
cwd: runtimeService.cwd ?? null,
port: runtimeService.port ?? null,
url: runtimeService.url ?? null,
canStart: false,
canRun: false,
workspaceCommandId: null,
runtimeServiceId: runtimeService.id,
serviceIndex: runtimeService.configIndex ?? null,
disabledReason: "This runtime service no longer matches a configured workspace command.",
}));
return {
services,
jobs,
otherServices,
};
}
export function buildWorkspaceRuntimeControlItems(input: {
runtimeConfig: Record<string, unknown> | null | undefined;
runtimeServices: WorkspaceRuntimeService[] | null | undefined;
canStartServices: boolean;
canRunJobs?: boolean;
}): LegacyWorkspaceRuntimeControlItem[] {
return buildWorkspaceRuntimeControlSections(input).services.map((item) => ({
...item,
status: item.statusLabel,
}));
}
export function getRunningRuntimeServiceUrl(
sections: WorkspaceRuntimeControlSections,
) {
const runningService = [...sections.services, ...sections.otherServices].find(
(item) => (item.statusLabel === "running" || item.statusLabel === "starting") && item.url,
);
return runningService?.url ?? null;
}
function isActiveStatusLabel(statusLabel: string) {
return statusLabel === "running" || statusLabel === "starting" || statusLabel === "provisioning";
}
function exposureFailureCopy(exposure: RuntimeExposureStatus | null) {
if (exposure?.state === "failed") {
return {
label: "HTTPS unavailable",
remediation: "Check the Tailscale broker and node HTTPS configuration.",
};
}
if (exposure?.state === "cleanup_pending") {
return {
label: "HTTPS cleanup pending",
remediation: "Restart the host broker before reusing this port.",
};
}
return null;
}
function ExposureFailureDetail({ exposure }: { exposure: RuntimeExposureStatus | null }) {
const copy = exposureFailureCopy(exposure);
if (!copy) return null;
return (
<div className="space-y-1 break-words text-xs text-destructive" role="alert">
<div
className="line-clamp-3 font-medium"
title={exposure?.lastError ?? undefined}
>
{copy.label}
{exposure?.lastError ? ` · ${exposure.lastError}` : ""}
</div>
<div>{copy.remediation}</div>
</div>
);
}
/**
* Maps runtime control sections onto the fixed-geometry service control bar
* model. In-flight mutations overlay the transitional states (starting /
* stopping / restarting) that the server status enum does not carry.
*/
export function buildWorkspaceServiceControlEntries(input: {
sections: WorkspaceRuntimeControlSections;
runtimeServices?: WorkspaceRuntimeService[] | null;
isPending?: boolean;
pendingRequest?: WorkspaceRuntimeControlRequest | null;
pendingRequests?: WorkspaceRuntimeControlRequest[];
}): WorkspaceServiceControlEntry[] {
const runtimeServicesById = new Map(
(input.runtimeServices ?? []).map((runtimeService) => [runtimeService.id, runtimeService]),
);
const pendingRequests = input.pendingRequests
?? (input.isPending && input.pendingRequest ? [input.pendingRequest] : []);
return [...input.sections.services, ...input.sections.otherServices].map((item) => {
let state: WorkspaceServiceControlEntry["state"] =
item.statusLabel === "running"
? "running"
: item.statusLabel === "provisioning"
? "provisioning"
: item.statusLabel === "starting"
? "starting"
: item.statusLabel === "failed"
? "failed"
: "stopped";
const pendingRequest = pendingRequests.find((request) =>
request.action !== "run"
&& (request.workspaceCommandId ?? null) === (item.workspaceCommandId ?? null)
&& (request.runtimeServiceId ?? null) === (item.runtimeServiceId ?? null)
&& (request.serviceIndex ?? null) === (item.serviceIndex ?? null));
if (pendingRequest) {
state = pendingRequest.action === "stop"
? "stopping"
: pendingRequest.action === "restart"
? "restarting"
: "starting";
}
const runtimeService = item.runtimeServiceId ? runtimeServicesById.get(item.runtimeServiceId) ?? null : null;
const failureDetail = state === "failed"
? `Service failed${runtimeService?.stoppedAt ? ` · ${timeAgo(runtimeService.stoppedAt)}` : ""}`
: null;
const exposure = runtimeService?.exposure ?? item.exposure;
const exposureFailure = exposureFailureCopy(exposure);
const exposureDetail = exposure?.state === "pending"
? "Provisioning HTTPS…"
: exposure?.state === "ready"
? "HTTPS ready"
: exposureFailure
? `${exposureFailure.label} · ${exposureFailure.remediation}`
: null;
return {
key: item.key,
name: item.title,
state,
healthStatus: item.healthStatus,
url: item.url,
port: item.port,
failureDetail,
exposureState: exposure?.state ?? null,
exposureDetail,
canStart: item.canStart,
};
});
}
/**
* Resolves a control-bar action into the runtime control requests to fire.
* A null serviceKey targets every applicable service (the aggregate bar and
* popover bulk actions).
*/
export function resolveWorkspaceServiceControlRequests(
sections: WorkspaceRuntimeControlSections,
action: WorkspaceServiceControlAction,
serviceKey: string | null,
): WorkspaceRuntimeControlRequest[] {
const items = [...sections.services, ...sections.otherServices];
if (serviceKey !== null) {
const item = items.find((candidate) => candidate.key === serviceKey);
return item ? [buildRequest(item, action)] : [];
}
if (action === "stop") {
return items
.filter((item) => isActiveStatusLabel(item.statusLabel))
.map((item) => buildRequest(item, "stop"));
}
if (action === "start") {
return items
.filter((item) => !isActiveStatusLabel(item.statusLabel) && item.canStart)
.map((item) => buildRequest(item, "start"));
}
return items.flatMap((item) => {
if (isActiveStatusLabel(item.statusLabel)) return [buildRequest(item, "restart")];
if (item.canStart) return [buildRequest(item, "start")];
return [];
});
}
function requestMatchesPending(
pendingRequest: WorkspaceRuntimeControlRequest | null | undefined,
nextRequest: WorkspaceRuntimeControlRequest,
) {
return pendingRequest?.action === nextRequest.action
&& (pendingRequest?.workspaceCommandId ?? null) === (nextRequest.workspaceCommandId ?? null)
&& (pendingRequest?.runtimeServiceId ?? null) === (nextRequest.runtimeServiceId ?? null)
&& (pendingRequest?.serviceIndex ?? null) === (nextRequest.serviceIndex ?? null);
}
function buildRequest(item: WorkspaceRuntimeControlItem, action: WorkspaceRuntimeAction): WorkspaceRuntimeControlRequest {
return {
action,
workspaceCommandId: item.workspaceCommandId ?? null,
runtimeServiceId: item.runtimeServiceId ?? null,
serviceIndex: item.serviceIndex ?? null,
};
}
function CommandActionButtons({
item,
isPending,
pendingRequest,
onAction,
square,
iconOnly,
}: {
item: WorkspaceRuntimeControlItem;
isPending: boolean;
pendingRequest: WorkspaceRuntimeControlRequest | null | undefined;
onAction: (request: WorkspaceRuntimeControlRequest) => void;
square?: boolean;
iconOnly?: boolean;
}) {
const actions: WorkspaceRuntimeAction[] =
item.kind === "job"
? ["run"]
: item.statusLabel === "running" || item.statusLabel === "starting"
? ["stop", ...(item.canStart ? ["restart" as const] : [])]
: ["start"];
return (
<div className={cn("flex gap-2", iconOnly ? "w-auto flex-row flex-wrap" : "w-full flex-col sm:w-auto sm:flex-row sm:flex-wrap")}>
{actions.map((action) => {
const request = buildRequest(item, action);
const Icon = action === "stop" ? Square : action === "restart" ? RotateCcw : Play;
const label = action === "run"
? "Run"
: action === "start"
? "Start"
: action === "stop"
? "Stop"
: "Restart";
const showSpinner = isPending && requestMatchesPending(pendingRequest, request);
const disabled =
isPending
|| (action === "run" && !item.canRun)
|| ((action === "start" || action === "restart") && !item.canStart);
return (
<Button
key={`${item.key}:${action}`}
variant={iconOnly ? "outline" : action === "stop" ? "destructive" : action === "restart" ? "outline" : "default"}
size={iconOnly ? "icon-xs" : "sm"}
className={cn(
iconOnly ? "shrink-0" : "w-full justify-start sm:w-auto",
square ? "rounded-none" : null,
)}
disabled={disabled}
onClick={() => onAction(request)}
aria-label={label}
title={label}
>
{showSpinner ? <Loader2 className="h-4 w-4 animate-spin" /> : <Icon className="h-4 w-4" />}
{iconOnly ? <span className="sr-only">{label}</span> : label}
</Button>
);
})}
</div>
);
}
function CommandSection({
title,
description,
items,
emptyMessage,
disabledHint,
isPending,
pendingRequest,
onAction,
square,
iconOnly,
}: {
title: string;
description: string;
items: WorkspaceRuntimeControlItem[];
emptyMessage: string;
disabledHint?: string | null;
isPending: boolean;
pendingRequest: WorkspaceRuntimeControlRequest | null | undefined;
onAction: (request: WorkspaceRuntimeControlRequest) => void;
square?: boolean;
iconOnly?: boolean;
}) {
// Managed-sandbox-only policy: the working directory is a path on the
// execution host, so the command rows drop it, and keep dropping it until the
// policy is known. The URL, the port, and the command itself stay — they
// describe the service, not the host filesystem.
const { hideHostPaths } = useManagedSandboxOnly();
return (
<div className="space-y-3">
<div className="space-y-1">
<div className="text-sm font-medium">{title}</div>
<p className="text-xs text-muted-foreground">{description}</p>
</div>
{items.length === 0 ? (
<div className={cn("border border-dashed border-border/80 bg-background px-3 py-4 text-sm text-muted-foreground", square ? "rounded-none" : "rounded-xl")}>
{emptyMessage}
{disabledHint ? <p className="mt-2 text-xs">{disabledHint}</p> : null}
</div>
) : (
<div className="space-y-3">
{items.map((item) => (
<div key={item.key} className={cn("border border-border/80 bg-background px-3 py-3", square ? "rounded-none" : "rounded-xl")}>
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="space-y-1">
<div className="text-sm font-medium">{item.title}</div>
<div className="text-xs text-muted-foreground">
{item.kind} · {item.statusLabel}
{item.lifecycle ? ` · ${item.lifecycle}` : ""}
</div>
</div>
<CommandActionButtons
item={item}
isPending={isPending}
pendingRequest={pendingRequest}
onAction={onAction}
square={square}
iconOnly={iconOnly}
/>
</div>
<div className="space-y-1 text-xs text-muted-foreground">
{item.url ? (
<a href={item.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 hover:underline">
{item.url}
<ExternalLink className="h-3.5 w-3.5" />
</a>
) : null}
{item.port ? <div>Port {item.port}</div> : null}
{item.command ? <div className="break-all font-mono">{item.command}</div> : null}
{item.cwd && !hideHostPaths ? <div className="break-all font-mono">{item.cwd}</div> : null}
{item.disabledReason ? <div>{item.disabledReason}</div> : null}
</div>
<ExposureFailureDetail exposure={item.exposure} />
{item.healthStatus && item.statusLabel !== "stopped" ? (
<div className="flex items-center gap-2">
<Badge variant="outline" className={cn(
"px-2.5 py-1 text-(length:--text-micro)",
item.healthStatus === "healthy"
? "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"
: item.healthStatus === "unhealthy"
? "border-destructive/30 bg-destructive/10 text-destructive"
: "border-border text-muted-foreground",
)}>
{item.healthStatus}
</Badge>
</div>
) : null}
</div>
</div>
))}
</div>
)}
</div>
);
}
export function WorkspaceRuntimeControls({
sections,
items,
isPending = false,
pendingRequest = null,
serviceEmptyMessage = "No services are configured for this workspace.",
jobEmptyMessage = "No one-shot jobs are configured for this workspace.",
emptyMessage,
disabledHint = null,
onAction,
className,
square,
}: WorkspaceRuntimeControlsProps) {
const resolvedSections = sections ?? {
services: (items ?? []).map((item) => ({
...item,
statusLabel: item.statusLabel ?? item.status ?? "stopped",
})),
jobs: [],
otherServices: [],
};
const resolvedServiceEmptyMessage = emptyMessage ?? serviceEmptyMessage;
const runningCount = [...resolvedSections.services, ...resolvedSections.otherServices].filter(
(item) => item.statusLabel === "running" || item.statusLabel === "starting",
).length;
const visibleDisabledHint = runningCount > 0 || disabledHint === null ? null : disabledHint;
return (
<div className={cn("space-y-4", className)}>
<div className={cn("border border-border/70 bg-background p-3", square ? "rounded-none" : "rounded-xl")}>
<div className="space-y-1">
<div className="text-xs font-medium uppercase tracking-(--tracking-eyebrow) text-muted-foreground">Workspace commands</div>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline"
className={cn(
"gap-1.5 px-2.5 py-1",
runningCount > 0
? "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"
: "border-border bg-background text-muted-foreground",
)}
>
<Activity className="h-3.5 w-3.5" />
{runningCount > 0 ? `${runningCount} services running` : "No services running"}
</Badge>
<span className="text-xs text-muted-foreground">
{resolvedSections.jobs.length > 0
? `${resolvedSections.jobs.length} job${resolvedSections.jobs.length === 1 ? "" : "s"} available to run on demand.`
: "Each command can be controlled independently."}
</span>
</div>
{visibleDisabledHint ? <p className="text-xs text-muted-foreground">{visibleDisabledHint}</p> : null}
</div>
</div>
<CommandSection
title="Services"
description="Long-running commands that Paperclip can supervise for this workspace."
items={resolvedSections.services}
emptyMessage={resolvedServiceEmptyMessage}
disabledHint={visibleDisabledHint}
isPending={isPending}
pendingRequest={pendingRequest}
onAction={onAction}
square={square}
/>
<CommandSection
title="Jobs"
description="One-shot commands that run now and exit when they finish."
items={resolvedSections.jobs}
emptyMessage={jobEmptyMessage}
isPending={isPending}
pendingRequest={pendingRequest}
onAction={onAction}
square={square}
/>
{resolvedSections.otherServices.length > 0 ? (
<CommandSection
title="Untracked services"
description="Running services that no longer match the current workspace command config."
items={resolvedSections.otherServices}
emptyMessage=""
isPending={isPending}
pendingRequest={pendingRequest}
onAction={onAction}
square={square}
/>
) : null}
</div>
);
}
export function WorkspaceRuntimeQuickControls({
sections,
isPending = false,
pendingRequest = null,
onAction,
square,
align = "end",
iconOnly = false,
}: {
sections: WorkspaceRuntimeControlSections;
isPending?: boolean;
pendingRequest?: WorkspaceRuntimeControlRequest | null;
onAction: (request: WorkspaceRuntimeControlRequest) => void;
square?: boolean;
align?: "start" | "end";
iconOnly?: boolean;
}) {
const controlItems = sections.services.length > 0 ? sections.services : sections.otherServices;
const serviceUrl = getRunningRuntimeServiceUrl(sections);
const alignEnd = align === "end";
if (controlItems.length === 0 && !serviceUrl) return null;
return (
<div className={cn("flex min-w-0 flex-col items-stretch gap-2", alignEnd ? "sm:items-end" : "sm:items-start")}>
{controlItems.length > 0 ? (
<div className={cn("flex max-w-full flex-col gap-2 sm:flex-row sm:flex-wrap", alignEnd ? "sm:justify-end" : "sm:justify-start")}>
{controlItems.map((item) => (
<div key={item.key} className={cn("flex min-w-0 flex-col gap-1", alignEnd ? "sm:items-end" : "sm:items-start")}>
{controlItems.length > 1 ? (
<span className="truncate text-xs text-muted-foreground">{item.title}</span>
) : null}
<CommandActionButtons
item={item}
isPending={isPending}
pendingRequest={pendingRequest}
onAction={onAction}
square={square}
iconOnly={iconOnly}
/>
</div>
))}
</div>
) : null}
{serviceUrl ? (
<a
href={serviceUrl}
target="_blank"
rel="noreferrer"
className={cn(
"inline-flex min-w-0 items-center gap-1 self-start break-all text-xs text-muted-foreground hover:text-foreground hover:underline",
alignEnd ? "sm:self-end" : "sm:self-start",
)}
>
{serviceUrl}
<ExternalLink className="h-3.5 w-3.5 shrink-0" />
</a>
) : null}
</div>
);
}