Start onboarding in chat and defer execution until the user chooses work (#22077)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Onboarding connects an agent and gives the user a place to discuss
work.
> - The previous flow created an execution task and project before the
user chose a scope.
> - A standing chat can gather the goal and clear exit criteria first.
> - This pull request opens chat after onboarding and starts a live
welcome after the chat is visible.
> - The agent proposes work for acceptance, or creates a task when the
user explicitly requests one.
> - Subscription setup and shared question state must work for this
first conversation to succeed.

## Linked Issues or Issue Description

**Subsystem affected**
Company onboarding, agent chat, local subscription setup, task
numbering, and shared interaction views.

**Problem or motivation**
The first session creates work before the user has agreed to a goal.
Standing chats consume task numbers. An answered chat question can
remain pending in the inbox. Claude code entry requires an extra click,
and switching from Claude to Codex can leave an incompatible model
selected.

**Proposed solution**
Open an owner-bound chat for every new company. Start a live welcome
after the chat paints in a visible tab. Gather scope in conversation and
use the existing task acceptance flow. Keep chat records out of the task
number sequence. Publish question responses to shared caches and cancel
stale reads. Submit pasted Claude codes once and wait for verified
sign-in before connecting.

**Alternatives considered**
A fixed welcome would not use the onboarding context. A hidden execution
task would still create work and consume a task number. Keep the
existing task proposal and acceptance contract instead.

**Roadmap alignment**
This improves the shipped Agent Chat and Personal & Shared AI Accounts
flows in ROADMAP.md. It does not add a separate execution or approval
system.

Related prior work: Refs #19643 and #19512. Related route handoff work:
Refs #12557. This change replaces the automatic first task with chat; it
also repairs the subscription and shared question state paths used
during that journey.

## What Changed

- Finish onboarding in agent chat for default and team-template
companies. Create no execution task or project.
- Queue one live welcome after visible chat content paints. Pass company
goals and the initial idea as context. Preserve access, budget, and
hiring controls.
- Instruct the agent to gather a goal and exit criteria, offer an
interview, and propose tasks for acceptance. Allow direct creation on an
explicit user request.
- Leave new standing chats unnumbered. The first execution task receives
number 1. Preserve existing identifiers.
- Synchronize answered question cards across chat and inbox, including
concurrent requests and inactive cached views.
- Submit a pasted Claude authorization code once. Show connection
progress and hide the restart link while sign-in is still preparing.
Detect rejected OAuth codes promptly. Clear incompatible models when the
provider changes.
- Use `Work with [agent name]` as the default chat composer placeholder.
- Add regression coverage and update onboarding documentation and API
notes.

## Verification

- Completed a real Claude subscription journey on macOS with an isolated
local database. Authorized the account, pasted the real code, and
reached the review step without clicking Submit code or Connect. Get
started opened chat and the live welcome run succeeded. The company had
zero execution tasks, zero projects, and task counter 0.
- On rebased commit c664949858, 6 browser cases passed for
paste-to-connect-to-chat, task-free onboarding, existing-company
routing, the native connection probe gate, desktop/mobile planning, and
two-tab chat/inbox question synchronization.
- On the rebased head, 419 focused UI tests passed. The focused server
and adapter run passed 160 tests and hit one `socket hang up` in the
existing authenticated chat route test. The full 72-test conversation
suite passed on one repeat. The cause of that first socket failure
remains unconfirmed; the passing repeat does not establish its cause.
- UI typecheck and server declaration typecheck pass after the rebase.
The first server check found a missing local dependency from master; a
frozen-lockfile install repaired it. No dependency manifest or lockfile
change was needed.
- The first Greptile review found two welcome edge cases. Four new tests
reproduced both before the fix. On commit b380f14ef9, all 114 onboarding
and queue tests pass, including timeout retries and queued welcomes
replaced by a user message or chat reset. Server source and focused test
type checks pass on this revision.
- [Greptile
review](https://github.com/paperclipai/paperclip/pull/22077#issuecomment-6961533641)
gives rebased commit 2dbad34445 a score of
5/5. The current-head check passed. Both welcome review threads are
resolved, with no new actionable findings.
- CI serialized shard 8/9 found a missing OpenAPI inventory entry for
the new route file. The exact coverage test reproduced this locally.
Commit 17a72ec8b7 adds explicit mounted paths and documents both
board-only operations. All 65 OpenAPI and onboarding route tests and
server source typecheck pass after the fix. The final CI run passes on
this revision.
- Rebased onto master 23ce68a8dc and regenerated the SDK source registry
from committed inputs. Worktree preflight, SDK source validation, and
all 65 API/onboarding tests pass on final head
2dbad34445.
- On final head 2dbad34445, all 419
affected UI tests pass. UI package typecheck and server declaration
typecheck also pass. Commands: `pnpm --filter @paperclipai/ui
typecheck`; `node server/scripts/typecheck-layers.mjs
--declarations-only`; focused Vitest suites for the wizard, subscription
login, agent chat, shared interaction cache, and OpenAPI/onboarding
routes.
- [Final-head CI
run](https://github.com/paperclipai/paperclip/actions/runs/44208652564)
completed successfully on commit
2dbad34445. All required typecheck, build,
test, Runner, browser, serialized-server, and canary gates pass,
including the [final verify
job](https://github.com/paperclipai/paperclip/actions/runs/44208652564/job/134487749343).
The fresh routing gate selected the trusted AWS fleet after the
protected owner policy in #22098 merged. No source rebase was needed:
the gate reads that policy from protected master.
- The repaired OpenAPI shard passed in the earlier same-head CI run.
General server shard 8/12 hit a 20-second step timeout in the existing
`issue-recovery-live-run-agent-census` suite. This PR does not change
that suite or its fixture. All four tests pass locally on the exact
current commit in 84 seconds. The cause of the CI timeout remains
unconfirmed. Every other test job passed. A single failed-shard retry
was accepted but remained queued on its saved GitHub-hosted selection.
It was cancelled before test execution after #22098 merged. The fresh
full-CI run passed on the unchanged head under the approved AWS policy,
including [server shard
8/12](https://github.com/paperclipai/paperclip/actions/runs/44208652564/job/134481388730).
This passing execution does not establish the cause of the earlier
timeout.
- Worktree preflight, committed SDK source input validation, and diff
whitespace checks pass after the rebase.
- `pnpm verify` reports exit 2 because the new subsystem documentation
requires broader CI coverage. The final successful CI run supplies that
broader coverage. This is not a full local suite pass.

## Risks

- The initial task is now an explicit user decision. Existing onboarding
tasks and numbered records remain readable. No schema migration is
required.
- A welcome still depends on a working provider connection and the
normal run queue. Failed starts can be retried without duplicate
successful welcomes.
- Claude paste acceptance was verified with a real subscription on
macOS. This change does not claim a new live Codex or Windows acceptance
test.

## Model Used

OpenAI Codex, based on GPT-6, with tool-assisted reasoning, code
execution, terminal checks, and browser verification. The client does
not expose the exact routed build or context limit.

## 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: Scott Tong <scott@scottsmbpm5max.lan>
Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
authored and GitHub committed 2026-11-17 16:52:35 -08:00
1 parent 96907f5518
commit ce27dde855
57 files changed
+1156 -509

No files matched your search

+37 -10
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useEffect, useRef, useState, type ClipboardEvent, type ReactNode } from "react";
import { AnimatePresence, motion } from "motion/react";
import { Copy, Check, Loader2 } from "lucide-react";
@@ -371,7 +371,7 @@ export function OnboardingCardField({
value: string;
onChange: (value: string) => void;
onSubmit: () => void;
onPaste?: () => void;
onPaste?: (event: ClipboardEvent<HTMLInputElement>) => void;
disabled?: boolean;
label?: string;
placeholder?: string;
@@ -404,7 +404,7 @@ export function OnboardingCardField({
value={value}
disabled={disabled}
onChange={(event) => onChange(event.target.value)}
onPaste={() => onPaste?.()}
onPaste={onPaste}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
@@ -497,31 +497,57 @@ export function LocalProviderLoginInstructions({ adapterType, login }: {
const [showCommand, setShowCommand] = useState(false);
const [browserCode, setBrowserCode] = useState("");
const [submitting, setSubmitting] = useState(false);
const [codeSubmitted, setCodeSubmitted] = useState(false);
const codeSubmissionRef = useRef<symbol | null>(null);
useEffect(() => {
codeSubmissionRef.current = null;
setBrowserCode("");
setSubmitting(false);
setCodeSubmitted(false);
}, [login?.authorizationUrl, login?.preparing]);
const provider = adapterType === "antigravity_runtime" ? "Google Antigravity" : adapterType === "claude_local" ? "Claude Code" : adapterType === "grok_local" ? "Grok CLI" : "Codex CLI";
const isolated = login?.isolated ?? (adapterType === "codex_local" || adapterType === "grok_local");
const command = login?.command;
const browserLogin = adapterType === "claude_local" || adapterType === "codex_local" || adapterType === "antigravity_runtime";
async function submitBrowserCode() {
if (!browserCode.trim() || !login?.submitCode || submitting) return;
async function submitBrowserCode(value = browserCode) {
if (!value.trim() || !login?.submitCode || codeSubmissionRef.current) return;
const submission = Symbol();
codeSubmissionRef.current = submission;
setSubmitting(true);
try {
await login.submitCode(browserCode.trim());
await login.submitCode(value.trim());
if (codeSubmissionRef.current !== submission) return;
setBrowserCode("");
setCodeSubmitted(true);
} catch {
// The login hook presents the request error beside the sign-in card.
if (codeSubmissionRef.current === submission) codeSubmissionRef.current = null;
} finally {
setSubmitting(false);
if (codeSubmissionRef.current === submission || codeSubmissionRef.current === null) setSubmitting(false);
}
}
function pasteBrowserCode(event: ClipboardEvent<HTMLInputElement>) {
const pasted = event.clipboardData?.getData("text");
if (!pasted?.trim()) return;
const input = event.currentTarget;
const start = input.selectionStart ?? input.value.length;
const end = input.selectionEnd ?? start;
const value = input.value.slice(0, start) + pasted + input.value.slice(end);
event.preventDefault();
setBrowserCode(value);
void submitBrowserCode(value);
}
if (login?.preparing) return <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />Preparing sign-in…</p>;
const ready = login?.status === "ready";
const awaitingBrowserSignIn = browserLogin && !ready && !login?.authorizationUrl && !login?.error;
return <div className="min-w-0 max-w-full space-y-3 text-sm text-muted-foreground">
{ready ? <>
<p role="status" className={cn("flex items-center gap-2 text-foreground", ANALYTICS_MASK_CLASS)}><Check className="size-4 shrink-0 text-(--status-task-icon-done)" />{login?.accountLabel ?? provider} is signed in. Click Connect to use this account.</p>
{!showCommand && <button type="button" className="underline underline-offset-4" onClick={() => browserLogin ? login?.retry() : setShowCommand(true)}>Use a different account</button>}
</> : !browserLogin && <p>{isolated ? `Sign in to ${provider} for this connection on the machine running Paperclip. Your existing terminal login stays separate.` : `Connect uses your local ${provider} account on the machine running Paperclip.`}</p>}
{browserLogin && !ready && !login?.authorizationUrl && !login?.error && <p role="status">Preparing browser sign-in…</p>}
{browserLogin && !ready && !login?.error && login?.authorizationUrl && <ProviderSubscriptionCard
{awaitingBrowserSignIn && <p role="status">Preparing browser sign-in…</p>}
{(submitting || codeSubmitted) && !ready && !login?.error && <p role="status">Finishing sign-in…</p>}
{browserLogin && !ready && !submitting && !codeSubmitted && !login?.error && login?.authorizationUrl && <ProviderSubscriptionCard
providerName={connectSourceName(adapterType)}
authorizationUrl={login.authorizationUrl}
mode={adapterType === "antigravity_runtime" ? "browser_redirect" : adapterType === "claude_local" ? "submitted_code" : "displayed_code"}
@@ -530,6 +556,7 @@ export function LocalProviderLoginInstructions({ adapterType, login }: {
<OnboardingCardField
value={browserCode}
onChange={setBrowserCode}
onPaste={pasteBrowserCode}
onSubmit={() => void submitBrowserCode()}
disabled={submitting}
/>
@@ -544,6 +571,6 @@ export function LocalProviderLoginInstructions({ adapterType, login }: {
</div>}
</>}
{login?.error && <p role="alert">{login.error}</p>}
{login && !login.preparing && !ready && (isolated || login.error) && <button type="button" className="underline underline-offset-4" onClick={login.retry}>{isolated ? "Start sign-in again" : "Check again"}</button>}
{login && !login.preparing && !ready && !awaitingBrowserSignIn && (isolated || login.error) && <button type="button" className="underline underline-offset-4" onClick={login.retry}>{isolated ? "Start sign-in again" : "Check again"}</button>}
</div>;
}
@@ -94,6 +94,8 @@ export function AttentionInteractionResolver({
}, [interactions, interactionId]);
const invalidate = (resolvedInteraction?: IssueThreadInteraction) => {
// Cancel old reads before publishing the write's canonical response.
invalidateInteractionRecordViews(queryClient, companyId, resolvedInteraction);
// The accept route returns the fully stitched interaction (including
// secretProposal.executed/failed). Put that receipt in the cache before
// invalidating so the attention surface never flashes a generic Accepted
@@ -104,8 +106,6 @@ export function AttentionInteractionResolver({
(current) => replaceResolvedInteraction(current, resolvedInteraction),
);
}
// Task detail keys the same list by identifier, so refresh every view (UX2).
invalidateInteractionRecordViews(queryClient, companyId);
onResolved?.(resolvedInteraction);
};
+54 -6
View File
@@ -173,6 +173,8 @@ const mockSecretsApi = vi.hoisted(() => ({
const mockIssuesApi = vi.hoisted(() => ({
create: vi.fn(),
}));
const mockAgentChatsApi = vi.hoisted(() => ({ startOnboarding: vi.fn(async () => ({ id: "onboarding-chat" })) }));
const mockNavigate = vi.hoisted(() => vi.fn());
const mockProjectsApi = vi.hoisted(() => ({
create: vi.fn(),
list: vi.fn(async () => []),
@@ -190,7 +192,7 @@ const mockRouterState = vi.hoisted(() => ({ pathname: "/" }));
vi.mock("@/lib/router", () => ({
useLocation: () => ({ pathname: mockRouterState.pathname, search: "", hash: "", state: null }),
useNavigate: () => vi.fn(),
useNavigate: () => mockNavigate,
useParams: () => ({}),
}));
vi.mock("../context/DialogContext", () => ({
@@ -205,6 +207,7 @@ vi.mock("../api/agents", () => ({ agentsApi: mockAgentsApi }));
vi.mock("../api/approvals", () => ({ approvalsApi: mockApprovalsApi }));
vi.mock("../api/secrets", () => ({ secretsApi: mockSecretsApi }));
vi.mock("../api/issues", () => ({ issuesApi: mockIssuesApi }));
vi.mock("../api/agentChats", () => ({ agentChatsApi: mockAgentChatsApi }));
vi.mock("../api/projects", () => ({ projectsApi: mockProjectsApi }));
vi.mock("../api/environments", () => ({ environmentsApi: mockEnvironmentsApi }));
vi.mock("../api/instanceSettings", () => ({ instanceSettingsApi: mockInstanceSettingsApi }));
@@ -1450,6 +1453,18 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
} finally { await act(async () => root.unmount()); }
});
it("finishes onboarding in chat without creating a task or project", async () => {
const { root } = await openSavedReview("/SC/onboarding");
try {
await act(async () => [...document.querySelectorAll("button")].find(button => button.textContent?.trim() === "Get started")!.click());
await vi.waitFor(() => expect(mockNavigate).toHaveBeenCalledWith("/SC/chats/saved-agent"));
expect(mockAgentChatsApi.startOnboarding).toHaveBeenCalledWith("c1", "saved-agent");
expect(mockCompany.setSelectedCompanyId).toHaveBeenCalledWith("c1", { source: "route_sync" });
expect(mockIssuesApi.create).not.toHaveBeenCalled();
expect(mockProjectsApi.create).not.toHaveBeenCalled();
} finally { await act(async () => root.unmount()); }
});
it("keeps restored review progress when initial effects replay in StrictMode", async () => {
const { root, draft } = await openSavedReview("/SC/onboarding", "auto", { strict: true });
try {
@@ -4533,6 +4548,23 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
} finally { await act(async () => root.unmount()); }
});
it.each(["claude_local", "codex_local"])("clears a stale Claude model when choosing an OpenAI subscription from %s", async adapterType => {
mockAdapterBuild.buildAdapterConfig.mockImplementation(values => buildCodexRunnerConfig(values!));
managedApi.list.mockResolvedValue({ currentUserId: "user-1", connections: [{
id: "openai-account", grantId: "openai-grant", companyId: "company-new", provider: "openai",
method: "subscription", ownership: "personal", ownerUserId: "user-1", status: "connected", isDefault: true,
}] } as never);
const { root } = await openStep4({ adapterType, model: "claude-opus-5-5" });
try {
await pickSource(/OpenAI/);
await settle();
expect(mockAdapterBuild.buildAdapterConfig).toHaveBeenCalledWith(expect.objectContaining({ adapterType: "codex_local", model: "" }));
expect(mockAgentsApi.testEnvironment).toHaveBeenCalledTimes(1);
const tested = mockAgentsApi.testEnvironment.mock.calls[0] as unknown as [string, string, { adapterConfig: Record<string, unknown> }];
expect(tested[2].adapterConfig.model).not.toBe("claude-opus-5-5");
} finally { await act(async () => root.unmount()); }
});
it.each(["environments", "settings", "policy"] as const)("does not use warm Claude discovery before %s resolves", async pending => {
let finish!: (value: any) => void;
const delayed = new Promise<any>(resolve => { finish = resolve; });
@@ -4672,7 +4704,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
await pickSource(label);
expect(document.body.textContent).toContain("Sign in to");
expect(document.body.textContent).not.toContain("Run this in a terminal");
expect(button("Connect").disabled).toBe(false);
expect(button("Connect").disabled).toBe(true);
await detected();
expectTesting();
// The saved account can become visible while its hello test is pending.
@@ -4744,7 +4776,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
expect(mockAgentsApi.testEnvironment).not.toHaveBeenCalled();
expect(mockAgentsApi.hire).not.toHaveBeenCalled();
expect(document.body.textContent).toContain("Sign in to");
expect(button("Connect").disabled).toBe(false);
expect(button("Connect").disabled).toBe(true);
} finally { await act(async () => root.unmount()); }
});
@@ -4840,12 +4872,17 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
}
});
it.each(providers)("keeps Connect usable when %s detection has not completed", async (adapterType, _provider, label) => {
it.each(providers)("waits for %s sign-in before allowing Connect or the keyboard shortcut", async (adapterType, _provider, label) => {
const { root } = await openStep4({ adapterType });
try {
await pickSource(label);
expect(mockAgentsApi.testEnvironment).not.toHaveBeenCalled();
expect(button("Connect").disabled).toBe(true);
await click("Connect");
await act(async () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", metaKey: true, bubbles: true })));
expect(managedApi.connectLocal).not.toHaveBeenCalled();
expect(mockAgentsApi.testEnvironment).not.toHaveBeenCalled();
await detected();
expect(managedApi.connectLocal).toHaveBeenCalledTimes(1);
expect(mockAgentsApi.testEnvironment).toHaveBeenCalledTimes(1);
expect(document.body.textContent).toContain("is ready to work!");
@@ -4920,7 +4957,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
} finally { await act(async () => root.unmount()); }
});
it("shows the Claude browser sign-in card and saves its connection before hiring", async () => {
it("automatically submits a pasted Claude code and saves the verified connection before hiring", async () => {
localHealth.get.mockResolvedValue({ deploymentMode: "local_trusted" });
mockEnvironmentsApi.list.mockResolvedValue([LOCAL_ENVIRONMENT]);
mockInstanceSettingsApi.get.mockResolvedValue({ defaultEnvironmentId: null });
@@ -4932,7 +4969,18 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", (
expect(mockAgentsApi.startClaudeSetupTokenLogin).not.toHaveBeenCalled();
const connect = [...document.body.querySelectorAll("button")].find(b => b.textContent?.trim().startsWith("Connect"));
expect(connect).toBeTruthy();
await act(async () => connect!.click());
expect(connect!.disabled).toBe(true);
const code = document.body.querySelector('input[aria-label="Authorization code"]')!;
const paste = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(paste, "clipboardData", { value: { getData: () => "fixture-authorization-code" } });
await act(async () => code.dispatchEvent(paste));
for (let i = 0; i < 4; i++) await flushReact();
expect(managedApi.submitLocalLoginCode).toHaveBeenCalledWith("company-new", "local-attempt", "fixture-authorization-code");
expect(managedApi.submitLocalLoginCode).toHaveBeenCalledTimes(1);
expect(document.body.textContent).toContain("Finishing sign-in");
expect(managedApi.connectLocal).not.toHaveBeenCalled();
managedApi.checkLocalLogin.mockResolvedValue({ status: "ready" });
await act(async () => window.dispatchEvent(new Event("focus")));
for (let i = 0; i < 6; i++) await flushReact();
expect(managedApi.connectLocal).toHaveBeenCalledWith("company-new", expect.objectContaining({ provider: "anthropic", method: "subscription", ownership: "personal" }));
expect(mockAgentsApi.hire).toHaveBeenCalled();
+20 -87
View File
@@ -78,8 +78,7 @@ import { useCompanyListQuery } from "../api/companies-query";
import { goalsApi } from "../api/goals";
import { agentsApi } from "../api/agents";
import { approvalsApi } from "../api/approvals";
import { issuesApi } from "../api/issues";
import { projectsApi } from "../api/projects";
import { agentChatsApi } from "../api/agentChats";
import { environmentsApi } from "../api/environments";
import { instanceSettingsApi } from "../api/instanceSettings";
import {
@@ -109,12 +108,7 @@ import { getAdapterDisplay } from "../adapters/adapter-display-registry";
import { buildFixedClaudeOAuthBinding, CLAUDE_OAUTH_TOKEN_ENV_KEY } from "./environment-variables-editor/model";
import { defaultCreateValues } from "./agent-config-defaults";
import { onboardingDraftStorage, restoreOnboardingState } from "../lib/onboarding-state";
import {
buildOnboardingIssuePayload,
buildOnboardingProjectPayload,
selectDefaultCompanyGoalId,
selectReusableOnboardingProject,
} from "../lib/onboarding-launch";
import { selectDefaultCompanyGoalId } from "../lib/onboarding-launch";
import { buildNewAgentRuntimeConfig } from "../lib/new-agent-runtime-config";
import { DEFAULT_CODEX_LOCAL_BYPASS_APPROVALS_AND_SANDBOX } from "@paperclipai/adapter-codex-local";
import { DEFAULT_CURSOR_LOCAL_MODEL } from "@paperclipai/adapter-cursor-local";
@@ -280,7 +274,6 @@ function ModelSourceMark({
}
export { ONBOARDING_STORAGE_KEY } from "../lib/onboarding-state";
const DEFAULT_TASK_TITLE = "Paperclip onboarding";
const INCOMPLETE_ONBOARDING_STATE_MESSAGE =
"Onboarding state is incomplete. Please restart onboarding and try again.";
@@ -698,12 +691,6 @@ function OnboardingWizardInner({
const [createdCompanyGoalId, setCreatedCompanyGoalId] = useState<string | null>(
(saved?.createdCompanyGoalId as string) ?? null
);
const [createdProjectId, setCreatedProjectId] = useState<string | null>(
(saved?.createdProjectId as string) ?? null
);
const [createdIssueRef, setCreatedIssueRef] = useState<string | null>(
(saved?.createdIssueRef as string) ?? null
);
// The company the *route* last supplied, so a navigation that stops naming
// one can drop it without touching a company the wizard created itself.
@@ -813,8 +800,6 @@ function OnboardingWizardInner({
setCreatedCompanyPrefix(null);
setCompanyName("");
setCreatedCompanyGoalId(null);
setCreatedProjectId(null);
setCreatedIssueRef(null);
setCreatedAgentId(null);
setSetupAgentId(null);
setSetupPrepared(false);
@@ -929,7 +914,7 @@ function OnboardingWizardInner({
// The mode, never the key: this blob is localStorage.
credentialMode, credentialModeChoice,
createdCompanyId, createdCompanyPrefix, createdAgentId, setupAgentId,
createdCompanyGoalId, createdProjectId, createdIssueRef,
createdCompanyGoalId,
};
onboardingDraftStorage.write(JSON.stringify(state));
}, [
@@ -937,7 +922,7 @@ function OnboardingWizardInner({
agentName, agentAppearance, agentRole, adapterType, runner, cwd, model, command, args, url,
credentialMode, credentialModeChoice,
createdCompanyId, createdCompanyPrefix, createdAgentId, setupAgentId,
createdCompanyGoalId, createdProjectId, createdIssueRef,
createdCompanyGoalId,
]);
const getCapabilities = useAdapterCapabilities();
@@ -1447,7 +1432,9 @@ function OnboardingWizardInner({
/** A sign-in is running and has not succeeded. */
const connectStepLoggingIn =
connectStepNeedsLogin && connectPhase !== "idle" && connectPhase !== "connecting";
(connectStepNeedsLogin && connectPhase !== "idle" && connectPhase !== "connecting") ||
(sourcePicked && canUseLocalLogin && credentialMode === "subscription" && !hasSavedSubscription &&
!managedBindingForStep() && localLogin.status !== "ready");
// Detecting a credential is enough to start verification once the user has
// chosen Claude or Codex. A saved-list refresh during that work is not a new
@@ -1562,7 +1549,7 @@ function OnboardingWizardInner({
label: "Connect",
icon: "arrow",
disabled:
!connectStepReady || (credentialMode === "api" && !apiKey.trim() && !selectedApiKey && !restoredApiCredential && !managedBindingForStep()),
!connectStepReady || connectStepLoggingIn || (credentialMode === "api" && !apiKey.trim() && !selectedApiKey && !restoredApiCredential && !managedBindingForStep()),
}
: // Nothing is chosen on arrival, and the row is what chooses. Until
// it has been answered the button has nothing to do.
@@ -1841,8 +1828,6 @@ function OnboardingWizardInner({
setSetupPrepared(false);
setSetupError(false);
setCreatedCompanyGoalId(null);
setCreatedProjectId(null);
setCreatedIssueRef(null);
}
function handleClose() {
@@ -1892,7 +1877,7 @@ function OnboardingWizardInner({
return false;
}
async function handleLaunchToDashboard() {
async function handleLaunchToChat() {
if (!createdCompanyId || !createdAgentId) {
setError(INCOMPLETE_ONBOARDING_STATE_MESSAGE);
return;
@@ -1900,71 +1885,17 @@ function OnboardingWizardInner({
setLoading(true);
setError(null);
try {
let goalId = createdCompanyGoalId;
if (!goalId) {
const goals = await goalsApi.list(createdCompanyId);
goalId = selectDefaultCompanyGoalId(goals);
if (stillTheSameCompany(createdCompanyId)) setCreatedCompanyGoalId(goalId);
}
let projectId = createdProjectId;
if (!projectId) {
const projects = await projectsApi.list(createdCompanyId);
const existingOnboardingProject = selectReusableOnboardingProject(projects);
if (existingOnboardingProject) {
projectId = existingOnboardingProject.id;
} else {
const project = await projectsApi.create(
createdCompanyId,
buildOnboardingProjectPayload(goalId)
);
projectId = project.id;
queryClient.invalidateQueries({
queryKey: queryKeys.projects.all(createdCompanyId)
});
}
if (stillTheSameCompany(createdCompanyId)) setCreatedProjectId(projectId);
}
let issueRef = createdIssueRef;
if (!issueRef) {
const issue = await issuesApi.create(
createdCompanyId,
buildOnboardingIssuePayload({
title: DEFAULT_TASK_TITLE,
assigneeAgentId: createdAgentId,
projectId,
goalId
})
);
issueRef = issue.identifier ?? issue.id;
if (stillTheSameCompany(createdCompanyId)) setCreatedIssueRef(issueRef);
queryClient.invalidateQueries({
queryKey: queryKeys.issues.list(createdCompanyId)
});
}
// Everything above is server work and stands on its own: the company has
// its goal, its onboarding project and its first task. What follows is
// this wizard finishing — selecting a company, discarding its own state
// and navigating. None of that is right for a customer who has moved to
// another company in the meantime: it would take them back, and `reset()`
// would discard the progress they had started there.
await agentChatsApi.startOnboarding(createdCompanyId, createdAgentId);
if (!stillTheSameCompany(createdCompanyId)) return;
const prefix = createdCompanyPrefix;
// Select the new company as a route sync, not a manual switch: the
// explicit navigate below is the intended destination, so page-memory's
// "restore last page" (which falls back to /dashboard) must not fire and
// clobber the first-task URL. See PAP-404.
const agentId = createdAgentId;
// Route sync preserves this explicit destination over page memory.
setSelectedCompanyId(createdCompanyId, { source: "route_sync" });
reset();
closeOnboarding();
// Drop the user straight into the first task's detail page (not the
// dashboard) so they land on the conversation the agent will start in.
navigate(prefix ? `/${prefix}/issues/${issueRef}` : `/issues/${issueRef}`);
navigate(`${prefix ? `/${prefix}` : ""}/chats/${agentId}`);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to launch first task");
setError(err instanceof Error ? err.message : "Failed to open your chat. Please try again.");
} finally {
setLoading(false);
}
@@ -2753,7 +2684,7 @@ function OnboardingWizardInner({
(retryLogin || submitLoginCode || !connectStepLoggingIn)
)
handleConnectStepPrimary();
else if (step === 5) handleLaunchToDashboard();
else if (step === 5) handleLaunchToChat();
}
}
@@ -3109,9 +3040,11 @@ function OnboardingWizardInner({
setSourcePicked(true);
setAdapterType(id);
if (id !== adapterType) setRunner("auto");
if (id !== adapterType) {
// Older drafts may already pair OpenAI with the Claude
// model retained by a previous source switch.
if (id !== adapterType || (id === "codex_local" && credentialMode === "subscription" && model.startsWith("claude-"))) {
if (id === "opencode_local") setModel(DEFAULT_OPENCODE_LOCAL_MODEL);
else if (id !== "codex_local") setModel("");
else setModel("");
}
setConnectPhase("collapsing");
}}
@@ -3592,7 +3525,7 @@ function OnboardingWizardInner({
// Cmd+Enter has to do the same thing. See
// `handleConnectStepPrimary`.
else if (step === 4) handleConnectStepPrimary();
else handleLaunchToDashboard();
else handleLaunchToChat();
}}
/>
)}
@@ -43,6 +43,29 @@ it("checks once under StrictMode, preserves renaming and navigation, and cancels
expect(api.cancelLocalLogin).toHaveBeenCalledTimes(1);
expect(api.cancelLocalLogin.mock.invocationCallOrder[0]).toBeLessThan(api.startLocalLogin.mock.invocationCallOrder[1]);
});
it.each(["anthropic", "openai"] as const)("waits for the %s authorization card before offering to restart sign-in", async provider => {
api.checkLocalLogin.mockResolvedValue({ status: "sign_in_required" });
flushSync(() => root.render(<Harness provider={provider} />));
await vi.waitFor(() => expect(host.textContent).toContain("Preparing browser sign-in"));
expect(host.textContent).not.toContain("Start sign-in again");
expect(api.startLocalLogin).toHaveBeenCalledTimes(1);
api.checkLocalLogin.mockResolvedValue({ status: "sign_in_required", authorizationUrl: "https://example.test/authorize", code: "ABCD-12345" });
window.dispatchEvent(new Event("focus"));
await vi.waitFor(() => expect(host.querySelector('a[href="https://example.test/authorize"]')).not.toBeNull());
if (provider === "anthropic") expect(host.querySelector('input[aria-label="Authorization code"]')).not.toBeNull();
else expect(host.textContent).toContain("ABCD-12345");
const retry = Array.from(host.querySelectorAll("button")).find(button => button.textContent === "Start sign-in again");
expect(retry).toBeTruthy();
api.checkLocalLogin.mockResolvedValue({ status: "sign_in_required" });
flushSync(() => retry!.click());
await vi.waitFor(() => expect(api.startLocalLogin).toHaveBeenCalledTimes(2));
await vi.waitFor(() => expect(host.textContent).toContain("Preparing browser sign-in"));
expect(host.textContent).not.toContain("Start sign-in again");
expect(api.cancelLocalLogin).toHaveBeenCalledTimes(1);
});
it.each(["anthropic", "openai"] as const)("detects an already-signed-in %s account before showing instructions, and does not save it until Connect", async provider => {
api.checkLocalLogin.mockResolvedValue({ status: "ready" });
flushSync(() => root.render(<Harness provider={provider} />));
@@ -92,9 +115,41 @@ it("submits a Claude browser code through the owned local attempt", async () =>
});
flushSync(() => Array.from(host.querySelectorAll("button")).find((button) => button.textContent === "Submit code")?.click());
await vi.waitFor(() => expect(api.submitLocalLoginCode).toHaveBeenCalledWith("company", "attempt-1", "fixture-code"));
await vi.waitFor(() => expect(host.textContent).toContain("Finishing sign-in"));
expect(host.querySelector('input[aria-label="Authorization code"]')).toBeNull();
expect(host.textContent).not.toContain("claude auth login");
});
it("submits a pasted Claude code once and waits for verification without another click", async () => {
let finishSubmit!: () => void;
api.submitLocalLoginCode.mockReturnValue(new Promise<void>(resolve => { finishSubmit = resolve; }));
api.checkLocalLogin.mockResolvedValue({ status: "sign_in_required", authorizationUrl: "https://claude.ai/oauth/authorize?client_id=test" });
flushSync(() => root.render(<Harness provider="anthropic" />));
await vi.waitFor(() => expect(host.querySelector('input[aria-label="Authorization code"]')).not.toBeNull());
const input = host.querySelector('input[aria-label="Authorization code"]') as HTMLInputElement;
flushSync(() => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "old-code");
input.dispatchEvent(new Event("input", { bubbles: true }));
});
expect(api.submitLocalLoginCode).not.toHaveBeenCalled();
input.select();
const paste = () => {
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", { value: { getData: () => " pasted-code#state\n" } });
input.dispatchEvent(event);
};
flushSync(() => { paste(); paste(); });
await vi.waitFor(() => expect(api.submitLocalLoginCode).toHaveBeenCalledWith("company", "attempt-1", "pasted-code#state"));
expect(api.submitLocalLoginCode).toHaveBeenCalledTimes(1);
expect(host.textContent).toContain("Finishing sign-in");
expect(host.querySelector('input[aria-label="Authorization code"]')).toBeNull();
expect(api.connectLocal).not.toHaveBeenCalled();
finishSubmit();
api.checkLocalLogin.mockResolvedValue({ status: "ready" });
window.dispatchEvent(new Event("focus"));
await vi.waitFor(() => expect(host.textContent).toContain("is signed in"));
});
it("hides a failed device prompt and lets the user restart sign-in", async () => {
api.checkLocalLogin.mockResolvedValue({ status: "sign_in_required", authorizationUrl: "https://auth.openai.com/codex/device", code: "OLD-CODE", error: "Sign-in ended. Start sign-in again." });
flushSync(() => root.render(<Harness />));
@@ -322,7 +322,7 @@ function modePlaceholder(mode: IssueWorkMode, agentName: string, mobile: boolean
if (mobile) {
if (mode === "planning") return `Plan with ${agentName}…`;
if (mode === "ask") return `Ask ${agentName}…`;
return `Message ${agentName}…`;
return `Work with ${agentName}`;
}
switch (mode) {
case "planning":
@@ -330,7 +330,7 @@ function modePlaceholder(mode: IssueWorkMode, agentName: string, mobile: boolean
case "ask":
return `Ask ${agentName} a question — read-only, nothing runs…`;
default:
return `Message ${agentName} — describe what you want done…`;
return `Work with ${agentName}`;
}
}