Files
PaperClipAI/ui/src/lib/onboarding-route.ts
T
5acf56658b feat(onboarding): first task opens as a chat with a chief of staff (#13068)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Onboarding ends by handing a new user to their first agent on a
seeded first task
> - Today the wizard asks for a mission up front, the UI composes what
the agent is told, and the agent starts running before the user says
anything
> - New users get a cold, ticket-shaped start, and nobody can edit the
agent's brief or persona without a code change
> - This pull request makes the first task a short chat: a four-step
wizard, a chief-of-staff persona, a greeting plus a two-option opening
card, server-owned markdown texts, and no run until the user answers
> - It also gives question cards one consistent action row (Cancel /
Skip / Next), makes agent hires idempotent within a run, and turns the
Paperclip Runner flag on by default for self-hosted instances
> - The benefit is a first run the user steers, with texts a board
operator can edit as markdown

## Linked Issues or Issue Description

No public GitHub issue exists for this change. The feature request
fields follow.

Related PRs and issues:

- Refs #11043 — an earlier draft of the first-task onboarding
experience. This PR supersedes it.
- Refs #11280 — a report about the onboarding first-task route test.
This PR extends that test file.

### Subsystem affected

Onboarding wizard, the seeded first task and its texts, task-chat
question cards, agent hiring, and the instance experimental settings.

### Problem or motivation

The onboarding wizard collects a mission through two extra steps and a
questionnaire. The UI then composes the first agent's instructions and
the first task description from those answers. The first task wakes the
agent at once, so the agent runs and posts before the user types a word.
Board operators cannot change the greeting, the brief, or the persona
without editing TypeScript. Question cards in chat behave differently
per adapter, and a single-select pick submits on click. A misread hire
response could create a duplicate agent that the creating agent cannot
remove.

### Proposed solution

Reduce the wizard to four steps and stop the UI from authoring agent
texts. Move the greeting, the brief, the chief-of-staff persona, and the
opening question into markdown and JSON files that the server loads at
runtime. Seed the persona onto the first agent through an explicit hire
marker. Do not wake the first task until the user answers the opening
card or types. Give every question card the same Cancel / Skip / Next
actions. Add an experimental toggle that switches the single-task
proposal between one confirmation card and a plan document with a
checkbox card. Make agent hires idempotent within a run.

### Alternatives considered

- Keep the mission questionnaire and feed it into the brief. Rejected:
the agent asks better questions in chat, and the wizard gets shorter.
- Keep the first task open-ended with a plain composer. Rejected: a
two-option card gives the user a clear first move.
- Derive the plan-document behaviour from the user's intent only.
Rejected in favour of an explicit experimental toggle so operators can
choose.
- Key the "pick does not submit" behaviour off the presence of a submit
label. Rejected: several adapters set a submit label on single-select
cards, and their cards would change behaviour.

### Roadmap alignment

`ROADMAP.md` lists no planned core work on onboarding or the first task.
This change refines the existing flow and does not duplicate planned
work.

## What Changed

- Wizard: four steps (Name your organization, Create your first agent,
Connect a model, Review). The front door and both mission steps are
removed with their state and saved-progress keys. The UI no longer
composes the first agent's instructions or the first task description.
- Server-owned texts: the greeting, the brief with two proposal
variants, the chief-of-staff persona, the opening question, and a README
live in `server/src/onboarding-assets/first-task/` and load at runtime.
The create route stores the assembled brief and ignores any client
description.
- Persona seed: an `onboardingFirstAgent` marker on the hire lets the
server seed the chief-of-staff persona over the first agent's entry
file. Board-authored hires only. The persona tells the agent the hire
response shape and to list agents before it acts on an unclear result.
- No auto-run: the first task does not queue an assignment wake. The
stranded-assignment reconciler leaves it idle until a user comment or an
answered card exists.
- Opening card: the server seeds an `ask_user_questions` card right
after the greeting with two options: "Interview me and propose a plan
and an agent team to execute it." and "I have a task in mind" with free
text. Answering wakes the agent.
- Experimental toggle `enableFirstTaskPlanProposal` (default off): the
single-task proposal is one confirmation card, or a plan document plus a
checkbox card when on.
- Question cards: every `ask_user_questions` card renders Cancel, Skip,
and Next (the submit label on the last question). Skip hides on required
questions. Picking an option no longer advances or submits by itself.
- Wizard guards: the dashboard's agentless offer ignores a cached empty
agent list while a refetch is in flight. The hire step adopts an agent
that already carries the typed name instead of hiring "Name 2".
- Agent hires are idempotent within a run: a retry of the identical
request under the same run id returns the existing agent with `200` and
`idempotent: true`. The fingerprint covers the whole validated request,
so a corrected payload is a new hire. Lookup, create, and activity
record run under one lock per company and run, so overlapping retries
cannot both create.
- The Paperclip Runner experimental flag defaults to on for self-hosted
instances. Cloud keeps its declared default: a managed instance whose
tenant row and managed overlay omit the flag resolves it to off.
- Question cards: a send that finds an earlier required answer missing
returns to that question with a message instead of failing silently.
- The two onboarding e2e specs follow the new wizard: the front door and
growth intake shots are gone, and the planning-mode spec dismisses the
opening card before it reads the composer.
- Docs: `docs/board-operator/editing-first-task-texts.md` explains how
to edit the texts and the toggle.

## Verification

Commands, run from the repo root:

```
pnpm -r --filter './packages/*' --filter '!@paperclipai/paperclip-runner' build
pnpm --filter ./packages/shared typecheck
pnpm --filter ./ui typecheck
pnpm --filter ./server exec tsc --noEmit
pnpm check:token-gates
pnpm --filter ./ui exec vitest run OnboardingWizard onboarding QuestionForm InteractionCard ProtocolCard TaskChatComposer Dashboard feature
PAPERCLIP_IN_WORKTREE=false pnpm --filter ./server exec vitest run onboarding-first-task heartbeat-process-recovery agent-hire-idempotency instance-settings agent-skills-routes issue-onboarding onboarding-greeting --testTimeout=90000
```

Results on this branch:

- Typecheck is clean for shared, ui, and server.
- Token gates: 4 of 4 clean.
- UI: 344 tests pass across 23 files.
- Server: all suites pass. The first test in `agent-skills-routes` has
its own 10 s cap and needs about 15 s on my laptop for the app cold
start. It passes with a longer cap. This PR does not change that cap.

Manual steps on a dev instance:

1. Open `/onboarding`. Confirm four steps: Name your organization,
Create your first agent, Connect a model, Review.
2. Finish the wizard. Confirm the first task shows the chief-of-staff
greeting and the opening card with two options. Confirm no run starts.
3. Pick "Interview me…". Confirm no run starts. Press Continue. Confirm
a run starts and an interview card of 3–4 questions arrives.
4. On a fresh organization, pick "I have a task in mind", type a task,
and press Continue. Confirm a proposal arrives as one confirmation card.
5. Turn on Settings → Experimental → "First task: propose with a plan
document" and repeat step 4. Confirm a plan document and a checkbox card
arrive.
6. Visit the dashboard after the hire. Confirm the wizard does not
reopen and one agent exists.
7. Open any question card. Confirm Cancel returns the plain composer
with the card still pending, Skip advances an optional question, and
Next moves to the next question.

Design reference with flow diagrams, chat mock-ups, and live captures:
https://pages.paperclip.ing/first-task-flow/proposed/

## Risks

- `pnpm dev` now builds the runner daemon because the Paperclip Runner
flag is on by default. Developers without a Rust toolchain must set
`PAPERCLIP_RUNNER_BINARY` or turn the flag off. Self-hosted instances
that never set the flag now let qualified agents use the runner.
- The wizard drops the mission steps and their saved-progress keys. A
user who is mid-wizard on an older build restarts at step 1 after an
upgrade. Existing organizations are not touched.
- The first task no longer runs on its own. A user who neither answers
the card nor types sees no agent activity. This is intended.
- The persona seed applies only to hires that carry the marker from the
wizard. API hires are unchanged.
- Hire idempotency is scoped to one run id and to the exact request.
Retries across runs, or with a changed payload, still create a second
agent. The lock is per server process, which matches how an instance
serves its API.
- Single-select question cards no longer submit on pick. Users of
adapters that relied on that behaviour now press Next.
- No database migrations.

> 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 (Anthropic) through Claude Code. `claude-fable-5-1` with
extended thinking, tool use, and code execution wrote most commits.
`claude-opus-4-8` wrote the toggle, texts, wizard, and idempotency
commits, as the `Co-Authored-By` trailers show.

## 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>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-08 20:19:14 -07:00

217 lines
8.1 KiB
TypeScript

type OnboardingRouteCompany = {
id: string;
issuePrefix: string;
};
export function isOnboardingPath(pathname: string): boolean {
const segments = pathname.split("/").filter(Boolean);
if (segments.length === 1) {
return segments[0]?.toLowerCase() === "onboarding";
}
if (segments.length === 2) {
return segments[1]?.toLowerCase() === "onboarding";
}
return false;
}
/**
* The company prefix in an onboarding pathname, or undefined when there is
* none.
*
* `OnboardingWizard` renders as a full-screen overlay beside `<Routes>` rather
* than inside it (`App.tsx`), so it has no route match and `useParams()`
* returns nothing there — `companyPrefix` was always undefined and the wizard
* always opened at step 1, even when the URL named a company. `useLocation()`
* needs only the router, not a match, so the pathname is the signal that
* survives where params do not.
*
* Deliberately parses the same shape as {@link isOnboardingPath}: the prefix is
* the first of exactly two segments. Anything else has no prefix to read.
*/
export function companyPrefixFromOnboardingPath(pathname: string): string | undefined {
const segments = pathname.split("/").filter(Boolean);
if (segments.length !== 2) return undefined;
if (segments[1]?.toLowerCase() !== "onboarding") return undefined;
return segments[0];
}
/** The wizard step that asks for the company's mission. */
export const ONBOARDING_MISSION_STEP = 2;
/**
* The wizard step that asks for the first agent.
*
* A company that already has its mission has answered steps 1 and 2 — Cloud
* collects both at signup and the seed writes the mission as a company-level
* goal. Opening such a company on "what is the mission?" asks the customer
* something they answered minutes earlier on another origin, which is the
* seam the seeded arc exists to remove.
*/
export const ONBOARDING_AGENT_STEP = 3;
export type ExistingCompanyOnboardingStep =
| typeof ONBOARDING_MISSION_STEP
| typeof ONBOARDING_AGENT_STEP;
/**
* The step a company that already exists belongs on: always the agent.
*
* This used to branch on whether the company had a mission, sending a company
* without one to `ONBOARDING_MISSION_STEP` first. Onboarding no longer asks —
* the mission is collected later, in the tenant app — so the branch had become
* a way to reach a question the arc had stopped asking. It survived because
* Cloud's naming screen dropped its own mission field, which left every
* Cloud-created company looking mission-less on arrival, and so every walk
* detoured through a step the design had removed.
*
* The parameter is gone rather than ignored: callers were running a goal lookup
* to compute it, and an argument that cannot change the answer is an invitation
* to keep computing it.
*/
export function onboardingStepForCompany(): ExistingCompanyOnboardingStep {
return ONBOARDING_AGENT_STEP;
}
export function resolveRouteOnboardingOptions(params: {
pathname: string;
companyPrefix?: string;
companies: OnboardingRouteCompany[];
/**
* Whether this instance is a Cloud-managed stack. Company creation lives on
* Cloud there — POST /companies is a 403 floor — so a route that cannot name
* an existing company must never open the create wizard: it would be a dead
* end wearing a form. A managed stack holds exactly one company, so the
* useful reading of a bare `/onboarding` is that company's agent arc.
*/
cloudManaged?: boolean;
}): { initialStep: 1 | ExistingCompanyOnboardingStep; companyId?: string } | null {
const { pathname, companyPrefix, companies, cloudManaged } = params;
if (!isOnboardingPath(pathname)) return null;
const managedFallback = (): { initialStep: ExistingCompanyOnboardingStep; companyId?: string } | null =>
companies.length === 1
? { initialStep: onboardingStepForCompany(), companyId: companies[0]!.id }
: null;
if (!companyPrefix) {
if (cloudManaged) return managedFallback();
return { initialStep: 1 };
}
const matchedCompany =
companies.find(
(company) =>
company.issuePrefix.toUpperCase() === companyPrefix.toUpperCase(),
) ?? null;
if (!matchedCompany) {
if (cloudManaged) return managedFallback();
return { initialStep: 1 };
}
return {
initialStep: onboardingStepForCompany(),
companyId: matchedCompany.id,
};
}
/**
* Whether a company with no agents should be sent to onboarding rather than
* left on the dashboard.
*
* A company with no agent cannot do anything: no runs, no tasks, nothing to
* show. The dashboard already says so in a banner with a "Create one here"
* link, which asks the customer to notice a problem the product could simply
* fix for them.
*
* It also closes the gap a Cloud-provisioned stack falls into. Cloud creates
* the company before the tenant boots, so `shouldRedirectCompanylessRouteToOnboarding`
* never fires — a seeded customer arrives at an empty dashboard having just
* answered a signup flow, and nothing routes them onward.
*
* `agentsLoaded` is required rather than optional on purpose. Callers hold
* agents as `Agent[] | undefined` while the query is in flight, and an absent
* list reads exactly like an empty one — redirecting on that would bounce
* every user through onboarding on each cold load.
*
* `agentsRefreshing` covers the other way a count of zero lies: a cached list
* that is being refetched. The wizard hires the first agent and then lands on
* the first task; a dashboard reached from there can hold the empty list it
* cached before the hire, with the refetch still in flight. Offering on that
* list reopens "Create your first agent" for a company that just got one,
* and the customer walks the agent and model steps a second time.
*/
export function shouldRouteAgentlessCompanyToOnboarding(params: {
pathname: string;
agentsLoaded: boolean;
agentsRefreshing?: boolean;
agentCount: number;
}): boolean {
if (!params.agentsLoaded) return false;
if (params.agentsRefreshing) return false;
if (params.agentCount > 0) return false;
// Already there. Redirecting onto the path we are on is the loop that
// "finished the wizard but created no agent" would otherwise spin in.
return !isOnboardingPath(params.pathname);
}
/**
* Whether the wizard's Back button is offered on the current step.
*
* A run never walks back behind the step it entered on: those steps either do
* not apply to it (an existing company is already named, and its mission is
* hydrated rather than asked for) or were completed elsewhere. Walking back
* into step 1 while holding a company is the sharpest case — that step creates
* a company, so it would make a second one.
*/
export function canGoBackFromOnboardingStep(params: {
currentStep: number;
entryStep: number;
}): boolean {
return params.currentStep > 1 && params.currentStep > params.entryStep;
}
/**
* Whether a completed progress-bar segment can be clicked to jump back to it.
*
* Same bound as {@link canGoBackFromOnboardingStep}. The progress bar applies
* only the "already completed" half of the rule, which lets a run entered on
* an existing company jump to the name and mission steps the Back button
* deliberately withholds.
*/
export function canJumpToOnboardingStep(params: {
targetStep: number;
currentStep: number;
entryStep: number;
}): boolean {
return (
params.targetStep < params.currentStep && params.targetStep >= params.entryStep
);
}
export function shouldRedirectCompanylessRouteToOnboarding(params: {
pathname: string;
hasCompanies: boolean;
}): boolean {
return !params.hasCompanies && !isOnboardingPath(params.pathname);
}
/**
* Whether the onboarding wizard is currently covering the screen — either
* opened explicitly via the dialog context or auto-opened from the
* /onboarding route and not yet dismissed. While this is true the route
* launcher must not render interactive content, so it hands off fully to the
* full-screen wizard instead of staying clickable/focusable behind it
* (PAP-52).
*/
export function isOnboardingWizardActive(params: {
onboardingOpen: boolean;
routeDismissed: boolean;
}): boolean {
return params.onboardingOpen || !params.routeDismissed;
}