Files
PaperClipAI/packages/adapter-utils/src/runtime-progress.ts
T
Devin FoleyandPaperclip 088f85c5fe fix: rename the managed environment to Paperclip Sandbox (#19296)
## Thinking Path

> - Paperclip manages AI agents and their execution environments.
> - Managed installations supply a default sandbox through managed
configuration.
> - Most selectors show the configured environment name.
> - A fallback label, two errors, and examples still use Paperclip
Computer.
> - This pull request changes that stock copy to Paperclip Sandbox.
> - Existing and custom environment names continue to come from the
stored row.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The managed environment label in agent settings and the errors shown
when the managed sandbox is unavailable.

**Subsystem affected**

The agent configuration UI, runner selection, and environment
reconciliation tests.

**Current behavior**

Fallback copy and current examples call the managed sandbox Paperclip
Computer. The actual environment name is already configurable.

**Proposed behavior**

Use Paperclip Sandbox for stock copy and current examples. Keep
configured names unchanged in selectors, including legacy names and
custom names.

**Reason and benefit**

The name identifies this environment as a managed sandbox and removes
ambiguity.

**Breaking changes**

The displayed fallback and error text change. Error codes, execution
behavior, and environment identity remain the same. No migration is
needed.

**Additional context**

No duplicate rename issue or pull request was found. This is a copy
update, with no new roadmap feature.

## What Changed

- Update the managed fallback label and two unavailable-sandbox error
messages.
- Update current test and Storybook fixtures without changing story IDs
or behavior.
- Test configured names, fallback copy, and the unavailable-sandbox
message.
- Add a PostgreSQL regression test for a rename that retains the
environment ID, instance default, agent binding, environment variables,
and lease.

## Verification

- `pnpm -r typecheck` passed.
- `pnpm build` passed.
- Focused coverage: 956 cases across nine changed suites. The new
fixture initially tried to insert an existing singleton; its corrected
upsert passed with all 52 environment-service cases. The updated runner
suite also passed all 243 cases.
- The two UI suites passed all 189 cases, including configured
legacy/custom names and the missing-default fallback.
- `pnpm check:token-gates` passed.
- `node scripts/storybook-catalog.mjs --check` passed. The catalog is
structural evidence only.
- `node --test scripts/check-maps.test.mjs
scripts/storybook-catalog.test.mjs
scripts/storybook-feature-index.test.mjs` passed.
- Full `pnpm test:run` is in progress. No live provider or browser
journey is claimed by these tests.
- CI passed on the current head after one server-shard rerun. The first
attempt hit a 10 ms deadline assertion in the unchanged status-card
timing test; its isolated local run and the complete rerun shard passed.
The original failure and rerun are retained in the PR comment.
- Reviewed the diff for secrets, personal data, and run artifacts.

## Risks

Low risk: runtime edits change three display strings. Managed
reconciliation is unchanged. The regression test exercises the existing
rename against PostgreSQL. The configured name still controls normal
display, so this code change alone does not rename existing database
rows. A managed configuration update uses the existing reconciliation
path. Roll back the copy by reverting this commit.

## Model Used

OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through Codex in T3 Code, xhigh
reasoning, with repository tools 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, version, and capabilities
- [x] I have checked ROADMAP.md; this copy update does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs
- [x] I have described the issue in the PR with the enhancement template
fields
- [x] No internal or instance-local issue references
- [x] The branch name describes the change and contains no internal
ticket ID
- [x] Focused tests pass locally
- [x] Relevant tests were added or updated
- [x] Relevant copy and examples were updated; no API or schema
documentation changed
- [x] Risks are documented
- [x] All CI gates passed on the current head, including the server
11/12 rerun and aggregate verify
- [ ] Full local test suite completed (still running; six chat shards
passed)
- [x] Greptile is 5/5 on the current head with no unresolved findings
- [x] I will address all reviewer comments before requesting merge

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-05 10:23:43 -08: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 Sandbox" 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));
},
};
}