Files
PaperClipAI/packages/adapter-utils/src/runtime-progress.ts
T
Devin Foley adfbe2d4b9 feat(environments): refer to the managed default environment by name, not the sandbox driver key (#11838)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Managed deployments provision a platform-managed default environment
for agent runs; the UI shows this environment in selectors, the agent
form, run details, and the environments page
> - Those surfaces append the raw driver key to the environment name, so
users see labels like "Paperclip Computer (sandbox)", "Paperclip
Computer · sandbox", and fallback copy such as "Managed sandbox" and
"The sandbox has no ready authentication"
> - "sandbox" is infrastructure vocabulary, not the product name of the
environment; showing it next to the managed environment's name is
confusing and off-brand
> - This pull request renders platform-managed environments by name
alone and rewords the sandbox-phrased copy, while user-created
environments keep the driver suffix so mixed lists stay distinguishable
> - The benefit is that the default environment reads as one clear
product name everywhere, and self-hosted users lose nothing: their own
environments still show the driver

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Display of the platform-managed default environment across the UI.

**Subsystem affected**

UI (environment selectors, agent config form, environments page, agents
page, run details) and the claude-local/codex-local adapter auth checks.

**Current behavior**

The agent form labels the inherited default environment as "Name
(sandbox)". Environment selectors and the environments list render "Name
· sandbox". The agents page describes the environment as "<provider>
sandbox provider". The agent form's fallback label is "Managed sandbox".
Adapter auth checks say "The sandbox has no ready authentication for
this adapter."

**Proposed behavior**

Platform-managed environment rows (`metadata.managedByPaperclip`) render
their name alone. The fallback label is "Paperclip Computer". The agents
page describes managed environments as "Managed by Paperclip". Run
details omit the driver suffix for sandbox-driver environments (the
adjacent Provider entry already identifies the mechanism). Adapter auth
checks say "This environment has no ready authentication for this
adapter."

**Reason and benefit**

The managed environment carries a product name. Appending the raw driver
key ("sandbox") to it is noise and contradicts the product naming.
User-created environments keep the driver suffix, so mixed lists stay
distinguishable.

**Breaking changes**

None. Message text of the auth check is not read programmatically; the
UI keys off `ADAPTER_AUTH_MISSING_CHECK_CODE`. Rows without the managed
marker render exactly as before.

## What Changed

- New `environmentDisplayLabel` helper in
`ui/src/lib/managed-sandbox-environment.ts`: managed rows → name alone;
other rows → "Name · driver".
- `AgentConfigForm`: inherited-default label uses the helper; fallback
copy "Managed sandbox" → "Paperclip Computer"; environment options use
the helper.
- `ProjectProperties`, `CompanyEnvironments`: environment selector
options use the helper; the environments-list row hides the driver
suffix on managed rows; the managed detail page's fallback description
no longer says "sandbox".
- `Agents` page: managed environments are described as "Managed by
Paperclip" instead of "<provider> sandbox provider".
- `CommentThread` run details: the driver suffix is omitted for
sandbox-driver environments.
- claude-local and codex-local adapters: auth-missing check message/hint
reworded from "sandbox" to "environment" (ACP and environment-test
paths); claude-local probe/effort/login hints reworded the same way.
- Run status lines: "Syncing workspace to sandbox", "Exporting git
changes from sandbox", "Starting adapter in sandbox", and friends now
say "environment"; "Finalizing sandbox workspace" → "Finalizing
workspace". Templated transfer-progress lines map the `sandbox`
transport key to "environment" for display (`runtime-progress.ts`).
- Agent form sign-in panel: "Sign in to the sandbox" → "Sign in to the
environment"; "Authenticated. The sandbox has credentials now." → "…The
environment has credentials now."
- Feature catalog + instance settings card: "Managed Sandbox Only" →
"Managed Environment Only" (setting key unchanged; the card keeps its
alphabetical slot).
- Server agents routes: execution-target failure and test-identity copy
no longer say "sandbox"; workspace-mode label "Cloud sandbox" → "Cloud
environment".
- Tests: new `environmentDisplayLabel` unit cases; new `AgentConfigForm`
render case asserting the managed default renders without "(sandbox)" or
"· sandbox"; status-line assertions updated across adapter-utils, server
heartbeat/live-run, and UI chat suites.

## Verification

- `pnpm --filter @paperclipai/ui typecheck` — clean.
- `pnpm --filter @paperclipai/adapter-claude-local typecheck` and
`--filter @paperclipai/adapter-codex-local typecheck` — clean.
- `vitest run` for `managed-sandbox-environment.test.ts`,
`AgentConfigForm.render.test.tsx`, `CompanyEnvironments.test.tsx`,
`Agents.test.tsx`, `CommentThread.test.tsx`, `NewAgent.test.tsx` — all
green (118 tests across the two runs).

## Risks

Low risk. Cosmetic label changes only; no data or API changes. Rows
without `metadata.managedByPaperclip` render exactly as before, so
self-hosted deployments with their own environments see no change. The
only self-hosted-visible wording changes are the adapter auth-check
message and the driver suffix omission on sandbox-driver rows in run
details.

## Model Used

- Claude (Anthropic) — claude-fable-5 (Claude Fable 5), Claude Code CLI,
extended thinking, tool use.

## 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 (no
docs reference these labels)
- [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-21 12:51:22 -07:00

175 lines
6.4 KiB
TypeScript

// Shared, throttled progress reporting for execution-target sync/restore.
//
// Transports (sandbox / SSH) own the byte counting and call `report()` as bytes
// move; orchestrators own the per-phase label and direction. The reporter
// throttles emits so a long transfer doesn't flood the log: a line is emitted
// only when the percentage crosses a step boundary (default every 10%) or once
// at least `minIntervalMs` has elapsed since the last emit. The terminal
// completion line is always emitted via `complete()` (or when `report()` reaches
// the known total).
/** A sink for fully-formatted progress lines (newline included). */
export type RuntimeProgressSink = (line: string) => void | Promise<void>;
export type RuntimeProgressPhase =
| "Syncing"
| "Restoring"
| "Importing git history"
| "Exporting git history";
export type RuntimeProgressDirection = "to" | "from";
export type RuntimeProgressTarget = "sandbox" | "ssh";
export type RuntimeStatusPhase =
| "git_sync"
| "config_sync"
| "adapter_startup"
| "restore"
| "export"
| "finalize";
export interface RuntimeStatusUpdate {
phase: RuntimeStatusPhase;
message: string;
currentToolName?: string | null;
lastAssistantSnippet?: string | null;
lastEventAt?: Date | string | null;
}
export type RuntimeStatusSink = (update: RuntimeStatusUpdate) => void | Promise<void>;
export interface RuntimeProgressReporterOptions {
sink: RuntimeProgressSink;
phase: RuntimeProgressPhase;
/** Optional per-phase label, e.g. "workspace" or an asset key. */
label?: string;
direction: RuntimeProgressDirection;
target: RuntimeProgressTarget;
/** Emit when the percentage crosses this step. Default 10. */
stepPercent?: number;
/** Emit when at least this many ms have elapsed since the last emit. Default 2000. */
minIntervalMs?: number;
/** Injectable clock for deterministic tests. Default `Date.now`. */
now?: () => number;
}
export interface RuntimeProgressReporter {
/**
* Report progress. Throttled: only emits on a step crossing or after
* `minIntervalMs`. When `totalBytes` is known and `doneBytes` reaches it, the
* terminal 100% line is emitted and the reporter is marked complete.
*/
report(doneBytes: number, totalBytes: number | null): Promise<void>;
/**
* Emit the terminal completion line if it hasn't been emitted yet. Idempotent.
*/
complete(doneBytes?: number, totalBytes?: number | null): Promise<void>;
/**
* Emit a terminal failure line if no terminal line has been emitted yet, so a
* failed transfer leaves an explicit marker instead of a dangling percentage.
* Idempotent and mutually exclusive with `complete()`.
*/
fail(doneBytes?: number, totalBytes?: number | null): Promise<void>;
}
const BYTES_PER_MB = 1024 * 1024;
function formatMb(bytes: number): string {
return (Math.max(0, bytes) / BYTES_PER_MB).toFixed(1);
}
function clampPercent(value: number): number {
if (!Number.isFinite(value)) return 0;
return Math.min(100, Math.max(0, Math.round(value)));
}
export function createRuntimeProgressReporter(
options: RuntimeProgressReporterOptions,
): RuntimeProgressReporter {
const stepPercent = options.stepPercent && options.stepPercent > 0 ? options.stepPercent : 10;
const minIntervalMs =
options.minIntervalMs && options.minIntervalMs > 0 ? options.minIntervalMs : 2000;
const now = options.now ?? Date.now;
// "sandbox" is the transport key, not product vocabulary: progress lines are
// user-visible run status, and the product refers to the run's machine as an
// environment ("Paperclip Computer" on managed deployments).
const targetDisplay = options.target === "sandbox" ? "environment" : options.target;
const prefix = `[paperclip] ${options.phase}${options.label ? ` ${options.label}` : ""} ${options.direction} ${targetDisplay}`;
let lastEmitAt: number | null = null;
let lastStep = -1;
let lastDoneBytes = 0;
let lastTotalBytes: number | null = null;
let completed = false;
function buildLine(doneBytes: number, totalBytes: number | null): string {
if (totalBytes != null && totalBytes > 0) {
const pct = clampPercent((doneBytes / totalBytes) * 100);
return `${prefix}: ${pct}% (${formatMb(doneBytes)}/${formatMb(totalBytes)} MB)\n`;
}
return `${prefix}: ${formatMb(doneBytes)} MB\n`;
}
function buildFailLine(doneBytes: number, totalBytes: number | null): string {
if (totalBytes != null && totalBytes > 0) {
const pct = clampPercent((doneBytes / totalBytes) * 100);
return `${prefix}: failed at ${pct}% (${formatMb(doneBytes)}/${formatMb(totalBytes)} MB)\n`;
}
return `${prefix}: failed after ${formatMb(doneBytes)} MB\n`;
}
async function emit(doneBytes: number, totalBytes: number | null): Promise<void> {
lastEmitAt = now();
if (totalBytes != null && totalBytes > 0) {
lastStep = Math.floor(((doneBytes / totalBytes) * 100) / stepPercent);
}
await options.sink(buildLine(doneBytes, totalBytes));
}
return {
async report(doneBytes, totalBytes) {
lastDoneBytes = doneBytes;
lastTotalBytes = totalBytes;
if (completed) return;
const elapsedOk = lastEmitAt == null || now() - lastEmitAt >= minIntervalMs;
if (totalBytes != null && totalBytes > 0) {
const terminal = doneBytes >= totalBytes;
const step = Math.floor(((doneBytes / totalBytes) * 100) / stepPercent);
const stepOk = step > lastStep;
if (terminal || stepOk || elapsedOk) {
await emit(doneBytes, totalBytes);
}
if (terminal) completed = true;
return;
}
// Unknown total: no step boundaries, throttle purely on elapsed time.
if (elapsedOk) {
await emit(doneBytes, totalBytes);
}
},
async complete(doneBytes, totalBytes) {
if (completed) return;
completed = true;
const total = totalBytes !== undefined ? totalBytes : lastTotalBytes;
const done =
doneBytes !== undefined
? doneBytes
: total != null && total > 0
? total
: lastDoneBytes;
await options.sink(buildLine(done, total));
},
async fail(doneBytes, totalBytes) {
if (completed) return;
completed = true;
const total = totalBytes !== undefined ? totalBytes : lastTotalBytes;
const done = doneBytes !== undefined ? doneBytes : lastDoneBytes;
await options.sink(buildFailLine(done, total));
},
};
}