mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 11:54:35 +01:00
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 commit2dbad34445a 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 master23ce68a8dcand regenerated the SDK source registry from committed inputs. Worktree preflight, SDK source validation, and all 65 API/onboarding tests pass on final head2dbad34445. - On final head2dbad34445, 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 commit2dbad34445. 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:
57 files changed
+1156
-509
No files matched your search
@@ -155,7 +155,7 @@ import {
|
||||
).toBe(false);
|
||||
expect(
|
||||
(
|
||||
await issueService(db).list(companyId, { q: results[0].identifier! })
|
||||
await issueService(db).list(companyId, { q: results[0].title })
|
||||
).some((issue) => issue.id === results[0].id),
|
||||
).toBe(true);
|
||||
expect(
|
||||
@@ -1053,6 +1053,13 @@ describe("chat prompt policy", () => {
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("say plainly that no earlier version was saved, and ask the person for the text they want");
|
||||
});
|
||||
|
||||
it("uses the company prefix for links in an unnumbered standing chat", () => {
|
||||
const prompt = buildPaperclipTaskMarkdown({ companyPrefix: "BOB", coordinatorWorkspace: true,
|
||||
issue: { id: "chat", identifier: null, title: "Chat", workMode: "standard", conversationAgentId: "agent" } });
|
||||
expect(prompt).toContain("/BOB/agents/");
|
||||
expect(prompt).not.toContain("/<prefix>/");
|
||||
});
|
||||
|
||||
it("points chat at the teams catalog for ready-made teams and stops the search there", () => {
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("Ready-made teams are installable packages in Paperclip's teams catalog");
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("list the catalog with GET /api/teams/catalog");
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { agents, agentWakeupRequests, authUsers, companies, companyOnboardingSeeds, goals, heartbeatRuns, issues, projects } from "@paperclipai/db";
|
||||
import { onboardingChatRoutes } from "../routes/onboarding-chat.js";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
|
||||
import { documentService } from "../services/documents.js";
|
||||
import { heartbeatService } from "../services/heartbeat.js";
|
||||
import { ONBOARDING_CHAT_GREETING_REASON } from "../services/onboarding-chat-prompt.js";
|
||||
import { prepareConversationTurn, settleConversationTurn } from "../services/agent-conversations.js";
|
||||
import { createHeartbeatQueue } from "../services/heartbeat/queue.js";
|
||||
import { createHeartbeatQueueTestDependencies } from "./helpers/heartbeat-queue.js";
|
||||
import { describeEmbeddedPostgres, routeApp, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
|
||||
describeEmbeddedPostgres("onboarding chat", () => {
|
||||
const ctx = useEmbeddedPostgres("onboarding-chat");
|
||||
async function setup() {
|
||||
const owner = await seedCompanyWithBoardAccess(ctx.db, "New company");
|
||||
await ctx.db.insert(authUsers).values({ id: owner.userId, name: "Owner", email: `${owner.userId}@example.test`,
|
||||
createdAt: new Date(), updatedAt: new Date() });
|
||||
const [agent] = await ctx.db.insert(agents).values({ companyId: owner.companyId, name: "Ada", role: "ceo", status: "idle", adapterType: "process" }).returning();
|
||||
const wakeup = vi.fn(async (_agentId, options) => {
|
||||
await ctx.db.insert(agentWakeupRequests).values({ companyId: owner.companyId, agentId: agent.id,
|
||||
source: options.source, reason: options.reason, status: "pending", idempotencyKey: options.idempotencyKey });
|
||||
return { id: randomUUID() };
|
||||
});
|
||||
const app = routeApp(ctx.db, owner.actor, db => onboardingChatRoutes(db, { wakeup } as never));
|
||||
const path = `/api/companies/${owner.companyId}/chats/${agent.id}/onboarding`;
|
||||
return { ...owner, agent, wakeup, app, path };
|
||||
}
|
||||
|
||||
it("keeps chats out of the task sequence, including repeated and concurrent onboarding opens", async () => {
|
||||
const { companyId, app, path } = await setup();
|
||||
const opened = await Promise.all([request(app).post(path), request(app).post(path)]);
|
||||
for (const response of opened) {
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toMatchObject({ identifier: null, issueNumber: null });
|
||||
}
|
||||
const [colleague] = await ctx.db.insert(agents).values({ companyId, name: "Grace", role: "engineer", status: "idle", adapterType: "process" }).returning();
|
||||
const secondChat = await request(app).post(`/api/companies/${companyId}/chats/${colleague.id}/onboarding`);
|
||||
expect(secondChat.status).toBe(200);
|
||||
expect(secondChat.body).toMatchObject({ identifier: null, issueNumber: null });
|
||||
const [company] = await ctx.db.select().from(companies).where(eq(companies.id, companyId));
|
||||
expect(company.issueCounter).toBe(0);
|
||||
const tasks = await Promise.all(Array.from({ length: 3 }, (_, index) =>
|
||||
issueService(ctx.db).create(companyId, { title: `Accepted task ${index}`, status: "backlog" }),
|
||||
));
|
||||
expect(tasks.map(task => task.issueNumber).sort()).toEqual([1, 2, 3]);
|
||||
expect(tasks.map(task => task.identifier).sort()).toEqual([1, 2, 3].map(number => `${company.issuePrefix}-${number}`));
|
||||
});
|
||||
|
||||
it("opens one owner-bound chat with signup context, zero execution tasks, zero projects, and no early wake", async () => {
|
||||
const { companyId, userId, agent, app, path, wakeup } = await setup();
|
||||
await ctx.db.insert(goals).values({ companyId, title: "Launch a robotics newsletter", level: "company", status: "active" });
|
||||
await ctx.db.insert(companyOnboardingSeeds).values({ companyId, revision: "one", firstTaskTitle: "Draft an editorial plan", firstTaskDetails: "One page" });
|
||||
const [first, retry] = await Promise.all([request(app).post(path), request(app).post(path)]);
|
||||
expect(first.status).toBe(200);
|
||||
expect(retry.body.id).toBe(first.body.id);
|
||||
expect(first.body).toMatchObject({ conversationAgentId: agent.id, conversationUserId: userId,
|
||||
originKind: "onboarding_chat", projectId: null, parentId: null });
|
||||
expect(JSON.parse(first.body.description)).toMatchObject({ initialIdea: "Draft an editorial plan", initialDetails: "One page",
|
||||
goals: [{ title: "Launch a robotics newsletter" }] });
|
||||
expect(await issueService(ctx.db).list(companyId)).toEqual([]);
|
||||
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(0);
|
||||
expect(wakeup).not.toHaveBeenCalled();
|
||||
await Promise.all([request(app).post(`${path}/greeting`), request(app).post(`${path}/greeting`)]);
|
||||
expect(wakeup).toHaveBeenCalledTimes(1);
|
||||
expect(wakeup).toHaveBeenCalledWith(agent.id, expect.objectContaining({
|
||||
reason: ONBOARDING_CHAT_GREETING_REASON, requestedByActorId: userId, manualUserWake: true,
|
||||
contextSnapshot: expect.objectContaining({ issueId: first.body.id }),
|
||||
}));
|
||||
});
|
||||
|
||||
it("respects company access, keeps another person's chat private, and skips a welcome after a user reply", async () => {
|
||||
const { companyId, app, path, wakeup, actor } = await setup();
|
||||
const opened = await request(app).post(path);
|
||||
const stranger = routeApp(ctx.db, { ...actor, companyIds: [], memberships: [] }, db => onboardingChatRoutes(db, { wakeup } as never));
|
||||
expect((await request(stranger).post(path)).status).toBe(403);
|
||||
const colleague = routeApp(ctx.db, { ...actor, userId: "another-person" }, db => onboardingChatRoutes(db, { wakeup } as never));
|
||||
expect((await request(colleague).post(`${path}/greeting`)).status).toBe(404);
|
||||
await issueService(ctx.db).addComment(opened.body.id, "Interview me", { userId: actor.userId });
|
||||
expect((await request(app).post(`${path}/greeting`)).body.started).toBe(false);
|
||||
expect(wakeup).not.toHaveBeenCalled();
|
||||
expect(await ctx.db.select().from(issues).where(eq(issues.companyId, companyId))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(["request", "run"])("retries a timed-out welcome recorded on its %s", async timedOutRecord => {
|
||||
const { companyId, agent, app, path, wakeup } = await setup();
|
||||
await request(app).post(path);
|
||||
await request(app).post(`${path}/greeting`);
|
||||
const [receipt] = await ctx.db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, agent.id));
|
||||
const [run] = await ctx.db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, status: "timed_out",
|
||||
wakeupRequestId: receipt.id, finishedAt: new Date() }).returning();
|
||||
await ctx.db.update(agentWakeupRequests).set(timedOutRecord === "request" ? { status: "timed_out" } : { runId: run.id })
|
||||
.where(eq(agentWakeupRequests.id, receipt.id));
|
||||
expect((await request(app).post(`${path}/greeting`)).status).toBe(200);
|
||||
expect(wakeup).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each(["message", "new session"])("skips a queued welcome superseded by a %s before dispatch", async superseding => {
|
||||
const { companyId, agent, userId, app, path } = await setup();
|
||||
const opened = await request(app).post(path);
|
||||
const [receipt] = await ctx.db.insert(agentWakeupRequests).values({ companyId, agentId: agent.id,
|
||||
source: "on_demand", reason: ONBOARDING_CHAT_GREETING_REASON, status: "pending" }).returning();
|
||||
const [run] = await ctx.db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, status: "queued",
|
||||
wakeupRequestId: receipt.id, contextSnapshot: { issueId: opened.body.id, wakeReason: ONBOARDING_CHAT_GREETING_REASON } }).returning();
|
||||
if (superseding === "message") await issueService(ctx.db).addComment(opened.body.id, "Interview me", { userId });
|
||||
else await ctx.db.update(issues).set({ conversationSessionGeneration: 1 }).where(eq(issues.id, opened.body.id));
|
||||
const deps = createHeartbeatQueueTestDependencies(ctx.db);
|
||||
deps.getAgent.mockResolvedValue(agent);
|
||||
const queue = createHeartbeatQueue(ctx.db, deps);
|
||||
expect(await queue.claimQueuedRun(run)).toBeNull();
|
||||
expect((await ctx.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0])
|
||||
.toMatchObject({ status: "cancelled", startedAt: null, errorCode: "onboarding_welcome_superseded" });
|
||||
expect(deps.setWakeupStatus).toHaveBeenCalledWith(receipt.id, "skipped", expect.anything());
|
||||
expect(deps.releaseIssueExecutionAndPromote).toHaveBeenCalledWith(expect.objectContaining({ id: run.id }),
|
||||
expect.objectContaining({ suppressImmediateRecovery: true }));
|
||||
expect(deps.executeRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("admits a real greeting run without a synthetic human message", async () => {
|
||||
const { agent, actor, app, path, companyId } = await setup();
|
||||
const opened = await request(app).post(path);
|
||||
const provider = express();
|
||||
provider.use(express.json());
|
||||
provider.post("/reply", async (req, res) => {
|
||||
await issueService(ctx.db).addComment(opened.body.id, "Welcome! What would you like to achieve?", { agentId: agent.id, runId: req.body.runId });
|
||||
res.json({ ok: true });
|
||||
});
|
||||
const listener = provider.listen(0, "127.0.0.1");
|
||||
await new Promise<void>(resolve => listener.once("listening", resolve));
|
||||
const port = (listener.address() as { port: number }).port;
|
||||
const script = `fetch("http://127.0.0.1:${port}/reply", {method:"POST", headers:{"content-type":"application/json"}, body:JSON.stringify({runId:process.env.PAPERCLIP_RUN_ID})}).then(r=>{if(!r.ok)process.exitCode=1})`;
|
||||
await ctx.db.update(agents).set({ adapterConfig: { command: process.execPath, args: ["-e", script] },
|
||||
runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: true } } }).where(eq(agents.id, agent.id));
|
||||
const runtimeApp = routeApp(ctx.db, actor, db => onboardingChatRoutes(db, heartbeatService(db)));
|
||||
try {
|
||||
const response = await request(runtimeApp).post(`${path}/greeting`);
|
||||
expect(response.status).toBe(200);
|
||||
await vi.waitFor(async () => {
|
||||
const [run] = await ctx.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agent.id));
|
||||
expect(run?.status).toBe("succeeded");
|
||||
expect(run?.contextSnapshot).toMatchObject({ issueId: opened.body.id, conversationMode: true });
|
||||
const current = await issueService(ctx.db).getById(opened.body.id);
|
||||
expect(current?.conversationState).toBe("waiting");
|
||||
expect(current?.executionRunId).toBeNull();
|
||||
}, { timeout: 10000 });
|
||||
expect(await issueService(ctx.db).list(companyId)).toEqual([]);
|
||||
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(0);
|
||||
} finally { await new Promise<void>(resolve => listener.close(() => resolve())); }
|
||||
});
|
||||
|
||||
it.each([false, true])("keeps a reply sent during the welcome actionable (reply=%s)", async hasReply => {
|
||||
const { app, path, companyId, agent, userId } = await setup();
|
||||
const opened = await request(app).post(path);
|
||||
const [run] = await ctx.db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, status: "running",
|
||||
contextSnapshot: { issueId: opened.body.id, wakeReason: ONBOARDING_CHAT_GREETING_REASON } }).returning();
|
||||
const prepared = await prepareConversationTurn(ctx.db, run);
|
||||
if (hasReply) await issueService(ctx.db).addComment(opened.body.id, "Interview me", { userId });
|
||||
await issueService(ctx.db).addComment(opened.body.id, "Welcome!", { agentId: agent.id, runId: run.id });
|
||||
expect(await settleConversationTurn(ctx.db, { ...run, status: "succeeded", contextSnapshot: prepared.context })).toBe(true);
|
||||
const current = await issueService(ctx.db).getById(opened.body.id);
|
||||
expect(current?.conversationState).toBe(hasReply ? "active" : "waiting");
|
||||
});
|
||||
|
||||
it("keeps a suggestion as chat context until acceptance creates its standalone task once", async () => {
|
||||
const { app, path, companyId, agent, userId } = await setup();
|
||||
const opened = await request(app).post(path);
|
||||
const chat = (await issueService(ctx.db).getById(opened.body.id))!;
|
||||
const interactions = issueThreadInteractionService(ctx.db);
|
||||
const plan = "Goal: launch a newsletter. Done: a one-page editorial plan with three topics and a publishing schedule.";
|
||||
const proposal = await interactions.create(chat, { kind: "suggest_tasks", idempotencyKey: "editorial-plan",
|
||||
payload: { version: 1, tasks: [{ clientKey: "plan", title: "Draft the editorial plan", description: plan,
|
||||
initialPlan: plan, assigneeAgentId: agent.id }] } }, { userId });
|
||||
expect(await issueService(ctx.db).list(companyId)).toEqual([]);
|
||||
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(0);
|
||||
const accepted = await interactions.acceptInteraction(chat, proposal.id, {}, { userId });
|
||||
expect(accepted.createdIssues).toHaveLength(1);
|
||||
const [task] = await issueService(ctx.db).list(companyId);
|
||||
expect(task).toMatchObject({ title: "Draft the editorial plan", parentId: null, assigneeAgentId: agent.id, issueNumber: 1 });
|
||||
expect((await documentService(ctx.db).getIssueDocumentByKey(task.id, "plan"))?.body).toBe(plan);
|
||||
await expect(interactions.acceptInteraction(chat, proposal.id, {}, { userId })).rejects.toThrow("already been resolved");
|
||||
expect(await issueService(ctx.db).list(companyId)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -71,7 +71,7 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
|
||||
// polling. A lazy receiver that applied the seed in the background would
|
||||
// fail here on any machine — which is the point, since Cloud gates the
|
||||
// redirect into the tenant dashboard on this response.
|
||||
it("applies the mission, the first agent and the first task before it answers", async () => {
|
||||
it("applies the mission and first agent, retaining the initial idea without creating work", async () => {
|
||||
const { companyId, app } = await seedCompany();
|
||||
|
||||
const response = await post(app, companyId, SEED);
|
||||
@@ -104,17 +104,8 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
|
||||
},
|
||||
});
|
||||
|
||||
const companyIssues = await ctx.db.select().from(issues).where(eq(issues.companyId, companyId));
|
||||
expect(companyIssues).toHaveLength(1);
|
||||
expect(companyIssues[0]?.title).toBe(SEED.firstTask.title);
|
||||
expect(companyIssues[0]?.description).toBe(SEED.firstTask.details);
|
||||
expect(companyIssues[0]?.assigneeAgentId).toBe(companyAgents[0]?.id);
|
||||
expect(companyIssues[0]?.goalId).toBe(companyGoals[0]?.id);
|
||||
|
||||
const companyProjects = await ctx.db.select().from(projects).where(eq(projects.companyId, companyId));
|
||||
expect(companyProjects).toHaveLength(1);
|
||||
expect(companyProjects[0]?.name).toBe("Onboarding");
|
||||
expect(companyIssues[0]?.projectId).toBe(companyProjects[0]?.id);
|
||||
expect(await ctx.db.select().from(issues).where(eq(issues.companyId, companyId))).toHaveLength(0);
|
||||
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(0);
|
||||
|
||||
const record = await ctx.db
|
||||
.select()
|
||||
@@ -123,7 +114,8 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
|
||||
expect(record).toHaveLength(1);
|
||||
expect(record[0]?.revision).toBe(SEED.revision);
|
||||
expect(record[0]?.agentId).toBe(companyAgents[0]?.id);
|
||||
expect(record[0]?.issueId).toBe(companyIssues[0]?.id);
|
||||
expect(record[0]?.issueId).toBeNull();
|
||||
expect(record[0]).toMatchObject({ firstTaskTitle: SEED.firstTask.title, firstTaskDetails: SEED.firstTask.details });
|
||||
});
|
||||
|
||||
it("uses the qualified Claude default for an unsupported seed adapter override", async () => {
|
||||
@@ -182,9 +174,9 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
|
||||
expect(replay.body.issueId).toBe(first.body.issueId);
|
||||
|
||||
expect(await ctx.db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(1);
|
||||
expect(await ctx.db.select().from(issues).where(eq(issues.companyId, companyId))).toHaveLength(1);
|
||||
expect(await ctx.db.select().from(issues).where(eq(issues.companyId, companyId))).toHaveLength(0);
|
||||
expect(await ctx.db.select().from(goals).where(eq(goals.companyId, companyId))).toHaveLength(1);
|
||||
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(1);
|
||||
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("updates in place when the customer edits their answers and the revision changes", async () => {
|
||||
@@ -210,8 +202,9 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
|
||||
expect(companyAgents[0]?.title).toBe("Head of Ops");
|
||||
|
||||
const companyIssues = await ctx.db.select().from(issues).where(eq(issues.companyId, companyId));
|
||||
expect(companyIssues).toHaveLength(1);
|
||||
expect(companyIssues[0]?.title).toBe("Draft the two-page strategy");
|
||||
expect(companyIssues).toHaveLength(0);
|
||||
const [saved] = await ctx.db.select().from(companyOnboardingSeeds).where(eq(companyOnboardingSeeds.companyId, companyId));
|
||||
expect(saved).toMatchObject({ firstTaskTitle: "Draft the two-page strategy", firstTaskDetails: "Two pages now" });
|
||||
|
||||
const companyGoals = await ctx.db.select().from(goals).where(eq(goals.companyId, companyId));
|
||||
expect(companyGoals).toHaveLength(1);
|
||||
@@ -377,7 +370,7 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
|
||||
expect(companyGoals[0]?.title).toBe("Body-supplied mission");
|
||||
});
|
||||
|
||||
it("reuses an existing Onboarding project instead of creating a second one", async () => {
|
||||
it("leaves an existing Onboarding project alone", async () => {
|
||||
const { companyId, app } = await seedCompany();
|
||||
await ctx.db.insert(projects).values({
|
||||
companyId,
|
||||
@@ -391,7 +384,7 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
|
||||
const companyProjects = await ctx.db.select().from(projects).where(eq(projects.companyId, companyId));
|
||||
expect(companyProjects).toHaveLength(1);
|
||||
const companyIssues = await ctx.db.select().from(issues).where(eq(issues.companyId, companyId));
|
||||
expect(companyIssues[0]?.projectId).toBe(companyProjects[0]?.id);
|
||||
expect(companyIssues).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("does not duplicate entities when two identical pushes race", async () => {
|
||||
@@ -412,42 +405,21 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
|
||||
|
||||
expect(await ctx.db.select().from(goals).where(eq(goals.companyId, companyId))).toHaveLength(1);
|
||||
expect(await ctx.db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(1);
|
||||
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(1);
|
||||
expect(await ctx.db.select().from(issues).where(eq(issues.companyId, companyId))).toHaveLength(1);
|
||||
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(0);
|
||||
expect(await ctx.db.select().from(issues).where(eq(issues.companyId, companyId))).toHaveLength(0);
|
||||
expect(await ctx.db.select().from(companyOnboardingSeeds)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("refreshes a first task's assignee and goal when a later revision adds them", async () => {
|
||||
it("does not update legacy onboarding work when a later seed revises the idea", async () => {
|
||||
const { companyId, app } = await seedCompany();
|
||||
|
||||
// First push seeds a task but no agent and no mission, so the issue is
|
||||
// created unassigned and goal-less.
|
||||
const taskOnly = await post(app, companyId, {
|
||||
revision: "1".repeat(32),
|
||||
firstTask: { title: "Draft the strategy" },
|
||||
});
|
||||
expect(taskOnly.status).toBe(200);
|
||||
|
||||
const beforeIssue = (await ctx.db.select().from(issues).where(eq(issues.companyId, companyId)))[0];
|
||||
expect(beforeIssue?.assigneeAgentId).toBeNull();
|
||||
|
||||
// A later revision supplies the mission and the agent. The existing task is
|
||||
// updated in place, and must pick up the newly-created assignee and goal
|
||||
// rather than reporting them on the seed record while the issue row stays
|
||||
// stale.
|
||||
const withAgent = await post(app, companyId, {
|
||||
revision: "2".repeat(32),
|
||||
mission: "Make robotics boring enough to trust",
|
||||
agent: { name: "Ada", role: "Chief of Staff" },
|
||||
firstTask: { title: "Draft the strategy" },
|
||||
});
|
||||
expect(withAgent.status).toBe(200);
|
||||
|
||||
const companyIssues = await ctx.db.select().from(issues).where(eq(issues.companyId, companyId));
|
||||
expect(companyIssues).toHaveLength(1);
|
||||
const companyAgents = await ctx.db.select().from(agents).where(eq(agents.companyId, companyId));
|
||||
const companyGoals = await ctx.db.select().from(goals).where(eq(goals.companyId, companyId));
|
||||
expect(companyIssues[0]?.assigneeAgentId).toBe(companyAgents[0]?.id);
|
||||
expect(companyIssues[0]?.goalId).toBe(companyGoals[0]?.id);
|
||||
const [legacy] = await ctx.db.insert(issues).values({ companyId, title: "Already accepted work", status: "todo", issueNumber: 1 }).returning();
|
||||
await ctx.db.insert(companyOnboardingSeeds).values({ companyId, revision: "old", issueId: legacy.id });
|
||||
const response = await post(app, companyId, SEED);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.issueId).toBe(legacy.id);
|
||||
const [retained] = await ctx.db.select().from(issues).where(eq(issues.companyId, companyId));
|
||||
expect(retained.title).toBe("Already accepted work");
|
||||
expect(retained.assigneeAgentId).toBeNull();
|
||||
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -84,6 +84,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"link-previews.ts": "/api",
|
||||
"managed-agent-profiles.ts": "/api",
|
||||
"onboarding-seed.ts": "/api",
|
||||
"onboarding-chat.ts": "/api",
|
||||
"openapi.ts": "/api",
|
||||
"plugin-ui-static.ts": "/api",
|
||||
"plugins.ts": "/api",
|
||||
@@ -1308,6 +1309,22 @@ describe("openapi routes", () => {
|
||||
expect(callback.parameters).toContainEqual(expect.objectContaining({ in: "query", name: "state", required: true, schema: expect.objectContaining({ maxLength: 128 }) }));
|
||||
});
|
||||
|
||||
it("documents board-owned onboarding chat and visible welcome operations", () => {
|
||||
const { spec } = loadSpecRoutes();
|
||||
const base = "/api/companies/{companyId}/chats/{agentRef}/onboarding";
|
||||
for (const path of [base, `${base}/greeting`]) {
|
||||
const operation = spec.paths[path]?.post;
|
||||
expect(operation).toBeDefined();
|
||||
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
||||
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
||||
expect(operation.responses["200"]).toBeDefined();
|
||||
expect(operation.responses["403"]).toBeDefined();
|
||||
expect(operation.responses["404"]).toBeDefined();
|
||||
}
|
||||
expect(spec.paths[`${base}/greeting`].post.responses["200"].content["application/json"].schema)
|
||||
.toMatchObject({ type: "object", required: ["started"], properties: { started: { type: "boolean" } } });
|
||||
});
|
||||
|
||||
it("covers the mounted server routes exactly", () => {
|
||||
const {
|
||||
routes: actualRoutes,
|
||||
|
||||
Reference in new issue
Block a user