feat(workspaces): sign the workspace login handoff and gate readiness (#11671)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Managed worktree services run isolated Paperclip instances with
cloned databases.
> - A reachable service was reported as ready even when its database,
runtime identity, or login path was not usable.
> - The first candidate added verified database seeding and managed
repair in #11665.
> - This pull request consolidates that candidate with signed login
handoff and a complete readiness contract.
> - Post-QA fixes close five defects in repair identity, repair
responses, UI retry, seed journal handling, and seed-source trust.
> - The benefit is a workspace that either opens safely or reports one
accurate recovery action.

## Linked Issues or Issue Description

No public GitHub issue exists for this work, so the problem is described
here.

**What happened**

Managed workspace URLs could return HTTP 200 and report ready while
login failed. QA also found cases where repair used the wrong instance
identity, returned a generic error, left the UI stuck, rejected a safe
journal lag, or trusted a mutable workspace manifest.

**Expected behavior**

Opening a ready workspace signs the board user in to the correct
isolated instance. Provisioning and repair use a registered source and
report a structured recovery state.

**Actual behavior**

Entry depended on a password copied into the clone. Several failure
paths could publish stale readiness, hide the repair precondition, or
trust state that the workspace could modify.

**Additional context**

This pull request includes the commits first published in #11665. That
pull request keeps the original base head for review history. This
consolidated pull request is the merge candidate. Related open readiness
work includes #11575 and #11621.

## What Changed

- Adds a short-lived, signed, single-use login ticket. It binds the
user, workspace, instance, and runtime origin.
- Exchanges the ticket through Better Auth. It creates the session and
cookie through the supported adapter path.
- Adds protected workspace readiness fields for the database, clone
data, login handoff, seed phase, and runtime identity.
- Fails readiness closed when the guest has no company or
execution-workspace binding.
- Binds ticket issuance to the exact cloned user and active company
membership selected for the handoff.
- Verifies every current active board identity through the exact-user
handoff before publication or reuse.
- Gates managed runtime publication on the readiness contract and the
recorded worktree instance identity.
- Refreshes runtime work products from the live runtime row after a port
change.
- Adds one workspace access card with ready, degraded, repairing, and
failed states.
- Uses the runtime response identity for repair. It returns structured
repair precondition errors.
- Lets a valid source journal lag converge during provisioning.
- Binds seed and repair manifests to a source registered outside the
agent-writable worktree.
- Clears recovered UI errors so a successful retry can open the
workspace.
- Makes runtime tests register canonical sources and avoid ports owned
by live host listeners.
- Keeps Vitest on source suites when compiled `dist` trees exist.
- Isolates CLI and adapter tests from ambient AWS and runtime API
environment variables.
- Preserves a 404 response for cross-company workspace ID lookups before
runtime authorization.
- Makes concurrent single-flight coverage independent of
path-canonicalization scheduling order.

## Verification

The following checks passed on the integrated head:

```sh
pnpm -r typecheck
pnpm build
pnpm check:token-gates
pnpm --filter @paperclipai/db check:migrations
```

- The server source lane passed 420 files and 4,953 tests. Five tests
were skipped.
- The CLI lane passed 57 files and 385 tests.
- The database lane passed 26 files and 97 tests.
- The shared package passed 58 files and 506 tests.
- The adapter utility lane passed 640 tests. Four tests were skipped.
- The Claude adapter passed 220 tests. One test was skipped.
- The Codex adapter passed 323 tests.
- The OpenClaw adapter passed 13 tests.
- The OpenCode adapter passed 42 tests.
- The plugin SDK passed 45 tests.
- The workspace runtime suite passed 124 tests.
- The caller-scoped readiness and handoff suite passed 52 tests.
- The workspace provisioning shell suite passed 7 tests.
- The runtime exposure suite passed 17 tests while live host mappings
occupied fixed test ports.
- `git diff --check` passed and the worktree is clean.

The serialized route lane will run in GitHub CI with its normal shards.
No deployment or active-workspace migration was performed.

## Risks

- This is a medium-risk authentication and runtime-readiness change.
- The login ticket uses exact origin, workspace, instance, and user
binding. It has a short expiry and a one-time nonce.
- Runtime publication is stricter. A real readiness, identity, per-user
handoff, or control-plane database disagreement now blocks publication.
- This pull request supersedes #11665 as the merge candidate. Close
#11665 after this pull request merges.
- No new database migration is included. The lockfile and workflow files
are unchanged.
- Deployment and active-workspace migration are intentionally outside
this pull request.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

Claude Opus 5 (`claude-opus-5[1m]`), 1M context, extended thinking, tool
use, and code execution produced the main candidate. OpenAI GPT-5
(`gpt-5`) through Codex, with agentic reasoning, tool use, and code
execution, integrated the post-QA fixes and hardened the test gates. The
Codex context-window size was not exposed.

## 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-08-19 02:37:02 -05:00
1 parent 6aaef2998f
commit a2bf936f9a
59 files changed
+7754 -243

No files matched your search

+18
View File
@@ -4,6 +4,7 @@ import type {
ExecutionWorkspaceStatus,
ExecutionWorkspaceCloseReadiness,
WorkspaceOverviewResponse,
WorkspaceLoginHandoffTicketResponse,
WorkspaceOperation,
WorkspaceRuntimeControlTarget,
} from "@paperclipai/shared";
@@ -114,6 +115,23 @@ export const executionWorkspacesApi = {
`/execution-workspaces/${id}/runtime-commands/${action}`,
sanitizeWorkspaceRuntimeControlTarget(target),
),
repair: (id: string) =>
api.post<{ workspace: ExecutionWorkspace; operation: WorkspaceOperation }>(
`/execution-workspaces/${id}/runtime-commands/repair`,
{},
),
/**
* Mint a single-use workspace login handoff (PAP-17572).
*
* The returned URL carries a short-lived ticket, so the caller must navigate to
* it rather than store or share it. The server answers the navigation with an
* HTTP redirect, which is what keeps the ticket out of browser history.
*/
requestLoginHandoff: (id: string, next?: string) =>
api.post<WorkspaceLoginHandoffTicketResponse>(
`/execution-workspaces/${id}/login-handoff`,
next ? { next } : {},
),
update: (id: string, data: Record<string, unknown>) => api.patch<ExecutionWorkspace>(`/execution-workspaces/${id}`, data),
/**
* Reconcile a git-worktree branch divergence via the S4 (`PAP-1586`) op.
@@ -0,0 +1,194 @@
// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { WorkspaceAccessCard } from "./WorkspaceAccessCard";
import type { WorkspaceAccessState } from "../lib/workspace-access-state";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
function act(callback: () => void) {
flushSync(callback);
}
function accessState(overrides: Partial<WorkspaceAccessState> = {}): WorkspaceAccessState {
return {
state: "ready",
title: "Ready",
description: "Opening the workspace signs you in to the cloned board without a password.",
action: { kind: "open", label: "Open workspace" },
handoffAvailable: true,
...overrides,
};
}
describe("WorkspaceAccessCard", () => {
let container: HTMLDivElement;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
document.body.innerHTML = "";
});
function renderCard(props: Partial<Parameters<typeof WorkspaceAccessCard>[0]> = {}) {
const handlers = {
onOpen: vi.fn(),
onStart: vi.fn(),
onRepair: vi.fn(),
onViewLogs: vi.fn(),
};
const root = createRoot(container);
act(() => {
root.render(<WorkspaceAccessCard access={accessState()} {...handlers} {...props} />);
});
const button = container.querySelector("button");
return { ...handlers, root, button };
}
function findButton(label: string) {
return Array.from(container.querySelectorAll("button")).find(
(candidate) => candidate.textContent?.trim() === label,
);
}
it("renders the ready state and opens without asking for a password", () => {
const { onOpen, root } = renderCard();
const card = container.querySelector("[data-testid='workspace-access-card']");
expect(card?.getAttribute("data-state")).toBe("ready");
expect(container.textContent).toContain("Ready");
expect(container.textContent).toContain("single-use login handoff");
const button = findButton("Open workspace");
expect(button).toBeDefined();
act(() => button!.click());
expect(onOpen).toHaveBeenCalledTimes(1);
act(() => root.unmount());
});
it("keeps a superseded repair failure visible without hiding the open action", () => {
const { onOpen, onViewLogs, root } = renderCard({
access: accessState({
secondaryNotice: {
title: "Repair failed",
description: "The repair stopped during managed_restart. The pre-repair backup was kept.",
action: { kind: "view_logs", label: "View repair log" },
},
}),
});
const openButton = findButton("Open workspace");
const logButton = findButton("View repair log");
expect(openButton).toBeDefined();
expect(logButton).toBeDefined();
expect(container.querySelector("[data-testid='workspace-access-secondary-notice']")?.textContent)
.toContain("pre-repair backup was kept");
act(() => openButton!.click());
act(() => logButton!.click());
expect(onOpen).toHaveBeenCalledTimes(1);
expect(onViewLogs).toHaveBeenCalledTimes(1);
act(() => root.unmount());
});
it("labels the credential fallback accurately when no handoff is available", () => {
const { root } = renderCard({
access: accessState({
handoffAvailable: false,
description: "Opening the board will ask for the credentials captured in this snapshot.",
}),
});
expect(container.textContent).toContain("snapshot-local credentials captured");
expect(container.textContent).not.toContain("single-use login handoff");
act(() => root.unmount());
});
it("gives provisioning, degraded, and failed states their own safe action", () => {
const cases = [
{
access: accessState({
state: "provisioning" as const,
title: "Provisioning database",
action: { kind: "start" as const, label: "Start workspace" },
}),
label: "Start workspace",
handlerKey: "onStart" as const,
},
{
access: accessState({
state: "degraded" as const,
title: "Workspace is degraded",
action: { kind: "repair" as const, label: "Repair workspace" },
}),
label: "Repair workspace",
handlerKey: "onRepair" as const,
},
{
access: accessState({
state: "failed" as const,
title: "Repair failed",
action: { kind: "view_logs" as const, label: "View repair log" },
}),
label: "View repair log",
handlerKey: "onViewLogs" as const,
},
];
for (const testCase of cases) {
const rendered = renderCard({ access: testCase.access });
expect(container.textContent).toContain(testCase.access.title);
const button = findButton(testCase.label);
expect(button).toBeDefined();
expect(button!.disabled).toBe(false);
act(() => button!.click());
expect(rendered[testCase.handlerKey]).toHaveBeenCalledTimes(1);
act(() => rendered.root.unmount());
container.innerHTML = "";
}
});
it("offers nothing clickable while a repair is already running", () => {
const { root } = renderCard({
access: accessState({
state: "repairing",
title: "Repairing workspace database",
action: { kind: "wait", label: "Repair in progress" },
}),
});
expect(findButton("Repair in progress")?.disabled).toBe(true);
expect(
container.querySelector("[data-testid='workspace-access-badge']")?.textContent,
).toContain("Repairing");
act(() => root.unmount());
});
it("always names the state and the cause instead of a bare failure", () => {
const { root } = renderCard({
access: accessState({
state: "failed",
title: "Database provisioning failed",
description: "The clone failed during restore. Repairing replaces only the isolated database.",
action: { kind: "repair", label: "Repair workspace" },
}),
errorMessage: "Failed to open the workspace.",
});
expect(container.textContent).toContain("Database provisioning failed");
expect(container.textContent).toContain("failed during restore");
expect(
container.querySelector("[data-testid='workspace-access-error']")?.textContent,
).toContain("Failed to open the workspace.");
act(() => root.unmount());
});
it("disables the action while the caller reports it busy", () => {
const { root } = renderCard({ isBusy: true });
expect(findButton("Open workspace")?.disabled).toBe(true);
act(() => root.unmount());
});
});
+149
View File
@@ -0,0 +1,149 @@
import { ExternalLink, Loader2, Play, ScrollText, Wrench } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { cn } from "../lib/utils";
import type { WorkspaceAccessState } from "../lib/workspace-access-state";
/**
* Workspace access surface (PAP-17572).
*
* One card per workspace that names the state, the cause, and the single safe
* next action. It replaces the previous behavior where a cloned workspace whose
* database was missing still rendered a plain "Open" link and answered with
* "invalid email or password".
*/
/**
* Badge tones come from the semantic status token layer, so a theme change moves
* these states with every other status surface. `ready` reuses the "done" tone
* and `degraded` the "todo" (amber) tone; the icon variants are the contrast-
* corrected pair the token layer already tunes per mode.
*/
const STATE_BADGE_CLASSES: Record<WorkspaceAccessState["state"], string> = {
provisioning: "border-border text-muted-foreground",
validating: "border-border text-muted-foreground",
ready: "border-(--status-task-done) text-(--status-task-icon-done)",
degraded: "border-(--status-task-todo) text-(--status-task-icon-todo)",
repairing: "border-border text-muted-foreground",
failed: "border-destructive/50 text-destructive",
};
const STATE_LABELS: Record<WorkspaceAccessState["state"], string> = {
provisioning: "Provisioning",
validating: "Validating clone",
ready: "Ready",
degraded: "Degraded",
repairing: "Repairing",
failed: "Failed",
};
const ACTION_ICONS = {
open: ExternalLink,
start: Play,
repair: Wrench,
view_logs: ScrollText,
wait: Loader2,
} as const;
export function WorkspaceAccessCard({
access,
isBusy,
onOpen,
onStart,
onRepair,
onViewLogs,
errorMessage,
}: {
access: WorkspaceAccessState;
isBusy?: boolean;
onOpen: () => void;
onStart: () => void;
onRepair: () => void;
onViewLogs: () => void;
errorMessage?: string | null;
}) {
const Icon = ACTION_ICONS[access.action.kind];
const isWaiting = access.action.kind === "wait";
const handlers: Record<WorkspaceAccessState["action"]["kind"], () => void> = {
open: onOpen,
start: onStart,
repair: onRepair,
view_logs: onViewLogs,
wait: () => undefined,
};
const SecondaryNoticeIcon = access.secondaryNotice
? ACTION_ICONS[access.secondaryNotice.action.kind]
: null;
return (
<Card data-testid="workspace-access-card" data-state={access.state}>
<CardHeader>
<div className="flex flex-wrap items-center gap-2">
<CardTitle>{access.title}</CardTitle>
<span
data-testid="workspace-access-badge"
className={cn(
"inline-flex items-center rounded-full border bg-background px-2.5 py-1 text-xs",
STATE_BADGE_CLASSES[access.state],
)}
>
{(access.state === "repairing" || access.state === "provisioning") && (
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
)}
{STATE_LABELS[access.state]}
</span>
</div>
<CardDescription>{access.description}</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant={access.action.kind === "open" ? "default" : "outline"}
disabled={isWaiting || isBusy}
onClick={handlers[access.action.kind]}
>
{isBusy && !isWaiting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Icon className={cn("mr-2 h-4 w-4", isWaiting && "animate-spin")} />
)}
{access.action.label}
</Button>
{access.state === "ready" && !access.handoffAvailable ? (
<span className="text-xs text-muted-foreground">
Signs in with the snapshot-local credentials captured when this clone was made.
</span>
) : null}
{access.state === "ready" && access.handoffAvailable ? (
<span className="text-xs text-muted-foreground">
Uses a single-use login handoff — no password needed.
</span>
) : null}
</div>
{errorMessage ? (
<p data-testid="workspace-access-error" className="text-sm text-destructive">
{errorMessage}
</p>
) : null}
{access.secondaryNotice && SecondaryNoticeIcon ? (
<div data-testid="workspace-access-secondary-notice" className="flex flex-col gap-1.5 text-sm">
<p className="font-medium text-destructive">{access.secondaryNotice.title}</p>
<p className="text-muted-foreground">{access.secondaryNotice.description}</p>
<Button
type="button"
variant="link"
size="sm"
className="h-auto w-fit p-0"
disabled={isBusy}
onClick={handlers[access.secondaryNotice.action.kind]}
>
<SecondaryNoticeIcon className="mr-2 h-4 w-4" />
{access.secondaryNotice.action.label}
</Button>
</div>
) : null}
</CardContent>
</Card>
);
}
+335
View File
@@ -0,0 +1,335 @@
import type { WorkspaceOperation, WorkspaceRuntimeService } from "@paperclipai/shared";
import { describe, expect, it } from "vitest";
import {
describeWorkspaceReadinessCause,
resolveWorkspaceAccessState,
} from "./workspace-access-state";
function runtimeService(overrides: Partial<WorkspaceRuntimeService> = {}): WorkspaceRuntimeService {
return {
id: "runtime-1",
companyId: "company-1",
projectId: "project-1",
projectWorkspaceId: null,
executionWorkspaceId: "ews-1",
issueId: null,
scopeType: "execution_workspace",
scopeId: "ews-1",
serviceName: "paperclip-dev",
status: "running",
lifecycle: "shared",
reuseKey: null,
command: "pnpm dev:once",
cwd: "/srv/worktree",
port: 42013,
url: "https://workspace.example.ts.net:42013/",
provider: "local_process",
providerRef: null,
ownerAgentId: null,
startedByRunId: null,
lastUsedAt: new Date("2026-08-19T00:00:00.000Z"),
startedAt: new Date("2026-08-19T00:00:00.000Z"),
stoppedAt: null,
stopPolicy: null,
healthStatus: "healthy",
createdAt: new Date("2026-08-19T00:00:00.000Z"),
updatedAt: new Date("2026-08-19T00:00:00.000Z"),
...overrides,
};
}
function operation(overrides: Partial<WorkspaceOperation> = {}): WorkspaceOperation {
return {
id: "op-1",
companyId: "company-1",
executionWorkspaceId: "ews-1",
heartbeatRunId: null,
issueId: null,
phase: "workspace_runtime_provision",
command: null,
cwd: null,
status: "succeeded",
exitCode: 0,
logStore: null,
logRef: null,
logBytes: null,
logSha256: null,
logCompressed: false,
stdoutExcerpt: null,
stderrExcerpt: null,
metadata: null,
startedAt: new Date("2026-08-19T00:00:00.000Z"),
finishedAt: new Date("2026-08-19T00:01:00.000Z"),
createdAt: new Date("2026-08-19T00:00:00.000Z"),
updatedAt: new Date("2026-08-19T00:01:00.000Z"),
...overrides,
};
}
describe("resolveWorkspaceAccessState", () => {
it("is ready with a password-independent open action when a healthy runtime publishes a URL", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [runtimeService()],
operations: [operation()],
});
expect(access).toMatchObject({
state: "ready",
action: { kind: "open", label: "Open workspace" },
handoffAvailable: true,
});
expect(access.description).toContain("without a password");
});
it("shows a repair-in-progress state with the current phase and no action", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [runtimeService()],
operations: [
operation({ phase: "workspace_repair", status: "running", metadata: { repairPhase: "full_reseed" } }),
],
});
expect(access.state).toBe("repairing");
expect(access.description).toContain("full_reseed");
expect(access.description).toContain("preserved");
expect(access.action.kind).toBe("wait");
});
it("shows a failed repair with the failing phase and points at the log", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [],
operations: [
operation({ phase: "workspace_repair", status: "failed", metadata: { repairPhase: "readiness_validation" } }),
],
});
expect(access).toMatchObject({ state: "failed", action: { kind: "view_logs" } });
expect(access.title).toBe("Repair failed");
expect(access.description).toContain("readiness_validation");
expect(access.description).toContain("backup");
});
it("returns to ready after a failed repair when a newer healthy runtime is serving", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [runtimeService({ startedAt: new Date("2026-08-19T00:03:00.000Z") })],
operations: [
operation({
phase: "workspace_repair",
status: "failed",
metadata: { repairPhase: "managed_restart" },
finishedAt: new Date("2026-08-19T00:02:00.000Z"),
}),
],
});
expect(access).toMatchObject({
state: "ready",
action: { kind: "open", label: "Open workspace" },
secondaryNotice: {
title: "Repair failed",
action: { kind: "view_logs", label: "View repair log" },
},
});
expect(access.secondaryNotice?.description).toContain("managed_restart");
expect(access.secondaryNotice?.description).toContain("backup");
});
it("returns to ready when a serving runtime has subsequently reported ready", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [runtimeService({ startedAt: new Date("2026-08-19T00:01:00.000Z") })],
operations: [
operation({
phase: "workspace_repair",
status: "failed",
metadata: { repairPhase: "managed_restart" },
finishedAt: new Date("2026-08-19T00:02:00.000Z"),
}),
],
handoffFailure: {
reason: "workspace_not_ready",
readiness: {
state: "ready",
databaseReady: true,
cloneDataReady: true,
authHandoffReady: true,
authHandoffUserId: null,
seedState: "verified",
seedPhase: "complete",
seedMode: "full",
instanceId: "instance-a",
executionWorkspaceId: "ews-1",
companyId: "company-1",
failurePhase: null,
},
},
});
expect(access).toMatchObject({ state: "ready", action: { kind: "open" } });
expect(access.secondaryNotice?.action.kind).toBe("view_logs");
});
it("keeps a newer failed repair primary even when an older runtime is healthy", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [runtimeService({ startedAt: new Date("2026-08-19T00:01:00.000Z") })],
operations: [
operation({
phase: "workspace_repair",
status: "failed",
finishedAt: new Date("2026-08-19T00:02:00.000Z"),
}),
],
});
expect(access).toMatchObject({ state: "failed", action: { kind: "view_logs" } });
expect(access.secondaryNotice).toBeUndefined();
});
it("shows provisioning while the clone is restoring", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [],
operations: [operation({ status: "running" })],
});
expect(access).toMatchObject({ state: "provisioning", action: { kind: "wait" } });
expect(access.title).toBe("Provisioning database");
});
it("offers a repair when provisioning failed, naming the seed phase", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [],
operations: [operation({ status: "failed", metadata: { seedFailurePhase: "restore" } })],
});
expect(access).toMatchObject({ state: "failed", action: { kind: "repair", label: "Repair workspace" } });
expect(access.description).toContain("restore");
});
it("shows validating, not degraded, while a fresh clone is still being confirmed", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [runtimeService()],
operations: [operation()],
handoffFailure: {
reason: "workspace_not_ready",
detail: "clone_data_missing",
readiness: {
state: "validating",
databaseReady: true,
cloneDataReady: false,
authHandoffReady: true,
authHandoffUserId: null,
seedState: "unknown",
seedPhase: "legacy_complete_marker",
seedMode: null,
instanceId: "instance-a",
executionWorkspaceId: "ews-1",
companyId: "company-1",
failurePhase: "clone_data_missing",
},
},
});
expect(access).toMatchObject({ state: "validating", action: { kind: "wait" } });
expect(access.description).toContain("restored no company or issue rows");
});
it("degrades a verified clone whose database regressed and offers one repair", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [runtimeService()],
operations: [operation()],
handoffFailure: {
reason: "workspace_not_ready",
detail: "database_unreachable",
readiness: {
state: "degraded",
databaseReady: false,
cloneDataReady: false,
authHandoffReady: false,
authHandoffUserId: null,
seedState: "verified",
seedPhase: "complete",
seedMode: "minimal",
instanceId: "instance-a",
executionWorkspaceId: "ews-1",
companyId: "company-1",
failurePhase: "database_unreachable",
},
},
});
expect(access).toMatchObject({ state: "degraded", action: { kind: "repair" } });
expect(access.description).toContain("isolated database is not answering");
});
it("labels the credential path accurately when no handoff is configured", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [runtimeService()],
operations: [operation()],
handoffFailure: { reason: "handoff_not_configured" },
});
expect(access).toMatchObject({
state: "ready",
action: { kind: "open" },
handoffAvailable: false,
});
expect(access.description).toContain("snapshot-local credentials");
});
it("offers start when nothing is running", () => {
expect(
resolveWorkspaceAccessState({ runtimeServices: [], operations: [] }),
).toMatchObject({ state: "provisioning", action: { kind: "start", label: "Start workspace" } });
expect(
resolveWorkspaceAccessState({
runtimeServices: [],
operations: [],
handoffFailure: { reason: "runtime_not_running" },
}),
).toMatchObject({ state: "provisioning", action: { kind: "start" } });
});
it("refuses to call an unhealthy running runtime ready", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [runtimeService({ healthStatus: "unhealthy" })],
operations: [operation()],
});
expect(access).toMatchObject({ state: "degraded", action: { kind: "repair" } });
});
it("treats a running service with no URL as not yet serving", () => {
const access = resolveWorkspaceAccessState({
runtimeServices: [runtimeService({ url: null })],
operations: [operation()],
});
expect(access.state).not.toBe("ready");
});
it("handles missing operations and services without throwing", () => {
expect(resolveWorkspaceAccessState({ runtimeServices: null, operations: undefined }).state)
.toBe("provisioning");
});
});
describe("describeWorkspaceReadinessCause", () => {
it("prefers the recorded readiness phase over the generic reason", () => {
expect(
describeWorkspaceReadinessCause({
reason: "workspace_not_ready",
readiness: {
state: "degraded",
databaseReady: true,
cloneDataReady: true,
authHandoffReady: false,
authHandoffUserId: null,
seedState: "verified",
seedPhase: "complete",
seedMode: "minimal",
instanceId: "i",
executionWorkspaceId: "e",
companyId: "company-1",
failurePhase: "cloned_membership_missing",
},
}),
).toBe("No cloned user has an active company membership.");
});
it("falls back to the reason and finally to null", () => {
expect(describeWorkspaceReadinessCause({ reason: "runtime_not_running" }))
.toContain("No healthy runtime service");
expect(describeWorkspaceReadinessCause({ reason: "something_new" })).toBeNull();
expect(describeWorkspaceReadinessCause(null)).toBeNull();
});
});
+271
View File
@@ -0,0 +1,271 @@
import type {
WorkspaceOperation,
WorkspaceReadiness,
WorkspaceReadinessState,
WorkspaceRuntimeService,
} from "@paperclipai/shared";
/**
* Derives the workspace access state the UI shows (PAP-17572).
*
* The board cannot read a cloned workspace's protected health directly, so state
* comes from three server-side facts it *can* see: the live runtime rows, the
* workspace operation log, and the readiness the control plane reported when it
* last tried to mint a login handoff.
*
* Every state carries one concrete next action. The failure this replaces was a
* generic "Load failed" (or worse, a green badge) that told an operator nothing
* about whether to wait, start, repair, or read a log.
*/
export type WorkspaceAccessActionKind =
| "open"
| "start"
| "repair"
| "view_logs"
/** Nothing to do but wait for a running operation. */
| "wait";
export type WorkspaceAccessAction = {
kind: WorkspaceAccessActionKind;
label: string;
};
export type WorkspaceAccessNotice = {
title: string;
description: string;
action: WorkspaceAccessAction;
};
export type WorkspaceAccessState = {
state: WorkspaceReadinessState;
title: string;
description: string;
action: WorkspaceAccessAction;
/** True when a password-independent handoff is the expected way in. */
handoffAvailable: boolean;
/** A non-blocking historical failure that is still useful to inspect. */
secondaryNotice?: WorkspaceAccessNotice;
};
/** What the control plane said the last time a handoff was requested. */
export type WorkspaceLoginHandoffFailureInfo = {
reason: string;
detail?: string | null;
readiness?: WorkspaceReadiness | null;
};
function latestOperation(operations: WorkspaceOperation[], phase: WorkspaceOperation["phase"]) {
return operations.find((operation) => operation.phase === phase) ?? null;
}
function describeSeedPhase(readiness: WorkspaceReadiness | null | undefined): string | null {
if (!readiness?.failurePhase && !readiness?.seedPhase) return null;
return readiness.failurePhase ?? readiness.seedPhase ?? null;
}
function timestampMs(value: Date | string | null | undefined): number | null {
if (!value) return null;
const timestamp = value instanceof Date ? value.getTime() : new Date(value).getTime();
return Number.isFinite(timestamp) ? timestamp : null;
}
function failedRepairNotice(repair: WorkspaceOperation): WorkspaceAccessNotice {
const phase = typeof repair.metadata?.repairPhase === "string" ? repair.metadata.repairPhase : null;
return {
title: "Repair failed",
description: phase
? `The repair stopped during ${phase}. The pre-repair backup was kept.`
: "The repair stopped before the workspace became usable. The pre-repair backup was kept.",
action: { kind: "view_logs", label: "View repair log" },
};
}
const HANDOFF_REASON_COPY: Record<string, string> = {
handoff_not_configured:
"This instance has no workspace login handoff configured, so opening the board falls back to snapshot-local credentials.",
no_board_identity:
"Your session has no cloned user to sign in as, so opening the board falls back to snapshot-local credentials.",
runtime_not_running: "No healthy runtime service is publishing a URL for this workspace yet.",
runtime_url_unusable: "The runtime row is publishing a URL Paperclip cannot open.",
workspace_not_ready: "The cloned database is not ready to accept a login yet.",
};
const READINESS_FAILURE_COPY: Record<string, string> = {
database_unreachable: "The isolated database is not answering.",
clone_data_missing: "The clone restored no company or issue rows.",
clone_data_unreadable: "The cloned product tables could not be read.",
cloned_membership_missing: "No cloned user has an active company membership.",
cloned_identity_unreadable: "The cloned identity tables could not be read.",
auth_handoff_not_configured: "The workspace was started without a login handoff key.",
seed_manifest_unreadable: "The seed manifest is unreadable, so the restore cannot be trusted.",
};
/**
* Human cause for a readiness rejection, preferring the specific recorded phase
* over a generic sentence so the copy names what to fix.
*/
export function describeWorkspaceReadinessCause(
failure: WorkspaceLoginHandoffFailureInfo | null | undefined,
): string | null {
if (!failure) return null;
const phase = describeSeedPhase(failure.readiness);
if (phase && READINESS_FAILURE_COPY[phase]) return READINESS_FAILURE_COPY[phase];
if (phase) return `Last recorded phase: ${phase}.`;
if (failure.detail && READINESS_FAILURE_COPY[failure.detail]) return READINESS_FAILURE_COPY[failure.detail];
return HANDOFF_REASON_COPY[failure.reason] ?? null;
}
export function resolveWorkspaceAccessState(input: {
runtimeServices: WorkspaceRuntimeService[] | null | undefined;
operations: WorkspaceOperation[] | null | undefined;
handoffFailure?: WorkspaceLoginHandoffFailureInfo | null;
}): WorkspaceAccessState {
const operations = input.operations ?? [];
const runtimeServices = input.runtimeServices ?? [];
const repair = latestOperation(operations, "workspace_repair");
const provision =
latestOperation(operations, "workspace_runtime_provision")
?? latestOperation(operations, "workspace_provision");
const failure = input.handoffFailure ?? null;
const cause = describeWorkspaceReadinessCause(failure);
const handoffAvailable = failure?.reason !== "handoff_not_configured" && failure?.reason !== "no_board_identity";
const servingService = runtimeServices.find(
(service) => service.status === "running" && service.healthStatus === "healthy" && service.url,
);
const repairFinishedAt = timestampMs(repair?.finishedAt);
const servingServiceStartedAt = timestampMs(servingService?.startedAt);
const readinessConfirmsServing = Boolean(servingService && failure?.readiness?.state === "ready");
const runtimeStartedAfterRepair = repairFinishedAt !== null
&& servingServiceStartedAt !== null
&& repairFinishedAt < servingServiceStartedAt;
const repairFailureWasSuperseded = repair?.status === "failed" && Boolean(
servingService
&& (readinessConfirmsServing || runtimeStartedAfterRepair),
);
const secondaryNotice = repair?.status === "failed" && repairFailureWasSuperseded
? failedRepairNotice(repair)
: undefined;
// A live repair outranks everything: it is already changing the answer.
if (repair?.status === "running") {
const phase = typeof repair.metadata?.repairPhase === "string" ? repair.metadata.repairPhase : null;
return {
state: "repairing",
title: "Repairing workspace database",
description: phase
? `Only the isolated database is replaced; the git worktree and your files are preserved. Current phase: ${phase}.`
: "Only the isolated database is replaced; the git worktree and your files are preserved.",
action: { kind: "wait", label: "Repair in progress" },
handoffAvailable,
};
}
if (repair?.status === "failed" && !repairFailureWasSuperseded) {
const notice = failedRepairNotice(repair);
return {
state: "failed",
...notice,
handoffAvailable,
};
}
if (provision?.status === "running") {
return {
state: "provisioning",
title: "Provisioning database",
description: "Restoring the isolated database clone for this workspace. This runs once before the first start.",
action: { kind: "wait", label: "Provisioning" },
handoffAvailable,
};
}
if (provision?.status === "failed") {
const seedPhase = typeof provision.metadata?.seedFailurePhase === "string"
? provision.metadata.seedFailurePhase
: null;
return {
state: "failed",
title: "Database provisioning failed",
description: seedPhase
? `The clone failed during ${seedPhase}. Repairing replaces only the isolated database.`
: "The clone did not finish, so this workspace has no usable database yet.",
action: { kind: "repair", label: "Repair workspace" },
handoffAvailable,
};
}
// Readiness the control plane actually observed beats anything inferred from
// runtime rows, because it is the only signal that looked inside the clone.
const staleNotReadyFailure = failure?.reason === "workspace_not_ready" && readinessConfirmsServing;
if (failure && !staleNotReadyFailure) {
if (failure.reason === "runtime_not_running" && !servingService) {
return {
state: "provisioning",
title: "Workspace is not running",
description: "Start the workspace runtime to publish its board.",
action: { kind: "start", label: "Start workspace" },
handoffAvailable,
};
}
if (failure.reason === "workspace_not_ready" || failure.reason === "runtime_url_unusable") {
const readinessState = failure.readiness?.state;
const validating = readinessState === "validating" || readinessState === "provisioning";
return {
state: validating ? "validating" : "degraded",
title: validating ? "Validating clone" : "Workspace is degraded",
description: [
cause ?? "The workspace is serving, but its clone did not pass the readiness contract.",
validating ? "Paperclip is still confirming the clone." : "One bounded repair replaces the isolated database.",
].join(" "),
action: validating
? { kind: "wait", label: "Validating" }
: { kind: "repair", label: "Repair workspace" },
handoffAvailable,
};
}
if (!handoffAvailable) {
return {
state: servingService ? "ready" : "degraded",
title: servingService ? "Ready — snapshot-local sign-in" : "Workspace is degraded",
description: cause ?? "Opening the board will ask for the credentials captured in this snapshot.",
action: servingService
? { kind: "open", label: "Open workspace" }
: { kind: "start", label: "Start workspace" },
handoffAvailable: false,
secondaryNotice,
};
}
}
if (servingService) {
return {
state: "ready",
title: "Ready",
description: "Opening the workspace signs you in to the cloned board without a password.",
action: { kind: "open", label: "Open workspace" },
handoffAvailable,
secondaryNotice,
};
}
const unhealthyService = runtimeServices.find(
(service) => service.status === "running" && service.healthStatus !== "healthy",
);
if (unhealthyService) {
return {
state: "degraded",
title: "Workspace is degraded",
description: cause
?? "The runtime is up but did not report a usable database, so Paperclip will not publish it as ready.",
action: { kind: "repair", label: "Repair workspace" },
handoffAvailable,
};
}
return {
state: "provisioning",
title: "Workspace is not running",
description: "Start the workspace runtime to publish its board.",
action: { kind: "start", label: "Start workspace" },
handoffAvailable,
};
}
+109
View File
@@ -13,6 +13,7 @@ import { CopyText } from "../components/CopyText";
import { ExecutionWorkspaceCloseDialog } from "../components/ExecutionWorkspaceCloseDialog";
import { MissingPluginTabPlaceholder } from "../components/MissingPluginTabPlaceholder";
import { agentsApi } from "../api/agents";
import { ApiError } from "../api/client";
import { executionWorkspacesApi } from "../api/execution-workspaces";
import { heartbeatsApi } from "../api/heartbeats";
import { issuesApi } from "../api/issues";
@@ -35,12 +36,17 @@ import {
type WorkspaceRuntimeControlRequest,
} from "../components/WorkspaceRuntimeControls";
import { WorkspaceServiceControlBar } from "../components/WorkspaceServiceControlBar";
import { WorkspaceAccessCard } from "../components/WorkspaceAccessCard";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { useCompany } from "../context/CompanyContext";
import { useToastActions } from "../context/ToastContext";
import { collectLiveIssueIds } from "../lib/liveIssueIds";
import { queryKeys } from "../lib/queryKeys";
import { cn, formatDateTime, issueUrl, projectRouteRef, projectWorkspaceUrl } from "../lib/utils";
import {
resolveWorkspaceAccessState,
type WorkspaceLoginHandoffFailureInfo,
} from "../lib/workspace-access-state";
import {
getWorkspaceSpecificRoutineVariableNames,
routineHasWorkspaceSpecificVariables,
@@ -412,6 +418,27 @@ export function resolveRuntimeProvisionStatus(input: {
return configured ? { kind: "deferred" } : { kind: "eager" };
}
/**
* Read the structured refusal the login-handoff endpoint returns.
*
* The server keeps a machine `reason` (and, where it probed, the workspace's own
* readiness) on the error body so the UI can name the cause instead of showing a
* bare HTTP failure. Anything else is a genuine transport error.
*/
export function readWorkspaceHandoffFailure(error: unknown): WorkspaceLoginHandoffFailureInfo | null {
if (!(error instanceof ApiError)) return null;
const body = error.body as
| { reason?: unknown; detail?: unknown; readiness?: unknown }
| null
| undefined;
if (!body || typeof body.reason !== "string") return null;
return {
reason: body.reason,
detail: typeof body.detail === "string" ? body.detail : null,
readiness: (body.readiness as WorkspaceLoginHandoffFailureInfo["readiness"]) ?? null,
};
}
function DetailRow({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="flex flex-col gap-1.5 py-1.5 sm:flex-row sm:items-start sm:gap-3">
@@ -779,6 +806,8 @@ export function ExecutionWorkspaceDetail() {
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [runtimeActionErrorMessage, setRuntimeActionErrorMessage] = useState<string | null>(null);
const [runtimeActionMessage, setRuntimeActionMessage] = useState<string | null>(null);
const [handoffFailure, setHandoffFailure] = useState<WorkspaceLoginHandoffFailureInfo | null>(null);
const [handoffErrorMessage, setHandoffErrorMessage] = useState<string | null>(null);
const [pendingRuntimeActions, setPendingRuntimeActions] = useState<WorkspaceRuntimeControlRequest[]>([]);
const activeRouteTab = workspaceId ? resolveExecutionWorkspaceTab(location.pathname, workspaceId) : null;
const pluginTabFromSearch = useMemo(() => {
@@ -968,6 +997,67 @@ export function ExecutionWorkspaceDetail() {
},
});
/**
* Password-independent workspace entry (PAP-17572).
*
* The server answers with a ticket-bearing URL, and the workspace answers *that*
* with a redirect — which is what keeps the ticket out of session history.
*
* The target tab is opened synchronously on click and only pointed at the URL
* once the ticket arrives. Opening it after the request resolves would be a
* popup the browser did not attribute to the click, and Safari and Firefox
* block exactly that. If the tab could not be opened anyway, fall back to
* navigating this one rather than silently doing nothing.
*/
const openWorkspace = useMutation({
mutationFn: async () => {
const target = window.open("about:blank", "_blank", "noopener,noreferrer");
try {
return { ticket: await executionWorkspacesApi.requestLoginHandoff(workspace!.id), target };
} catch (error) {
target?.close();
throw error;
}
},
onSuccess: ({ ticket, target }) => {
setHandoffFailure(null);
setHandoffErrorMessage(null);
if (target && !target.closed) target.location.replace(ticket.url);
else window.location.assign(ticket.url);
},
onError: async (error) => {
// A structured refusal is rendered as workspace state by the access card,
// so only an unrecognized transport error needs its own message line.
const failure = readWorkspaceHandoffFailure(error);
setHandoffFailure(failure);
setHandoffErrorMessage(
failure ? null : error instanceof Error ? error.message : "Failed to open the workspace.",
);
// The refusal reason often comes from an operation that has since advanced,
// so refresh the log the access card derives its state from.
await queryClient.invalidateQueries({
queryKey: queryKeys.executionWorkspaces.workspaceOperations(workspace!.id),
});
},
});
const repairWorkspace = useMutation({
mutationFn: () => executionWorkspacesApi.repair(workspace!.id),
onSuccess: (result) => {
queryClient.setQueryData(queryKeys.executionWorkspaces.detail(result.workspace.id), result.workspace);
queryClient.invalidateQueries({
queryKey: queryKeys.executionWorkspaces.workspaceOperations(result.workspace.id),
});
setHandoffFailure(null);
setHandoffErrorMessage(null);
setRuntimeActionErrorMessage(null);
setRuntimeActionMessage("Workspace database repaired.");
},
onError: (error) => {
setRuntimeActionMessage(null);
setRuntimeActionErrorMessage(error instanceof Error ? error.message : "Failed to repair the workspace.");
},
});
if (workspaceQuery.isLoading) return <p className="text-sm text-muted-foreground">Loading workspace…</p>;
if (workspaceQuery.error) {
return (
@@ -992,6 +1082,11 @@ export function ExecutionWorkspaceDetail() {
runtimeServices: workspace.runtimeServices ?? [],
pendingRequests: pendingRuntimeActions,
});
const workspaceAccess = resolveWorkspaceAccessState({
runtimeServices: workspace.runtimeServices ?? [],
operations: workspaceOperationsQuery.data,
handoffFailure,
});
const pluginSlotContext = {
companyId: workspace.companyId,
@@ -1062,6 +1157,20 @@ export function ExecutionWorkspaceDetail() {
{runtimeActionErrorMessage ? <p className="text-sm text-destructive">{runtimeActionErrorMessage}</p> : null}
{!runtimeActionErrorMessage && runtimeActionMessage ? <p className="text-sm text-muted-foreground">{runtimeActionMessage}</p> : null}
<WorkspaceAccessCard
access={workspaceAccess}
isBusy={openWorkspace.isPending || repairWorkspace.isPending}
onOpen={() => openWorkspace.mutate()}
onStart={() => {
runRuntimeControlRequests(
resolveWorkspaceServiceControlRequests(runtimeControlSections, "start", null),
);
}}
onRepair={() => repairWorkspace.mutate()}
onViewLogs={() => handleTabChange("runtime_logs")}
errorMessage={handoffErrorMessage}
/>
<PluginSlotOutlet
slotTypes={["toolbarButton", "contextMenuItem"]}
entityType="execution_workspace"