Files
PaperClipAI/server/src/services/onboarding-seed.ts
T
ce27dde855 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>
2026-11-17 16:52:35 -08:00

326 lines
12 KiB
TypeScript

import { and, eq, ne, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { agents, companyOnboardingSeeds, goals } from "@paperclipai/db";
import type { ApplyOnboardingSeed } from "@paperclipai/shared";
import { writePaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
import { findActiveServerAdapter } from "../adapters/registry.js";
import { agentService } from "./agents.js";
import { createAgentLifecycle, scheduleAgentLifecycle } from "./agent-lifecycle.js";
import { withDedicatedDbConnection } from "@paperclipai/db";
import { PAPERCLIP_CORE_SKILL_KEYS } from "./company-skills.js";
import { goalService } from "./goals.js";
import { readBuiltInAgentMarker } from "../lib/built-in-agent-metadata.js";
import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
/**
* Role assigned to the seeded lead agent. The seed's own `agent.role` is
* customer free text ("Chief of Staff") and lands on `title`; `role` stays the
* structural `ceo` key the org chart and default-instructions lookup read.
*/
const SEEDED_AGENT_ROLE = "ceo";
/**
* Adapter the seeded agent is created with. Mirrors the teams-catalog default
* (`claude_local`), which is the safe adapter for agents created server-side
* without a human running an environment test first.
*/
const FALLBACK_SEEDED_AGENT_ADAPTER_TYPE = "claude_local";
function seededAgentAdapterType() {
const configured = process.env.PAPERCLIP_ONBOARDING_SEED_ADAPTER_TYPE?.trim()
|| process.env.PAPERCLIP_TEAMS_CATALOG_DEFAULT_ADAPTER_TYPE?.trim()
|| FALLBACK_SEEDED_AGENT_ADAPTER_TYPE;
// Server-seeded onboarding deliberately stays on a direct adapter. Native
// runner rollout is an explicit post-onboarding configuration choice.
return configured === "paperclip_runner"
? FALLBACK_SEEDED_AGENT_ADAPTER_TYPE
: configured;
}
/**
* Adapter config for the seeded CEO. The default CEO instructions tell the
* agent to use the core paperclip skills (hiring, memory, coordination), and
* an agent's runtime only receives skills listed in its own desired set — so
* a seeded CEO with an empty adapter config arrives with zero skills and
* truthfully reports its own toolkit as not installed. Enable the core set
* whenever the seeded adapter supports skill sync.
*/
function seededAgentAdapterConfig(adapterType: string): Record<string, unknown> {
const adapter = findActiveServerAdapter(adapterType);
if (!adapter?.listSkills && !adapter?.syncSkills) return {};
return writePaperclipSkillSyncPreference(
{},
PAPERCLIP_CORE_SKILL_KEYS.map((key) => ({ key, versionId: null })),
);
}
/**
* Split a free-text mission into a goal title + description the same way the
* first-run wizard's `parseOnboardingGoalInput` does: first line is the title,
* the remainder is the description.
*/
export function parseSeedMission(raw: string): { title: string; description: string | null } {
const trimmed = raw.trim();
if (!trimmed) return { title: "", description: null };
const [firstLine, ...restLines] = trimmed.split(/\r?\n/);
const description = restLines.join("\n").trim();
return {
title: (firstLine ?? "").trim(),
description: description.length > 0 ? description : null,
};
}
export type OnboardingSeedApplication = {
revision: string;
/** False when the stored revision already matched and nothing was re-applied. */
changed: boolean;
goalId: string | null;
agentId: string | null;
issueId: string | null;
};
/**
* The actor fields the audit entry needs, as `getActorInfo` produces them.
* Narrowed to what {@link LogActivityInput} reads so the route can hand its
* actor straight through without the service depending on Express.
*/
export type OnboardingSeedAuditActor = {
actorType: "agent" | "user" | "system" | "plugin";
actorId: string;
agentId?: string | null;
runId?: string | null;
agentApiKeyId?: string | null;
};
export function onboardingSeedService(db: Db) {
async function readRecord(dbx: Db, companyId: string) {
return dbx
.select()
.from(companyOnboardingSeeds)
.where(eq(companyOnboardingSeeds.companyId, companyId))
.then((rows) => rows[0] ?? null);
}
async function goalStillExists(dbx: Db, companyId: string, goalId: string | null) {
if (!goalId) return false;
return dbx
.select({ id: goals.id })
.from(goals)
.where(and(eq(goals.id, goalId), eq(goals.companyId, companyId)))
.then((rows) => rows.length > 0);
}
/**
* The agent a re-push should update rather than duplicate: the one this
* seed created if it is still around, else a pre-existing lead the tenant
* already has. Built-in agents are excluded — they are provisioned by the
* platform and are not the customer's first hire.
*/
async function resolveTargetAgentId(dbx: Db, companyId: string, recordedAgentId: string | null) {
if (recordedAgentId) {
const recorded = await dbx
.select({ id: agents.id })
.from(agents)
.where(and(eq(agents.id, recordedAgentId), eq(agents.companyId, companyId)))
.then((rows) => rows[0] ?? null);
if (recorded) return recorded.id;
}
const candidates = await dbx
.select({ id: agents.id, metadata: agents.metadata })
.from(agents)
.where(and(
eq(agents.companyId, companyId),
eq(agents.role, SEEDED_AGENT_ROLE),
ne(agents.status, "terminated"),
));
return candidates.find((row) => !readBuiltInAgentMarker(row.metadata))?.id ?? null;
}
async function prepareAgent(dbx: Db, companyId: string, seed: ApplyOnboardingSeed, audit?: OnboardingSeedAuditActor) {
const existing = await readRecord(dbx, companyId);
if (existing?.revision === seed.revision) return existing.agentId;
const agentSvc = agentService(dbx);
const agentName = seed.agent?.name.trim() || null;
const agentRole = seed.agent?.role?.trim() || null;
// Agent → the customer's first hire and initial chat partner.
let agentId = await resolveTargetAgentId(dbx, companyId, existing?.agentId ?? null);
if (agentName) {
if (agentId) {
await agentSvc.update(agentId, { name: agentName, title: agentRole });
} else {
const adapterType = seededAgentAdapterType();
const created = await createAgentLifecycle(dbx).requestHire(companyId, {
name: agentName,
role: SEEDED_AGENT_ROLE,
title: agentRole,
adapterType,
adapterConfig: seededAgentAdapterConfig(adapterType),
runtimeConfig: {},
permissions: {},
status: "idle",
spentMonthlyCents: 0,
lastHeartbeatAt: null,
}, { createdByUserId: audit?.actorType === "user" ? audit.actorId : null });
agentId = created.id;
}
}
return agentId;
}
async function applyWithin(
dbx: Db,
companyId: string,
seed: ApplyOnboardingSeed,
preparedAgentId: string | null,
): Promise<OnboardingSeedApplication> {
const goalSvc = goalService(dbx);
const existing = await readRecord(dbx, companyId);
if (existing && existing.revision === seed.revision) {
return {
revision: existing.revision,
changed: false,
goalId: existing.goalId,
agentId: existing.agentId,
issueId: existing.issueId,
};
}
const mission = seed.mission?.trim() || null;
const agentName = seed.agent?.name.trim() || null;
const agentRole = seed.agent?.role?.trim() || null;
const firstTaskTitle = seed.firstTask?.title.trim() || null;
const firstTaskDetails = seed.firstTask?.details?.trim() || null;
// 1. Mission → the company-level goal the dashboard reads.
let goalId = existing?.goalId ?? null;
if (mission) {
const parsed = parseSeedMission(mission);
const target = (await goalStillExists(dbx, companyId, goalId))
? goalId
: (await goalSvc.getDefaultCompanyGoal(companyId))?.id ?? null;
if (target) {
await goalSvc.update(target, {
title: parsed.title,
description: parsed.description,
});
goalId = target;
} else {
const created = await goalSvc.create(companyId, {
title: parsed.title,
description: parsed.description,
level: "company",
status: "active",
});
goalId = created.id;
}
}
const agentId = preparedAgentId;
// Signup ideas are context for the first chat, never authorization to
// create execution work. Preserve old back-references without modifying
// historical tasks when Cloud pushes an updated seed.
const issueId = existing?.issueId ?? null;
// 4. Record the revision last. Everything above has to have landed before
// this row claims the seed is applied.
const now = new Date();
const values = {
companyId,
revision: seed.revision,
mission,
agentName,
agentRole,
firstTaskTitle,
firstTaskDetails,
goalId,
agentId,
issueId,
appliedAt: now,
updatedAt: now,
};
await dbx
.insert(companyOnboardingSeeds)
.values(values)
.onConflictDoUpdate({
target: companyOnboardingSeeds.companyId,
set: {
revision: values.revision,
mission: values.mission,
agentName: values.agentName,
agentRole: values.agentRole,
firstTaskTitle: values.firstTaskTitle,
firstTaskDetails: values.firstTaskDetails,
goalId: values.goalId,
agentId: values.agentId,
issueId: values.issueId,
appliedAt: values.appliedAt,
updatedAt: values.updatedAt,
},
});
return { revision: seed.revision, changed: true, goalId, agentId, issueId };
}
// Hire first. If the content transaction fails, a retry reuses the committed agent.
// The dedicated transaction holds only the workflow lock, not the hire writes.
async function apply(
companyId: string,
seed: ApplyOnboardingSeed,
audit?: OnboardingSeedAuditActor,
): Promise<OnboardingSeedApplication> {
// Collected inside the transaction, published only after it commits: the
// activity row is transactional but its realtime/plugin fan-out is not, and
// announcing a seed that then rolled back would be worse than announcing it
// late.
const publications: ActivityPublication[] = [];
const database = db;
const lockKey = `paperclip:onboarding-seed:${companyId}`;
return withDedicatedDbConnection(db, lockDb => lockDb.transaction(async lock => {
await lock.execute(sql`select pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`);
const preparedAgentId = await prepareAgent(database, companyId, seed, audit);
const result = await database.transaction(async (tx) => {
const dbx = tx as unknown as Db;
const applied = await applyWithin(dbx, companyId, seed, preparedAgentId);
if (applied.changed && audit) {
await logActivity(
dbx,
{
companyId,
actorType: audit.actorType,
actorId: audit.actorId,
agentId: audit.agentId,
runId: audit.runId,
agentApiKeyId: audit.agentApiKeyId,
action: "company.onboarding_seed_applied",
entityType: "company",
entityId: companyId,
details: {
revision: applied.revision,
goalId: applied.goalId,
agentId: applied.agentId,
issueId: applied.issueId,
},
},
publications,
);
}
return applied;
});
for (const publication of publications) publishActivity(publication);
if (result.agentId) scheduleAgentLifecycle(db, result.agentId);
return result;
}));
}
return { apply, get: (companyId: string) => readRecord(db, companyId) };
}