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>
This commit is contained in:
Nicky LeachandPaperclip authored and GitHub committed 2026-08-17 13:42:51 -07:00
1 parent 3061ce6901
commit c1c46f1e4e
101 files changed
+99708 -1031

No files matched your search

+9
View File
@@ -84,6 +84,15 @@ export const createAgentSchema = z.object({
budgetMonthlyCents: z.number().int().nonnegative().optional().default(0),
permissions: agentPermissionsSchema.optional(),
metadata: z.record(z.string(), z.unknown()).optional().nullable(),
// The optional stored-session claim from a completed Claude login session. It
// is the non-secret `storedSessionId`; it carries no token. The agent-create
// transaction consumes it as the one-time stored-session claim.
storedSessionId: z.string().min(1).max(256).optional(),
// The optional apply-existing flag. When true, the caller binds the fixed
// Claude OAuth token reference to the owner stored value with no new login
// round trip. The server permits the no-claim bind only for a user actor and
// only when that owner already has a stored value. It carries no token.
applyStoredClaudeLogin: z.boolean().optional(),
});
export type CreateAgent = z.infer<typeof createAgentSchema>;
@@ -0,0 +1,141 @@
import { describe, expect, it } from "vitest";
import {
BROWSER_CODE_MAX_LENGTH,
browserCodeSchema,
claudeSetupTokenCompletionResponseSchema,
claudeSetupTokenSessionOwnerResponseSchema,
isValidBrowserCode,
startClaudeSetupTokenSessionRequestSchema,
submitBrowserCodeRequestSchema,
} from "./claude-setup-token-session.js";
import { createAgentSchema, createAgentHireSchema } from "./agent.js";
const ENVIRONMENT_ID = "11111111-1111-4111-8111-111111111111";
describe("claude setup-token session start request", () => {
it("accepts a company-and-environment request with no agent id", () => {
const parsed = startClaudeSetupTokenSessionRequestSchema.parse({
environmentId: ENVIRONMENT_ID,
adapterType: "claude_local",
});
expect(parsed.environmentId).toBe(ENVIRONMENT_ID);
expect(parsed.adapterType).toBe("claude_local");
});
it("rejects a legacy ttlSeconds: the runtime does not support it", () => {
const result = startClaudeSetupTokenSessionRequestSchema.safeParse({
environmentId: ENVIRONMENT_ID,
adapterType: "claude_local",
ttlSeconds: 300,
});
expect(result.success).toBe(false);
});
it("rejects an agent id: the scope carries no agent id", () => {
const result = startClaudeSetupTokenSessionRequestSchema.safeParse({
environmentId: ENVIRONMENT_ID,
adapterType: "claude_local",
agentId: "22222222-2222-4222-8222-222222222222",
});
expect(result.success).toBe(false);
});
});
describe("browser-code grammar", () => {
it("accepts a conservative printable code", () => {
const code = "ac_012-AZ_az.9#state";
expect(browserCodeSchema.parse(code)).toBe(code);
expect(isValidBrowserCode(code)).toBe(true);
});
it("rejects a carriage return, a line feed, a NUL, and a control byte", () => {
for (const bad of ["ab\rcd", "ab\ncd", "ab\u0000cd", "ab\u0001cd", "ab\u007fcd", "ab cd", "ab\tcd"]) {
expect(browserCodeSchema.safeParse(bad).success).toBe(false);
expect(isValidBrowserCode(bad)).toBe(false);
}
});
it("rejects a trailing newline that an anchored regex would let pass", () => {
// The runtime `.refine()` is the authoritative guard. JavaScript `$`
// matches before a final line feed, so an anchored printable-ASCII regex
// accepts a trailing newline. The `.refine()` closes that trap.
expect(browserCodeSchema.safeParse("abc\n").success).toBe(false);
expect(isValidBrowserCode("abc\n")).toBe(false);
});
it("rejects a single control byte and accepts a printable code", () => {
expect(browserCodeSchema.safeParse("abc").success).toBe(true);
expect(browserCodeSchema.safeParse("valid-code_123").success).toBe(true);
});
it("rejects an empty code", () => {
expect(browserCodeSchema.safeParse("").success).toBe(false);
expect(isValidBrowserCode("")).toBe(false);
});
it("rejects an oversized code", () => {
const oversized = "a".repeat(BROWSER_CODE_MAX_LENGTH + 1);
expect(browserCodeSchema.safeParse(oversized).success).toBe(false);
expect(isValidBrowserCode(oversized)).toBe(false);
const atLimit = "a".repeat(BROWSER_CODE_MAX_LENGTH);
expect(browserCodeSchema.parse(atLimit)).toBe(atLimit);
});
it("wraps the grammar in the submit-browser-code request and rejects an extra field", () => {
expect(submitBrowserCodeRequestSchema.parse({ browserCode: "abc123" }).browserCode).toBe(
"abc123",
);
expect(submitBrowserCodeRequestSchema.safeParse({ browserCode: "a\nb" }).success).toBe(false);
expect(
submitBrowserCodeRequestSchema.safeParse({ browserCode: "abc", extra: 1 }).success,
).toBe(false);
});
});
describe("claude setup-token owner response and completion response", () => {
it("accepts an owner response with the submitted-browser-code panel mode and a prompt", () => {
const parsed = claudeSetupTokenSessionOwnerResponseSchema.parse({
sessionId: "opaque-base64url-session-id",
environmentId: ENVIRONMENT_ID,
status: "waiting_for_user",
expiresAt: null,
failure: null,
panelMode: "submitted_browser_code",
prompt: { authorizationUrl: "https://example.test/authorize" },
});
expect(parsed.panelMode).toBe("submitted_browser_code");
expect(parsed.prompt?.authorizationUrl).toBe("https://example.test/authorize");
});
it("rejects a token on the completion response: the claim carries no token", () => {
expect(
claudeSetupTokenCompletionResponseSchema.parse({ storedSessionId: "session-claim" })
.storedSessionId,
).toBe("session-claim");
const withToken = claudeSetupTokenCompletionResponseSchema.safeParse({
storedSessionId: "session-claim",
token: "secret",
});
expect(withToken.success).toBe(false);
});
});
describe("agent create and hire carry an optional stored-session claim", () => {
const base = { name: "Claude Agent", adapterType: "claude_local" as const };
it("accepts a create request without a stored-session claim", () => {
expect(createAgentSchema.parse({ ...base }).storedSessionId).toBeUndefined();
});
it("accepts a create request with a stored-session claim", () => {
expect(
createAgentSchema.parse({ ...base, storedSessionId: "session-claim" }).storedSessionId,
).toBe("session-claim");
});
it("accepts a hire request with a stored-session claim", () => {
expect(
createAgentHireSchema.parse({ ...base, storedSessionId: "session-claim" }).storedSessionId,
).toBe("session-claim");
});
});
@@ -0,0 +1,170 @@
import { z } from "zod";
import { AGENT_ADAPTER_TYPES } from "../constants.js";
import { ADAPTER_AUTH_PANEL_MODES, SETUP_TOKEN_TRANSPORT_ADVISORY_CODE } from "../types/agent.js";
import {
adapterAuthSessionFailureSchema,
adapterAuthSessionStatusSchema,
} from "./adapter-auth-session.js";
const isoDateTime = z.union([z.date(), z.string().datetime()]);
// The transport advisory schema. A guarded confidential response carries it when
// the login rides a non-confidential transport. The client shows a disclaimer.
export const setupTokenTransportAdvisorySchema = z.object({
code: z.literal(SETUP_TOKEN_TRANSPORT_ADVISORY_CODE),
}).strict();
export type SetupTokenTransportAdvisory = z.infer<typeof setupTokenTransportAdvisorySchema>;
// The confirmed-overwrite capture for a replacement login. The client reads the
// stored value metadata from the status route and passes it back when it starts
// a replacement login. The server maps it to the owner-bound compare-and-set: it
// rotates the value only when the captured version still matches. The server
// still derives the owner and the definition; this body carries no owner. A
// missing capture starts a first-write login instead.
export const claudeSetupTokenOverwriteSchema = z.object({
expectedSecretId: z.string().uuid(),
expectedLatestVersion: z.number().int().min(1),
}).strict();
export type ClaudeSetupTokenOverwrite =
z.infer<typeof claudeSetupTokenOverwriteSchema>;
// The start request for a company-and-environment Claude login session. The
// company and the owner user come from the authenticated caller, not from this
// body. The body names the adapter and the environment of the login. It reuses
// the adapter login-session request fields; every field has the same meaning.
//
// The optional `overwrite` capture turns the login into a confirmed replacement.
// The client sends it only after a stored token fails the agent test. The server
// rotates the stored value under the captured version, so a concurrent change
// fails closed with a stale conflict.
//
// `.strict()` rejects an extra field, so an agent id never validates. The scope
// carries no agent id: a hire flow with no agent still starts one session. The
// runtime does not support a caller-supplied session length, so the schema
// exposes no `ttlSeconds` field; a legacy `ttlSeconds` fails the strict parse.
export const startClaudeSetupTokenSessionRequestSchema = z.object({
environmentId: z.string().uuid(),
adapterType: z.enum(AGENT_ADAPTER_TYPES),
overwrite: claudeSetupTokenOverwriteSchema.optional(),
}).strict();
export type StartClaudeSetupTokenSessionRequest =
z.infer<typeof startClaudeSetupTokenSessionRequestSchema>;
// The panel-mode schema. It accepts only the two known panel modes.
export const adapterAuthPanelModeSchema = z.enum(ADAPTER_AUTH_PANEL_MODES);
export type AdapterAuthPanelMode = z.infer<typeof adapterAuthPanelModeSchema>;
// The session id is an opaque, cryptographically random string, not a UUID. So
// the schema accepts a bounded opaque string, not a UUID.
const sessionIdSchema = z.string().min(1).max(256);
// The public Claude login-session response schema. `.strict()` rejects an extra
// field, so a prompt, a token, an account identifier, or a provider lease
// identifier never validates.
export const claudeSetupTokenSessionResponseSchema = z.object({
sessionId: sessionIdSchema,
environmentId: z.string().uuid(),
status: adapterAuthSessionStatusSchema,
expiresAt: isoDateTime.nullable(),
failure: adapterAuthSessionFailureSchema.nullable(),
transportAdvisory: setupTokenTransportAdvisorySchema.nullable().optional(),
}).strict();
export type ClaudeSetupTokenSessionResponse =
z.infer<typeof claudeSetupTokenSessionResponseSchema>;
// The one-time Claude login prompt schema. It carries the authorization URL the
// user opens. It carries no server-displayed code.
export const claudeSetupTokenSessionPromptSchema = z.object({
authorizationUrl: z.string().min(1),
transportAdvisory: setupTokenTransportAdvisorySchema.nullable().optional(),
}).strict();
export type ClaudeSetupTokenSessionPrompt =
z.infer<typeof claudeSetupTokenSessionPromptSchema>;
// The owner read schema. It adds the panel mode and the one-time prompt to the
// public response.
export const claudeSetupTokenSessionOwnerResponseSchema =
claudeSetupTokenSessionResponseSchema.extend({
panelMode: adapterAuthPanelModeSchema,
prompt: claudeSetupTokenSessionPromptSchema.nullable(),
}).strict();
export type ClaudeSetupTokenSessionOwnerResponse =
z.infer<typeof claudeSetupTokenSessionOwnerResponseSchema>;
// The bounded maximum length of a browser code. The provider code is short. The
// server rejects an oversized code before it reaches the live login process.
export const BROWSER_CODE_MAX_LENGTH = 512;
// The conservative printable grammar for the submitted browser code. It matches
// one character outside the visible ASCII range (0x21-0x7E). The validator
// rejects a code that contains a match, so it rejects a space, a carriage
// return, a line feed, a NUL, and every other control byte. A later
// characterization test narrows this set to the exact provider format.
export const BROWSER_CODE_DISALLOWED_CHAR = /[^\x21-\x7E]/;
/**
* Returns true when the browser code obeys the grammar. The code has one or more
* characters, no character outside the visible ASCII range, and a length at or
* below the bounded maximum.
*/
export function isValidBrowserCode(code: string): boolean {
return (
code.length >= 1 &&
code.length <= BROWSER_CODE_MAX_LENGTH &&
!BROWSER_CODE_DISALLOWED_CHAR.test(code)
);
}
// The printable-ASCII allowlist pattern for the published contract. It is an
// anchored allowlist of the visible ASCII range (0x21-0x7E). The converter reads
// this `.regex()` from the inner `ZodString` and emits it as the OpenAPI
// `pattern`. It is NOT the authoritative guard: JavaScript `$` matches before a
// final line feed, so this pattern accepts a trailing newline. The `.refine()`
// below is the authoritative guard that rejects a trailing newline.
export const BROWSER_CODE_PATTERN = /^[\x21-\x7E]+$/u;
// The browser-code grammar schema. It rejects an empty code, an oversized code,
// and a code with a control byte or any other non-printable character. The
// `.regex()` runs before the `.refine()` so the converter serializes its
// `pattern`; the `.refine()` stays the authoritative guard.
export const browserCodeSchema = z
.string()
.min(1, "A browser code is required.")
.max(BROWSER_CODE_MAX_LENGTH, "The browser code is too long.")
.regex(BROWSER_CODE_PATTERN, "The browser code has an invalid character.")
.refine((code) => !BROWSER_CODE_DISALLOWED_CHAR.test(code), {
message: "The browser code has an invalid character.",
});
export type BrowserCode = z.infer<typeof browserCodeSchema>;
// The submit-browser-code request schema. `.strict()` rejects an extra field.
export const submitBrowserCodeRequestSchema = z.object({
browserCode: browserCodeSchema,
}).strict();
export type SubmitBrowserCodeRequest =
z.infer<typeof submitBrowserCodeRequestSchema>;
// The stored-session claim schema. The `storedSessionId` is the opaque durable
// session id. It is a non-secret claim; it carries no token.
export const storedSessionIdSchema = z.string().min(1).max(256);
// The completion response schema. It carries the non-secret `storedSessionId`
// claim and no token. `.strict()` rejects an extra field, so a token never
// validates.
export const claudeSetupTokenCompletionResponseSchema = z.object({
storedSessionId: storedSessionIdSchema,
}).strict();
export type ClaudeSetupTokenCompletionResponse =
z.infer<typeof claudeSetupTokenCompletionResponseSchema>;
// The stored Claude OAuth token status response schema. It carries only the
// secret id and the latest version of the owner value; it carries no token.
// `.strict()` rejects an extra field, so a token never validates. The status
// route returns a fixed 404 for a missing or a foreign value, so a 200 body
// always describes a present owner value.
export const claudeOAuthTokenStatusResponseSchema = z.object({
secretId: z.string().uuid(),
latestVersion: z.number().int().min(1),
}).strict();
export type ClaudeOAuthTokenStatusResponse =
z.infer<typeof claudeOAuthTokenStatusResponseSchema>;
+1
View File
@@ -187,6 +187,7 @@ export const pluginEnvironmentDriverDeclarationSchema = z.object({
templateConfigBinding: pluginEnvironmentTemplateConfigBindingSchema.optional(),
templateIdentityPaths: z.array(z.string().min(1).max(200)).max(20).optional(),
supportsTemplateDelete: z.boolean().optional(),
supportsSetupTokenLogin: z.boolean().optional(),
configSchema: jsonSchemaSchema,
});