Files
PaperClipAI/ui/src/components/environment-variables-editor/model.ts
T
Nicky LeachandPaperclip c1c46f1e4e feat: Claude login on the new-agent page before agent creation (#11347)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Claude local adapter supports subscription login through a
sandbox
> - The new-agent page must show login before the user creates an agent
> - Test results must not expose raw sandbox diagnostics or secret
values
> - This pull request adds the login UI to both Test lanes and closes
the diagnostic boundary
> - The branch also adds durable cleanup recovery for failed sandbox
teardown
> - Reusable sandboxes must retain both their recorded teardown
configuration and a valid lifecycle path until destruction succeeds
> - The benefit is a usable login flow with fixed public checks,
redacted server logs, and recoverable sandbox cleanup

## Linked Issues or Issue Description

Related public work:
[#9488](https://github.com/paperclipai/paperclip/pull/9488) adds
first-class recognition for `CLAUDE_CODE_OAUTH_TOKEN` in headless and
remote runs. Related public issue:
[#2681](https://github.com/paperclipai/paperclip/issues/2681) requests
Claude Code subscription support. This pull request adds the login
transport and new-agent UI flow that those changes do not provide.

**Subsystem affected:** Claude local adapter, server login probes,
sandbox provider setup, cleanup recovery, and the new-agent UI.

**Problem or motivation:** The Test lanes did not show the sandbox login
panel in all supported cases. Test results also exposed raw probe
diagnostics, and JSON escapes could end secret redaction early.

**Proposed solution:** Surface the login capability through the bundled
provider manifest. Prepare the same probe runtime in the ACP lane. Send
diagnostics only to redacted server logs. Keep Test checks on fixed
public messages. Normalize login URL hints to allowlisted HTTPS Claude
and Anthropic hosts. Consume JSON escapes during redaction. Preserve
failed sandbox cleanup state across retries and restarts, and prevent
deletion from severing the lifecycle context of a live reusable sandbox.

**Alternatives considered:** Keep raw diagnostics in Test checks or
trust login URL text from the sandbox. Both choices increase information
exposure. Keep separate probe behavior in the ACP lane. That choice
would leave the two Test lanes inconsistent.

## What Changed

- Surface the sandbox login panel on both Test lanes.
- Reconcile the bundled Daytona plugin manifest so
`supportsSetupTokenLogin` reaches the UI capability gate.
- Prepare the ACP Test lane with the same probe runtime as the CLI Test
lane.
- Add the `claude_acp_login_probe_unavailable` warning when the ACP
probe cannot run.
- Send raw sandbox diagnostics only to redacted server logs.
- Keep Test checks on fixed public messages in the ACP, managed-config,
and CLI paths.
- Normalize login URL hints to allowlisted HTTPS Claude and Anthropic
hosts.
- Redact JSON and escaped-JSON secret values, including escaped quotes
and backslashes.
- Preserve orphan cleanup records across provider failures, restarts,
and unavailable plugins.
- Atomically block environment deletion while a live reusable sandbox
lease still depends on it.
- Verify pending cleanup destroys plugin sandboxes with the provider
configuration recorded on the lease, even after the current environment
configuration changes.

## Verification

- Head under review: `506b7fa2d83c36bfa5fd722ee9d95b0c7431c241`.
- Focused environment route/service/runtime coverage passes: 196 tests
across 3 files.
- `pnpm -r typecheck` passes.
- `pnpm build` passes.
- The full Vitest run completed with 4,754 passing and 28 failing tests.
All 23 source-test failures reproduce unchanged on parent head
`58cfe61a33191ce03d965d65085d26064b4888ba`; the other 5 are duplicate
executions from stale `server/dist` output. The failures are unrelated
macOS path/listener and scheduler-fixture failures, so there is no new
bad commit for bisect to localize.
- All required CI checks pass for the current head, including build,
typecheck/release registry, all server and workspace shards, serialized
server suites, canary, and e2e.
- A fresh Greptile review for `506b7fa2d83c36bfa5fd722ee9d95b0c7431c241`
reports 5/5, “safe to merge,” with no blocking failure remaining.

## Risks

- A probe or redaction change could hide useful server diagnostics.
- An allowlist change could reject a valid Claude login URL.
- Cleanup recovery changes could affect provider teardown ordering.
- An environment with a live reusable sandbox can no longer be deleted
until the owning issue or execution workspace completes teardown.
- The implementation keeps public Test messages fixed and sends detail
to redacted server logs.

## Model Used

OpenAI GPT-5 via Codex — exact model ID: GPT-5; tool use and code
execution enabled; extended reasoning enabled. The implementation author
used AI-assisted development.

## 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 documented the result
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation or confirmed no separate
documentation change is needed
- [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-17 13:42:51 -07:00

307 lines
9.7 KiB
TypeScript

import type { CompanySecret, EnvBinding, SecretVersionSelector, UserSecretDefinition } from "@paperclipai/shared";
export type RowSource = "text" | "secret" | "user_secret";
/** Local, per-row UI state. Only a subset is emitted upward (see {@link valueFromRows}). */
export interface EnvRow {
/** Stable local id — used as React key and to target popovers/undo. */
id: string;
name: string;
source: RowSource;
textValue: string;
secretId: string;
userSecretKey: string;
required: boolean;
version: SecretVersionSelector;
/** Session-local dismissal of the sensitive-value suggestion (§6.6). */
sensitiveDismissed?: boolean;
}
let rowCounter = 0;
export function nextRowId(): string {
rowCounter += 1;
return `env-row-${rowCounter}`;
}
export function emptyRow(source: RowSource = "text"): EnvRow {
return {
id: nextRowId(),
name: "",
source,
textValue: "",
secretId: "",
userSecretKey: "",
required: true,
version: "latest",
};
}
function isSecretRef(binding: unknown): binding is { type: "secret_ref"; secretId?: unknown; version?: unknown } {
return (
typeof binding === "object" &&
binding !== null &&
"type" in binding &&
(binding as { type?: unknown }).type === "secret_ref"
);
}
function isPlainObj(binding: unknown): binding is { type: "plain"; value?: unknown } {
return (
typeof binding === "object" &&
binding !== null &&
"type" in binding &&
(binding as { type?: unknown }).type === "plain"
);
}
function isUserSecretRef(
binding: unknown,
): binding is { type: "user_secret_ref"; key?: unknown; version?: unknown; required?: unknown } {
return (
typeof binding === "object" &&
binding !== null &&
"type" in binding &&
(binding as { type?: unknown }).type === "user_secret_ref"
);
}
/** Build editor rows from the controlled value. No implicit trailing ghost row. */
export function rowsFromValue(value: Record<string, EnvBinding> | null | undefined): EnvRow[] {
if (!value || typeof value !== "object") return [];
return Object.entries(value).map(([name, binding]) => {
if (typeof binding === "string") {
return { ...emptyRow(), name, textValue: binding };
}
if (isSecretRef(binding)) {
const version: SecretVersionSelector = typeof binding.version === "number" ? binding.version : "latest";
return {
...emptyRow(),
name,
source: "secret" as const,
secretId: typeof binding.secretId === "string" ? binding.secretId : "",
version,
};
}
if (isUserSecretRef(binding)) {
const version: SecretVersionSelector = typeof binding.version === "number" ? binding.version : "latest";
return {
...emptyRow(),
name,
source: "user_secret" as const,
userSecretKey: typeof binding.key === "string" ? binding.key : "",
required: binding.required !== false,
version,
};
}
if (isPlainObj(binding)) {
return {
...emptyRow(),
name,
source: "text" as const,
textValue: typeof binding.value === "string" ? binding.value : "",
};
}
return { ...emptyRow(), name };
});
}
/**
* Emit semantics (plan §4/§6.1): rows with empty (trimmed) names are dropped;
* secret rows without a chosen secret are incomplete and dropped; an empty
* result emits `undefined`. Duplicate names are last-writer-wins (unchanged).
*/
export function valueFromRows(rows: EnvRow[]): Record<string, EnvBinding> | undefined {
const record: Record<string, EnvBinding> = {};
for (const row of rows) {
const name = row.name.trim();
if (!name) continue;
if (row.source === "secret") {
if (!row.secretId) continue; // incomplete ref — not emitted
record[name] = { type: "secret_ref", secretId: row.secretId, version: row.version };
} else if (row.source === "user_secret") {
const key = row.userSecretKey.trim();
if (!key) continue;
record[name] = {
type: "user_secret_ref",
key,
version: row.version,
required: row.required,
};
} else {
record[name] = { type: "plain", value: row.textValue };
}
}
return Object.keys(record).length > 0 ? record : undefined;
}
// The fixed environment variable name for the Claude subscription OAuth token.
// A subscription login stores the token as a user secret under this key. The
// adapter reads the variable at run start.
export const CLAUDE_OAUTH_TOKEN_ENV_KEY = "CLAUDE_CODE_OAUTH_TOKEN";
/**
* Build the fixed `CLAUDE_CODE_OAUTH_TOKEN` binding. The binding is a
* `user_secret_ref`, so the adapter config holds a reference to the user secret,
* never the token value. This reuses the editor `user_secret_ref` builder in
* {@link valueFromRows}, so the fixed binding keeps the same shape as an
* operator-authored user-secret row.
*/
export function buildFixedClaudeOAuthBinding(): Record<string, EnvBinding> {
return (
valueFromRows([
{
...emptyRow("user_secret"),
name: CLAUDE_OAUTH_TOKEN_ENV_KEY,
userSecretKey: CLAUDE_OAUTH_TOKEN_ENV_KEY,
required: true,
version: "latest",
},
]) ?? {}
);
}
export const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
export type NameIssueLevel = "error" | "warn";
export interface NameIssue {
level: NameIssueLevel;
message: string;
}
/**
* Validate a single row's name given the full set of names (for duplicate
* detection). Returns null when the name is empty (not yet an error) or valid.
*/
export function validateName(
name: string,
duplicateNames: ReadonlySet<string>,
reservedPrefixes: readonly string[],
): NameIssue | null {
const trimmed = name.trim();
if (!trimmed) return null;
if (!ENV_NAME_RE.test(trimmed)) {
return { level: "error", message: "Invalid name — use letters, digits and _" };
}
if (duplicateNames.has(trimmed)) {
return { level: "error", message: "Duplicate name" };
}
for (const prefix of reservedPrefixes) {
if (prefix && trimmed.startsWith(prefix)) {
return { level: "warn", message: "Reserved prefix — provided automatically and may be overridden" };
}
}
return null;
}
/** Names that appear on more than one row (trimmed, non-empty). */
export function computeDuplicateNames(rows: EnvRow[]): Set<string> {
const counts = new Map<string, number>();
for (const row of rows) {
const name = row.name.trim();
if (!name) continue;
counts.set(name, (counts.get(name) ?? 0) + 1);
}
const dupes = new Set<string>();
for (const [name, count] of counts) {
if (count > 1) dupes.add(name);
}
return dupes;
}
/**
* Pure decision for a source switch (§6.3), extracted so the value-preserving
* behaviour is unit-testable without driving the Radix menu.
*/
export type SourceSwitchPlan =
| { kind: "noop" }
/** Text → Secret with a non-empty value: never discard it — open Store-as-secret. */
| { kind: "open-store"; name: string; value: string }
/** Text → Secret with an empty value: switch and open the picker. */
| { kind: "to-secret" }
/** Secret → Text: clear the ref; offer undo when a secret was bound. */
| { kind: "to-text"; undoFrom: EnvRow | null };
export function planSourceSwitch(row: EnvRow, next: RowSource): SourceSwitchPlan {
if (next === row.source) return { kind: "noop" };
if (next === "secret") {
if (row.textValue.trim()) {
return { kind: "open-store", name: secretNameFromKey(row.name) || "secret", value: row.textValue };
}
return { kind: "to-secret" };
}
return { kind: "to-text", undoFrom: row.secretId ? { ...row } : null };
}
export interface SecretHealth {
level: "error" | "warn";
message: string;
/** Short label for the summary line at the top of the editor. */
kind: "missing" | "disabled";
}
/** Per-row secret-binding health (plan §6.8). Null when healthy or not a bound ref. */
export function computeRowHealth(row: EnvRow, secrets: readonly CompanySecret[]): SecretHealth | null {
if (row.source !== "secret" || !row.secretId) return null;
const secret = secrets.find((candidate) => candidate.id === row.secretId);
if (!secret) {
return {
level: "error",
kind: "missing",
message: "This secret no longer exists — runs will fail until you rebind.",
};
}
if (secret.status !== "active") {
return {
level: "warn",
kind: "disabled",
message: "Runs will fail until re-enabled or rebound.",
};
}
return null;
}
/** Per-row user-secret health. Null when healthy or not a bound user-secret ref. */
export function computeUserSecretRowHealth(
row: EnvRow,
definitions: readonly UserSecretDefinition[] | undefined,
): SecretHealth | null {
if (row.source !== "user_secret" || !row.userSecretKey || !definitions?.length) return null;
const definition = definitions.find((candidate) => candidate.key === row.userSecretKey);
if (!definition) {
return {
level: "error",
kind: "missing",
message: "This user secret definition no longer exists — runs will fail until you rebind.",
};
}
if (definition.status !== "active") {
return {
level: "warn",
kind: "disabled",
message: "Runs will fail until this user secret definition is re-enabled or rebound.",
};
}
return null;
}
/** Suggest a `lower_snake` secret name from an env KEY (plan §6.5). */
export function secretNameFromKey(key: string): string {
return key
.trim()
.toLowerCase()
.replace(/[^a-z0-9_]+/g, "_")
.replace(/^_+|_+$/g, "")
.slice(0, 64);
}
/** Suggest an env KEY (UPPER_SNAKE) from a secret name (for quick-bind). */
export function envKeyFromSecretName(name: string): string {
return name
.trim()
.toUpperCase()
.replace(/[^A-Z0-9_]+/g, "_")
.replace(/^_+|_+$/g, "")
.slice(0, 64);
}