diff --git a/doc/onboarding-chat.md b/doc/onboarding-chat.md new file mode 100644 index 00000000000..deaf5e791b7 --- /dev/null +++ b/doc/onboarding-chat.md @@ -0,0 +1,32 @@ +# Starting in chat + +Finishing company onboarding opens the new agent's standing chat. It creates no +execution task or project. Chat uses the existing owner-bound conversation record +and is excluded from task collections. New chats have no task number or identifier +and do not advance the company's task counter, so the first accepted task is +`-1`. Existing numbered records keep their identifiers. Existing onboarding +tasks remain readable. + +The wizard prepares the conversation before navigating. After its content paints +in a visible tab, the UI requests a live welcome through the normal agent queue. +Hidden tabs wait for visibility. Unmount cancels an unsent request. A database +advisory lock and durable wake receipts prevent concurrent requests and refreshes +from starting duplicate welcomes; failed attempts can be retried. A user message +or a new conversation session supersedes a welcome that has not started. + +The welcome receives the organization, company goals and any Cloud signup idea. +Cloud seeds retain initial task titles/details as context without creating or +editing projects and tasks. Existing seed task references are preserved. + +Subsequent chat turns gather a goal and clear exit criteria. The agent offers an +interview and starts one only when requested; ordinary conversation works too. +It proposes scoped work through `suggest_tasks`. Recorded acceptance creates the +selected tasks through the existing atomic handoff. An explicit task-creation +request can create work directly. Project selection, budgets and hiring gates +retain their normal authority. The conversation remains available after handoff. + +Local subscription setup waits for verified sign-in before enabling Connect. +Pasting a Claude authorization code submits it automatically and shows a finishing +state; a rejected code offers a fresh sign-in immediately. Switching providers +clears the previous provider's model so subscription verification uses a +compatible model. diff --git a/docs/api/issues.md b/docs/api/issues.md index dac6071142c..209643be83c 100644 --- a/docs/api/issues.md +++ b/docs/api/issues.md @@ -5,6 +5,20 @@ summary: Issue CRUD, checkout/release, comments, documents, interactions, and at Issues are the unit of work in Paperclip. They support hierarchical relationships, atomic checkout, comments, issue-thread interactions, keyed text documents, and file attachments. +## Onboarding chat + +Board users open their own onboarding conversation with +`POST /api/companies/{companyId}/chats/{agentRef}/onboarding` (empty body). +It returns a conversation record, creates no execution task or project, and does +not start an agent turn. Existing conversations are reused. + +After the thread is visible, call +`POST /api/companies/{companyId}/chats/{agentRef}/onboarding/greeting` (empty body). +It returns `{ "started": true }` when the welcome is queued or already owed, or +`{ "started": false }` when unnecessary. Requests are company-scoped and +owner-bound. Refreshes do not repeat a successful welcome. Normal pause, budget +and agent admission gates apply. + ## List Issues ``` diff --git a/maps/agent-access-map/onboarding.md b/maps/agent-access-map/onboarding.md index 5b40a0ea582..096050ffa57 100644 --- a/maps/agent-access-map/onboarding.md +++ b/maps/agent-access-map/onboarding.md @@ -185,13 +185,22 @@ API: `present` — representative operation IDs: - `POST /api/companies/{companyId}/issues`. - `POST /api/issues/{issueId}/children`. +- `POST /api/companies/{companyId}/chats/{agentRef}/onboarding` (board only). +- `POST /api/companies/{companyId}/chats/{agentRef}/onboarding/greeting` (board only). Agent access: `available` — Native create_task / agent REST / CLI issue. Policy: Instance setup is operator work; company creation is board; agent creation/task creation retain their individual permissions. -An authenticated run bound to the server-created onboarding first task must +The company wizard opens the owner's standing chat without an execution task or +project. Its board client requests a live welcome only once the thread is +visible. Agents use the existing chat interactions to propose work; acceptance +creates standalone tasks, and explicit task requests permit direct creation. +See [chat-first onboarding](../../doc/onboarding-chat.md). The new board routes +do not grant agents authority to start another person's onboarding conversation. + +For historical task-based onboarding, an authenticated run bound to an onboarding first task must obtain persisted human acceptance of the latest ordinary proposal before creating new tasks through native `create_task` or REST. Its authenticated run determines this admission even for an explicit standalone task. A card decision or a saved diff --git a/maps/feature-map/onboarding.md b/maps/feature-map/onboarding.md index b35bf33b370..56f7f03b898 100644 --- a/maps/feature-map/onboarding.md +++ b/maps/feature-map/onboarding.md @@ -4,7 +4,7 @@ navigation: {"section":"Getting started and access","sectionOrder":10,"order":10 # Onboarding and first work -An operator can start an instance, create a company, configure its first agent, and reach a real first task. Instance setup and company onboarding are separate steps. +An operator can start an instance, create a company, configure its first agent, and start in chat. Execution work begins after an accepted task proposal or an explicit task-creation request. Instance setup and company onboarding are separate steps. Feature ID: `onboarding`. @@ -17,7 +17,7 @@ Agent access: [companion](../agent-access-map/onboarding.md). - `instance`: `onboarding/instance` — choose local instance configuration and start the server. - `company`: `onboarding/company` — create a company with its identity and initial agent. - `adapter`: `onboarding/adapter` — choose an available harness, model, account, and execution environment. -- `first-task`: `onboarding/first-task` — leave setup with a task whose execution or missing prerequisite is visible. +- `first-task`: `onboarding/first-task` — leave setup in chat, clarify the goal and exit criteria, and accept or explicitly request the first task. - `resume`: `onboarding/resume` — return to an incomplete wizard without losing saved state. @@ -64,8 +64,13 @@ Automated: [wizard tests](../../ui/src/components/OnboardingWizard.test.tsx) cov Manual: Create a disposable company and first agent. Leave midway, reopen the company's onboarding route, and finish; drafts save automatically. Follow the -created first task, verify the selected agent and company, and inspect its output -or explicit authentication gate. Reload both company and task. +agent chat, verify the selected agent and company, and watch the live welcome. +No execution tasks or projects should exist yet. Request an interview or describe +a goal and clear exit criteria, then accept the suggested task. Verify one +standalone task is created. Reload chat and ensure the welcome is not repeated. +Also verify an explicit task-creation request uses the normal handoff directly. +See [chat-first onboarding](../../doc/onboarding-chat.md). Legacy first-task asset +evaluations cover existing task-based onboarding, not this chat landing. For Codex or Claude, choose the harness to prove automatic first-agent runner selection. On a qualified target it saves Paperclip Runner. The wizard has no diff --git a/packages/adapters/claude-local/src/server/setup-token-parse.ts b/packages/adapters/claude-local/src/server/setup-token-parse.ts index 6028695d16a..96eb42241b1 100644 --- a/packages/adapters/claude-local/src/server/setup-token-parse.ts +++ b/packages/adapters/claude-local/src/server/setup-token-parse.ts @@ -221,6 +221,11 @@ function stripTerminalControls(text: string): string { .replace(ANSI_CSI_RE, ""); } +/** The CLI waits for another Enter after rejecting a code instead of exiting. */ +export function hasSetupTokenOAuthError(text: string): boolean { + return /OAuth\s+error\s*:/.test(stripTerminalControls(text)); +} + /** * Returns true when `value` is a valid `scope` value: one to eight * space-separated tokens, a total length of at most {@link MAX_SCOPE_LENGTH}, diff --git a/packages/adapters/claude-local/src/server/setup-token-runner.test.ts b/packages/adapters/claude-local/src/server/setup-token-runner.test.ts index ede26a52a74..8482efac1f6 100644 --- a/packages/adapters/claude-local/src/server/setup-token-runner.test.ts +++ b/packages/adapters/claude-local/src/server/setup-token-runner.test.ts @@ -96,6 +96,31 @@ async function flush(): Promise { } describe("runSetupTokenLogin", () => { + it("reports a rejected OAuth code immediately even while the CLI waits for Enter to retry", async () => { + const fake = createFakeDriver({ chunks: [PROMPT_OUTPUT] }); + let stream!: (chunk: string) => void; + const start = fake.driver.start.bind(fake.driver); + fake.driver.start = (command, onData) => { stream = onData; return start(command, onData); }; + const write = fake.driver.write.bind(fake.driver); + fake.driver.write = input => { + write(input); + if (input === CODE_SUBMISSION_TERMINATOR) { + stream("\r\n\u001b[31mOAuth\u001b[1Cerr"); + stream(`or: Invalid code ${BROWSER_CODE}\u001b[0m\r\nPress Enter to retry\r\n`); + } + }; + const log = vi.fn(); + const onCredential = vi.fn(); + const result = await runSetupTokenLogin(fake.driver, { + onPrompt: () => {}, provideCode: async () => BROWSER_CODE, onCredential, + codeSubmitSettleMs: 0, timeoutMs: 1000, log, + }); + expect(result).toMatchObject({ outcome: "failure", failureReason: "oauth_error", credentialDelivered: false }); + expect(onCredential).not.toHaveBeenCalled(); + expect(fake.stops.count).toBe(1); + expect(JSON.stringify({ result, logs: log.mock.calls })).not.toContain(BROWSER_CODE); + }); + it("sends one login URL through onPrompt", async () => { // A success stream and a resolving sink, so the run reports success after the // runner delivers the credential. diff --git a/packages/adapters/claude-local/src/server/setup-token-runner.ts b/packages/adapters/claude-local/src/server/setup-token-runner.ts index 076323f7f6b..f1d16644371 100644 --- a/packages/adapters/claude-local/src/server/setup-token-runner.ts +++ b/packages/adapters/claude-local/src/server/setup-token-runner.ts @@ -8,6 +8,7 @@ import { import { parseSetupTokenCredential, parseSetupTokenPrompt, + hasSetupTokenOAuthError, type SetupTokenPrompt, } from "./setup-token-parse.js"; @@ -123,6 +124,7 @@ export type SetupTokenOutcome = LoginRunnerOutcome; * the base result with the two setup-token status fields. */ export interface SetupTokenLoginResult extends LoginRunnerResult { + failureReason?: "oauth_error"; codeSubmitted: boolean; /** True when the runner bound the token and invoked `onCredential` one time. */ credentialDelivered: boolean; @@ -218,6 +220,7 @@ export async function runSetupTokenLogin( let promptSurfaced = false; let codeSubmitted = false; let submitStarted = false; + let oauthError = false; // The runner sets this true one time, only after the mandatory sink resolves. let credentialDelivered = false; // The bound token bytes. The runner binds them from the success record during @@ -329,11 +332,16 @@ export async function runSetupTokenLogin( } return; } - // The prompt already surfaced. Scan the post-prompt stream for the success - // token. The runner scans only when a caller provides an `onCredential` - // sink, so it never holds the secret-bearing stream without a need. - if (!onCredential || tokenBytes) return; + // Observe a rejected code even if the CLI remains open waiting for Enter. + // Retain only the bounded private buffer; return a fixed failure reason. + if (tokenBytes || oauthError) return; tokenBuffer += chunk; + if (hasSetupTokenOAuthError(tokenBuffer)) { + oauthError = true; + tokenBuffer = ""; + controller.abort(); + return; + } captureCredential(); if (!tokenBytes && tokenBuffer.length > CLAUDE_SETUP_TOKEN_MAX_BUFFER_CHARS) { tokenBuffer = tokenBuffer.slice(tokenBuffer.length - CLAUDE_SETUP_TOKEN_MAX_BUFFER_CHARS); @@ -346,6 +354,7 @@ export async function runSetupTokenLogin( promptSurfaced, codeSubmitted, credentialDelivered, + ...(oauthError ? { failureReason: "oauth_error" as const } : {}), }); try { @@ -361,6 +370,11 @@ export async function runSetupTokenLogin( controller.abort(); await submitPromise; + if (oauthError) { + log("[paperclip] Setup-token login: the provider rejected the authorization code."); + return result("failure", null); + } + if (raced.kind === "timeout") { log("[paperclip] Setup-token login timed out; stopping the process."); return result("timeout", null); diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts index 698b73db166..97621602179 100644 --- a/packages/shared/src/constants.ts +++ b/packages/shared/src/constants.ts @@ -372,6 +372,7 @@ export const TASK_WATCHDOG_PRODUCT_BUG_ORIGIN_KIND = "task_watchdog_product_bug" // Marks the single onboarding "first task" so surfaces can special-case it // (e.g. suppress the seeded-description bubble and rely on a seeded greeting). export const ONBOARDING_FIRST_TASK_ORIGIN_KIND = "onboarding_first_task"; +export const ONBOARDING_CHAT_ORIGIN_KIND = "onboarding_chat"; export const ISSUE_ORIGIN_KINDS = [ "manual", @@ -384,6 +385,7 @@ export const ISSUE_ORIGIN_KINDS = [ "task_watchdog", TASK_WATCHDOG_PRODUCT_BUG_ORIGIN_KIND, ONBOARDING_FIRST_TASK_ORIGIN_KIND, + ONBOARDING_CHAT_ORIGIN_KIND, "chat_channel", ] as const; export type BuiltInIssueOriginKind = (typeof ISSUE_ORIGIN_KINDS)[number]; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 0ee8c415f1d..bc4373e3956 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -456,6 +456,7 @@ export { ISSUE_ORIGIN_KINDS, TASK_WATCHDOG_PRODUCT_BUG_ORIGIN_KIND, ONBOARDING_FIRST_TASK_ORIGIN_KIND, + ONBOARDING_CHAT_ORIGIN_KIND, ISSUE_WATCHDOG_DISCOVERY_KINDS, ISSUE_SURFACE_VISIBILITIES, ISSUE_RECOVERY_ACTION_KINDS, diff --git a/server/src/__tests__/agent-conversations.test.ts b/server/src/__tests__/agent-conversations.test.ts index 6feed91153f..74987029b4c 100644 --- a/server/src/__tests__/agent-conversations.test.ts +++ b/server/src/__tests__/agent-conversations.test.ts @@ -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("//"); + }); + 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"); diff --git a/server/src/__tests__/onboarding-chat-route.test.ts b/server/src/__tests__/onboarding-chat-route.test.ts new file mode 100644 index 00000000000..7bf1fb4bc68 --- /dev/null +++ b/server/src/__tests__/onboarding-chat-route.test.ts @@ -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(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(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); + }); +}); diff --git a/server/src/__tests__/onboarding-seed-route.test.ts b/server/src/__tests__/onboarding-seed-route.test.ts index a767a318d8a..93360957222 100644 --- a/server/src/__tests__/onboarding-seed-route.test.ts +++ b/server/src/__tests__/onboarding-seed-route.test.ts @@ -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); }); }); diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index 69c2a5e4bfa..72d5dfabb13 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -84,6 +84,7 @@ const apiPrefixes: Record = { "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, diff --git a/server/src/app.ts b/server/src/app.ts index 558f4ecb4d5..0c419b01aad 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -141,6 +141,7 @@ import { tailscaleConnectionRoutes } from "./routes/tailscale-connections.js"; import { executionWorkspaceRoutes } from "./routes/execution-workspaces.js"; import { goalRoutes } from "./routes/goals.js"; import { onboardingSeedRoutes } from "./routes/onboarding-seed.js"; +import { onboardingChatRoutes } from "./routes/onboarding-chat.js"; import { boardChatRoutes } from "./routes/board-chat.js"; import { approvalRoutes } from "./routes/approvals.js"; import { secretRoutes } from "./routes/secrets.js"; @@ -871,6 +872,7 @@ export async function createApp( api.use(emailRoutes(db, emailChannels)); api.use(goalRoutes(db)); api.use(onboardingSeedRoutes(db)); + api.use(onboardingChatRoutes(db, connectionIntentHeartbeat)); api.use(boardChatRoutes(db, { deploymentMode: opts.deploymentMode })); api.use(voiceSessionRoutes(db, chatChannels.voice)); api.use(approvalRoutes(db, { pluginWorkerManager: workerManager })); diff --git a/server/src/onboarding-assets/first-task/README.md b/server/src/onboarding-assets/first-task/README.md index 5e3f1745b62..a8ea8bff126 100644 --- a/server/src/onboarding-assets/first-task/README.md +++ b/server/src/onboarding-assets/first-task/README.md @@ -1,5 +1,10 @@ # First-task onboarding assets +The company wizard now opens a standing chat and starts a live welcome after the +thread is visible. It creates no task or project; see +[`doc/onboarding-chat.md`](../../../../doc/onboarding-chat.md). +These assets remain for existing onboarding tasks and explicit legacy fixtures. + Everything the very first agent is told during onboarding lives here as plain markdown so the board can edit the wording without touching TypeScript. The server loads these files (see `server/src/services/onboarding-first-task-assets.ts` diff --git a/server/src/routes/onboarding-chat.ts b/server/src/routes/onboarding-chat.ts new file mode 100644 index 00000000000..fbba4cbaf5b --- /dev/null +++ b/server/src/routes/onboarding-chat.ts @@ -0,0 +1,33 @@ +import { Router, type RequestHandler } from "express"; +import type { Db } from "@paperclipai/db"; +import { forbidden, notFound } from "../errors.js"; +import { agentService } from "../services/agents.js"; +import type { heartbeatService } from "../services/heartbeat.js"; +import { instanceSettingsService } from "../services/instance-settings.js"; +import { issueService } from "../services/issues.js"; +import { ensureOnboardingChat, startOnboardingGreeting } from "../services/onboarding-chat.js"; +import { assertCompanyAccess } from "./authz.js"; + +export function onboardingChatRoutes(db: Db, heartbeat: Pick, "wakeup">) { + const router = Router(); + const handle = (greeting: boolean): RequestHandler => async (req, res) => { + const companyId = req.params.companyId as string; + assertCompanyAccess(req, companyId); + if (req.actor.type !== "board" || !req.actor.userId) throw forbidden("Board user access required"); + if (!(await instanceSettingsService(db).getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled"); + const resolved = await agentService(db).resolveByReference(companyId, req.params.agentRef as string); + if (!resolved.agent || resolved.ambiguous) throw notFound("Agent not found"); + const agent = resolved.agent; + const userId = req.actor.userId; + if (!greeting) { + res.json(await ensureOnboardingChat(db, { companyId, agentId: agent.id, agentName: agent.name, userId })); + return; + } + const issue = await issueService(db).getConversation(companyId, agent.id, userId); + if (!issue) throw notFound("Conversation not found"); + res.json({ started: await startOnboardingGreeting(db, issue, userId, heartbeat.wakeup) }); + }; + router.post("/companies/:companyId/chats/:agentRef/onboarding", handle(false)); + router.post("/companies/:companyId/chats/:agentRef/onboarding/greeting", handle(true)); + return router; +} diff --git a/server/src/routes/onboarding-seed.ts b/server/src/routes/onboarding-seed.ts index e167fd81dc5..e402c44b621 100644 --- a/server/src/routes/onboarding-seed.ts +++ b/server/src/routes/onboarding-seed.ts @@ -22,7 +22,8 @@ import { assertCompanyAccess, getActorInfo } from "./authz.js"; * acknowledged revision only afterwards, retrying from the next portfolio * fetch otherwise. So this route answers 200 only once every part of the seed * has been applied, and a replay of an already-applied revision is a - * successful no-op rather than a second agent and a second task. + * successful no-op rather than a second agent. Initial task ideas are retained + * as chat context; applying a seed creates no execution task or project. * * "Every part" includes the audit entry, which `apply` writes inside the same * transaction as the seed. Because Cloud stops retrying on a 2xx, anything this diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 19e87bd6507..a80a1a74074 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -1467,6 +1467,8 @@ const mcpSkillsBoardOperations = [ ] as const; const BOARD_ONLY_OPERATIONS = new Set([ + "POST /api/companies/{companyId}/chats/{agentRef}/onboarding", + "POST /api/companies/{companyId}/chats/{agentRef}/onboarding/greeting", "PATCH /api/agents/{id}/permission-grants", // Budget changes are board-only (assertBoard in routes/costs.ts). "POST /api/companies/{companyId}/budgets/policies", @@ -4428,6 +4430,26 @@ registry.registerPath({ // ─── Issues ────────────────────────────────────────────────────────────────── +registry.registerPath({ + method: "post", + path: "/api/companies/{companyId}/chats/{agentRef}/onboarding", + tags: ["issues"], + summary: "Open the current board user's onboarding chat", + description: "Requires Agent Chat and company access. Reuses the caller's existing conversation or creates an unnumbered standing chat with onboarding context. Creates no execution task or project and starts no agent turn.", + request: { params: z.object({ companyId: z.string(), agentRef: z.string() }) }, + responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound }, +}); + +registry.registerPath({ + method: "post", + path: "/api/companies/{companyId}/chats/{agentRef}/onboarding/greeting", + tags: ["issues"], + summary: "Start the visible onboarding chat's live welcome", + description: "Call after the chat is visible. Requires an existing conversation owned by the caller. Returns started=true when a welcome is queued or already pending, or false when the conversation no longer needs a welcome. Retries failed or timed-out attempts and preserves normal agent admission gates.", + request: { params: z.object({ companyId: z.string(), agentRef: z.string() }) }, + responses: { 200: r.ok(z.object({ started: z.boolean() })), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound }, +}); + registry.registerPath({ method: "get", path: "/api/companies/{companyId}/chats", diff --git a/server/src/services/agent-conversations.ts b/server/src/services/agent-conversations.ts index 887a4fb6c0e..55f31790280 100644 --- a/server/src/services/agent-conversations.ts +++ b/server/src/services/agent-conversations.ts @@ -29,6 +29,7 @@ import { evaluateAgentInvokabilityFromDb } from "./agent-invokability.js"; import { createHeartbeatTimerPolicy, parseHeartbeatPolicy } from "./heartbeat/timer-policy.js"; import { isAgentAwaitingSetup } from "../modules/agent-lifecycle/index.js"; import { HttpError } from "../errors.js"; +import { ONBOARDING_CHAT_GREETING_REASON } from "./onboarding-chat-prompt.js"; export type ConversationIdentity = { conversationAgentId?: string | null; @@ -424,7 +425,9 @@ export async function settleConversationTurn( .from(issueComments) .where(eq(issueComments.id, wakeId)) : []; - const [pending] = wake + // The welcome has no synthetic human anchor. Every real user message + // arriving during that first reply is still owed a response. + const [pending] = wake || context.wakeReason === ONBOARDING_CHAT_GREETING_REASON ? await tx .select({ id: issueComments.id }) .from(issueComments) @@ -433,7 +436,7 @@ export async function settleConversationTurn( eq(issueComments.issueId, issueId), isNull(issueComments.deletedAt), sql`${issueComments.authorUserId} is not null`, - sql`(${issueComments.createdAt}, ${issueComments.id}) > (select cursor.created_at, cursor.id from issue_comments cursor where cursor.id = ${wake.id}::uuid)`, + wake ? sql`(${issueComments.createdAt}, ${issueComments.id}) > (select cursor.created_at, cursor.id from issue_comments cursor where cursor.id = ${wake.id}::uuid)` : undefined, ), ) .limit(1) diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index 84b38160dad..8d575a55ef9 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -59,6 +59,8 @@ import { isConversationExecutionWake, isWaitingConversation, } from "../agent-conversations.js"; +import { onboardingGreetingNeeded } from "../onboarding-chat.js"; +import { ONBOARDING_CHAT_GREETING_REASON } from "../onboarding-chat-prompt.js"; import { legacyControllerClaim } from "../legacy-controller-lease.js"; import { admitExplicitNativeContinuation, @@ -1036,6 +1038,20 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const runContext = parseObject(run.contextSnapshot); const systemContinuationReason = readNonEmptyString(runContext.wakeReason); const continuedIssueId = readNonEmptyString(runContext.issueId); + if (systemContinuationReason === ONBOARDING_CHAT_GREETING_REASON && !run.startedAt) { + const [chat] = continuedIssueId ? await db.select().from(issues) + .where(and(eq(issues.companyId, run.companyId), eq(issues.id, continuedIssueId))) : []; + if (!chat || !(await onboardingGreetingNeeded(db, chat))) { + const errorCode = "onboarding_welcome_superseded"; + const cancelled = await cancelRunIfStillQueued(run.id, { finishedAt: new Date(), errorCode, + error: "The conversation no longer needs an opening welcome." }); + if (cancelled) { + await setWakeupStatus(run.wakeupRequestId, "skipped", { finishedAt: cancelled.finishedAt!, error: errorCode }); + await releaseIssueExecutionAndPromote(cancelled, { suppressImmediateRecovery: true, deferredPostCommitEffects }); + } + return null; + } + } if (systemContinuationReason && SYSTEM_CONTINUATION_WAKE_REASONS.has(systemContinuationReason) && continuedIssueId && runContext.onboardingCompletion !== true) { const [target] = await db.select({ status: issues.status, assigneeAgentId: issues.assigneeAgentId }).from(issues) @@ -2805,6 +2821,8 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende ); const hasIndependentConversationWakeCause = () => Boolean( wakeCommentId || opts.taskRetryRequestId || + (reason === "onboarding_chat_greeting" && opts.manualUserWake === true + && opts.requestedByActorType === "user" && source === "on_demand") || hasInteractionContinuationWakeContext(enrichedContextSnapshot) || reason === CHAT_COMPLETION_WAKE_REASON || isManualContextCompactionWake(), ); @@ -2862,6 +2880,8 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende if (taskRetryActorId && conversation) assertTaskRetryConversationAllowed(conversation, taskRetryActorId); if (reason === "issue_children_completed" && conversation?.originKind === "onboarding_first_task") enrichedContextSnapshot.onboardingCompletion = true; if (isConversation(conversation)) { + if (reason === "onboarding_chat_greeting" && (conversation?.originKind !== "onboarding_chat" + || conversation.conversationUserId !== opts.requestedByActorId)) return null; if (opts.manualUserWake && conversation!.conversationUserId !== opts.requestedByActorId) { throw new HttpError(403, "Only the conversation owner can start a chat run"); } diff --git a/server/src/services/heartbeat/task-context.ts b/server/src/services/heartbeat/task-context.ts index 672cee529d4..ec94bc7b4cb 100644 --- a/server/src/services/heartbeat/task-context.ts +++ b/server/src/services/heartbeat/task-context.ts @@ -1,4 +1,6 @@ import { createHash } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { companies } from "@paperclipai/db"; import type { Db, agents, agentTaskSessions, heartbeatRuns } from "@paperclipai/db"; import { FAST_RESPONSE_AGENT_GUIDANCE, fastResponseHistoryBody, isValidIanaTimeZone } from "@paperclipai/shared"; import type { PaperclipTurnContext } from "@paperclipai/adapter-utils/server-utils"; @@ -252,7 +254,11 @@ export async function prepareHeartbeatTaskContext(db: Db, input: HeartbeatTaskCo : null; if (personTimeZone) context.paperclipConversationTimeZone = personTimeZone; else delete context.paperclipConversationTimeZone; + const [chatCompany] = issueRef?.conversationAgentId && !issueRef.identifier + ? await db.select({ issuePrefix: companies.issuePrefix }).from(companies).where(eq(companies.id, agent.companyId)) + : []; const taskMarkdownInput = { + companyPrefix: chatCompany?.issuePrefix, coordinatorWorkspace: Boolean(coordinatorWorkspace), personTimeZone, conferenceRoomEnabled: experimentalInstanceSettings.enableConferenceRoomChat === true, @@ -261,6 +267,8 @@ export async function prepareHeartbeatTaskContext(db: Db, input: HeartbeatTaskCo conversationConfirmations: issueRef && isConversation(issueContext) ? await getConversationConfirmationContext({ db, companyId: agent.companyId, issueId: issueRef.id, agentId: agent.id }) : null, + onboardingChat: issueContext?.originKind === "onboarding_chat", + onboardingGreeting: context.wakeReason === "onboarding_chat_greeting", issue: issueRef ? { id: issueRef.id, diff --git a/server/src/services/heartbeat/task-markdown.test.ts b/server/src/services/heartbeat/task-markdown.test.ts index a51dfd5a047..7fbe9cbf098 100644 --- a/server/src/services/heartbeat/task-markdown.test.ts +++ b/server/src/services/heartbeat/task-markdown.test.ts @@ -9,6 +9,26 @@ const issue = { }; describe("heartbeat task markdown rendering", () => { + it("carries signup context and proposal boundaries into every onboarding chat turn, greeting only on arrival", () => { + const input = { issue: { ...issue, conversationAgentId: "agent", description: '{"initialIdea":"Launch a newsletter"}' }, + nativeRunner: true, coordinatorWorkspace: true, onboardingChat: true }; + const greeting = buildPaperclipTaskMarkdown({ ...input, onboardingGreeting: true }); + expect(greeting).toContain("Welcome turn:"); + expect(greeting).toContain("so it streams to the user"); + for (const includeDescription of [true, false]) { + const followup = buildPaperclipTaskMarkdown({ ...input, includeDescription }); + expect(followup).toContain("Launch a newsletter"); + expect(followup).toContain("concrete goal and clear exit criteria"); + expect(followup).toContain("begin a structured interview only when they request"); + expect(followup).toContain('interactionKind: "suggest_tasks"'); + expect(followup).toContain("acceptance creates the task atomically"); + expect(followup).toContain("omit projectId from the suggestion"); + expect(followup).not.toContain("Coordinator task proposals:"); + expect(followup).toContain("An explicit task-creation request authorizes creating it directly"); + expect(followup).not.toContain("Welcome turn:"); + } + expect(buildPaperclipTaskMarkdown({ issue })).not.toContain("Onboarding conversation:"); + }); it.each([true, false])("keeps native task clarification in the current task on full and resumed assignments (description=%s)", (includeDescription) => { const markdown = buildPaperclipTaskMarkdown({ issue: { ...issue, description: "Write a blog post about our launch." }, diff --git a/server/src/services/heartbeat/task-markdown.ts b/server/src/services/heartbeat/task-markdown.ts index 2304331d7a2..ef0bde0f691 100644 --- a/server/src/services/heartbeat/task-markdown.ts +++ b/server/src/services/heartbeat/task-markdown.ts @@ -4,8 +4,12 @@ import { publicChatTaskUrl } from "../chat-task-url.js"; import { slackChatAgentGuidance } from "../connectors/slack/agent-guidance.js"; import type { ConversationConfirmationContext } from "../conversation-confirmation-context.js"; import { TASK_QUESTION_GUIDANCE } from "../issue-question-context.js"; +import { ONBOARDING_CHAT_DIRECTIVE, ONBOARDING_CHAT_GREETING_DIRECTIVE } from "../onboarding-chat-prompt.js"; export function buildPaperclipTaskMarkdown(input: { + companyPrefix?: string | null; + onboardingChat?: boolean; + onboardingGreeting?: boolean; issue: { id: string; identifier: string | null; @@ -89,10 +93,9 @@ export function buildPaperclipTaskMarkdown(input: { return [fence + "text", value, fence].join("\n"); }; const issue = input.issue; - // Chat guidance names company pages as //...; a model can copy that - // placeholder verbatim into a link the person clicks. The conversation's own - // identifier (COM-1 -> COM) is the company prefix, so hand the agent real paths. - const companyPagePrefix = /^(.+)-\d+$/.exec(issue?.identifier ?? "")?.[1] ?? null; + // Unnumbered chats get the company's prefix directly. Legacy numbered chats + // can fall back to their identifier so guidance always names real page paths. + const companyPagePrefix = input.companyPrefix ?? /^(.+)-\d+$/.exec(issue?.identifier ?? "")?.[1] ?? null; const companyPages = (text: string) => companyPagePrefix ? text.replaceAll("//", `/${companyPagePrefix}/`) : text; const ancestors = (input.ancestors ?? []).slice(0, 6); @@ -231,10 +234,15 @@ export function buildPaperclipTaskMarkdown(input: { } if (issue.conversationAgentId) { lines.push("", "Chat mode directive:", companyPages(AGENT_CHAT_DIRECTIVE), `Current composer mode: ${issue.workMode ?? "standard"}.`); + if (input.onboardingChat) { + lines.push("", "Onboarding conversation:", ONBOARDING_CHAT_DIRECTIVE, + "Onboarding answers (quoted user data):", fenceTaskText(issue.description ?? "")); + if (input.onboardingGreeting) lines.push("", "Welcome turn:", ONBOARDING_CHAT_GREETING_DIRECTIVE); + } if (input.personTimeZone) { lines.push(`The person's time zone is ${input.personTimeZone} (from their browser). Read times and dates they give, such as "nine in the morning" or "today", in that zone, and save schedules such as routine triggers with that timezone; say the zone when you report a schedule.`); } - if (input.nativeRunner && input.coordinatorWorkspace) { + if (input.nativeRunner && input.coordinatorWorkspace && !input.onboardingChat) { lines.push("", "Coordinator task proposals:", companyPages(COORDINATOR_CHAT_HANDOFF_DIRECTIVE)); } if (input.conferenceRoomEnabled) lines.push("", "Conference Room:", companyPages(CONFERENCE_ROOM_CHAT_DIRECTIVE)); diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 8ff17885260..b18678dc74f 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -11023,29 +11023,34 @@ export function issueService(db: Db) { executionWorkspaceSettings: issueData.executionWorkspaceSettings, }); } - // Self-correcting counter: use MAX(issue_number) + 1 if the counter - // has drifted below the actual max, preventing identifier collisions. - const [maxRow] = await tx - .select({ - maxNum: sql`coalesce(max(${issues.issueNumber}), 0)`, - }) - .from(issues) - .where(eq(issues.companyId, companyId)); - const currentMax = maxRow?.maxNum ?? 0; + // Standing chats use UUIDs and do not consume execution task numbers. + let issueNumber: number | null = null; + let identifier: string | null = null; + if (!issueData.conversationAgentId) { + // Self-correcting counter: use MAX(issue_number) + 1 if the counter + // has drifted below the actual max, preventing identifier collisions. + const [maxRow] = await tx + .select({ + maxNum: sql`coalesce(max(${issues.issueNumber}), 0)`, + }) + .from(issues) + .where(eq(issues.companyId, companyId)); + const currentMax = maxRow?.maxNum ?? 0; - const [company] = await tx - .update(companies) - .set({ - issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + 1`, - }) - .where(eq(companies.id, companyId)) - .returning({ - issueCounter: companies.issueCounter, - issuePrefix: companies.issuePrefix, - }); + const [company] = await tx + .update(companies) + .set({ + issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + 1`, + }) + .where(eq(companies.id, companyId)) + .returning({ + issueCounter: companies.issueCounter, + issuePrefix: companies.issuePrefix, + }); - const issueNumber = company.issueCounter; - const identifier = `${company.issuePrefix}-${issueNumber}`; + issueNumber = company.issueCounter; + identifier = `${company.issuePrefix}-${issueNumber}`; + } const responsibleUserId = await resolveResponsibleUserIdForIssueCreate( tx, companyId, diff --git a/server/src/services/local-ai-browser-login.test.ts b/server/src/services/local-ai-browser-login.test.ts index 9bfdd7434ab..38a0d55f0a9 100644 --- a/server/src/services/local-ai-browser-login.test.ts +++ b/server/src/services/local-ai-browser-login.test.ts @@ -212,6 +212,27 @@ describe.skipIf(process.platform === "win32")("local browser subscription login" expect((await stat(path.join(home, ".credentials.json"))).mode & 0o777).toBe(0o600); }); + it("reports a rejected Claude code while the CLI waits for a terminal retry", async () => { + const url = "https://claude.com/cai/oauth/authorize?client_id=cid&code=abcdefgh&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&response_type=code&scope=user&state=0123456789abcdef"; + const home = await fakeCli("claude", [ + 'printf "Welcome to Claude Code\\nOpening browser to sign in…\\nBrowser didn\x27t open? Use the url below to sign in (c to copy)\\n"', + `printf '%s\\n' '${url}'`, + 'printf "Paste code here if prompted >\\n"', + 'read -r entered', + 'printf "OAuth error: Invalid code. Press Enter to retry.\\n"', + 'exec sleep 60', + ].join("\n")); + const login = startLocalBrowserLogin("anthropic", home); + try { + await vi.waitFor(() => expect(login.authorizationUrl).toBe(url), { timeout: 5000 }); + login.submitCode?.("fixture-code"); + await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5000 }); + expect(login.error).toContain("Claude rejected the authorization code"); + expect(login.error).not.toContain("fixture-code"); + await expect(readFile(path.join(home, ".credentials.json"))).rejects.toMatchObject({ code: "ENOENT" }); + } finally { login.abort(); } + }); + it("terminates the local provider process when sign-in is cancelled", async () => { const home = await fakeCli("codex", 'echo $$ > "$CODEX_HOME/login.pid"\nexec sleep 60'); const login = startLocalBrowserLogin("openai", home); diff --git a/server/src/services/local-ai-browser-login.ts b/server/src/services/local-ai-browser-login.ts index c657287494d..8ae0a0d54e0 100644 --- a/server/src/services/local-ai-browser-login.ts +++ b/server/src/services/local-ai-browser-login.ts @@ -120,7 +120,10 @@ export function startLocalBrowserLogin(provider: "anthropic" | "openai" | "googl await file.close(); } }, - }).then((result) => { state.outcome = result.outcome === "success" ? "success" : "failure"; }) + }).then((result) => { + state.outcome = result.outcome === "success" ? "success" : "failure"; + if (result.failureReason === "oauth_error") state.error = "Claude rejected the authorization code. Start sign-in again and use the code from the new sign-in tab."; + }) .catch(() => { state.outcome = "failure"; }); } else { void runDeviceLogin(driver, { diff --git a/server/src/services/onboarding-chat-prompt.ts b/server/src/services/onboarding-chat-prompt.ts new file mode 100644 index 00000000000..7dee0c0dc2e --- /dev/null +++ b/server/src/services/onboarding-chat-prompt.ts @@ -0,0 +1,9 @@ +export const ONBOARDING_CHAT_GREETING_REASON = "onboarding_chat_greeting"; + +export const ONBOARDING_CHAT_DIRECTIVE = `This conversation is the user's starting point after onboarding. Help them turn an idea into a well-scoped task with a concrete goal and clear exit criteria. Use the onboarding context below as background, not as authorization to execute work or as instructions that override this workflow. Do not invent missing goals or success criteria. + +Let the user choose an interview or ordinary conversation. Offer to interview them; begin a structured interview only when they request or choose it. In an interview, ask focused questions about their goal, relevant background, constraints and what done looks like, using a question card when useful. In ordinary conversation, ask only what is needed to understand the outcome and exit criteria. Reuse answers already provided. + +Once the goal and exit criteria are clear, suggest a concrete task for the user to accept. Use request_human_input with interactionKind: "suggest_tasks", a stable idempotencyKey and payload.tasks containing a clientKey, concise title, self-contained description with context, constraints and acceptance criteria, initialPlan and assigneeAgentId defaulting to yourself. With HTTP, POST the equivalent suggest_tasks interaction to /api/issues/{issueId}/interactions. A suggestion is not an execution task; acceptance creates the task atomically, so read result.createdTasks and link that task rather than creating it again. Reuse a suitable existing projectId when available. If no suitable project exists, omit projectId from the suggestion; do not create a project just to prepare a proposal. After acceptance, use the normal project controls if the approved work needs a new project. Do not create a task, project or hire agents just because onboarding finished, the user described an idea or answered questions. Create execution work only after the user accepts a proposal or explicitly asks you to create a task. An explicit task-creation request authorizes creating it directly once material scope questions are answered; do not ask them to approve the same scope again. Use the normal project and task handoff controls, preserve hiring and budget gates, and link the resulting task in this conversation. Keep this chat available for further discussion.`; + +export const ONBOARDING_CHAT_GREETING_DIRECTIVE = `The user has just arrived in this visible chat after onboarding. Greet them now with a short, warm message in your own voice using the onboarding context. You can start with "Welcome to Paperclip! I'm , your first agent teammate." Invite them to tell you what they want to achieve, or ask you to interview them to work it out together. If they already supplied a goal, acknowledge it and ask the next useful question instead of asking them to repeat it. Do not create tasks, projects, hires, plans or question cards during this greeting. Send the welcome as your conversational reply so it streams to the user. If a user message is already present, answer it naturally instead of repeating an opening greeting.`; diff --git a/server/src/services/onboarding-chat.ts b/server/src/services/onboarding-chat.ts new file mode 100644 index 00000000000..1b57bfe4b67 --- /dev/null +++ b/server/src/services/onboarding-chat.ts @@ -0,0 +1,72 @@ +import { and, eq, isNull, ne, sql } from "drizzle-orm"; +import { agentWakeupRequests, companies, companyOnboardingSeeds, goals, heartbeatRuns, issueComments, withDedicatedDbConnection, type Db } from "@paperclipai/db"; +import { ONBOARDING_CHAT_ORIGIN_KIND } from "@paperclipai/shared"; +import { issueService } from "./issues.js"; +import { logActivity } from "./activity-log.js"; +import type { heartbeatService } from "./heartbeat.js"; +import { ONBOARDING_CHAT_GREETING_REASON } from "./onboarding-chat-prompt.js"; + +/** Called by Finish, before navigation. Opening a conversation never starts work. */ +export async function ensureOnboardingChat(db: Db, input: { + companyId: string; agentId: string; agentName: string; userId: string; +}) { + const svc = issueService(db); + const existing = await svc.getConversation(input.companyId, input.agentId, input.userId); + if (existing) return existing; + const [company] = await db.select({ name: companies.name }).from(companies).where(eq(companies.id, input.companyId)); + const [seed] = await db.select().from(companyOnboardingSeeds).where(eq(companyOnboardingSeeds.companyId, input.companyId)); + const companyGoals = await db.select({ title: goals.title, description: goals.description }).from(goals) + .where(and(eq(goals.companyId, input.companyId), eq(goals.level, "company"))); + const issue = await svc.create(input.companyId, { + title: `Chat with ${input.agentName}`, + description: JSON.stringify({ organization: company?.name, goals: companyGoals, + initialIdea: seed?.firstTaskTitle, initialDetails: seed?.firstTaskDetails }), + originKind: ONBOARDING_CHAT_ORIGIN_KIND, + conversationAgentId: input.agentId, conversationUserId: input.userId, + assigneeAgentId: input.agentId, createdByUserId: input.userId, + conversationState: "waiting", status: "in_review", + }); + await logActivity(db, { companyId: input.companyId, actorType: "user", actorId: input.userId, + action: "issue.conversation_opened", entityType: "issue", entityId: issue.id, + details: { agentId: input.agentId, onboarding: true } }); + return issue; +} + +/** A typed reply or /new supersedes a welcome that has not started yet. */ +export async function onboardingGreetingNeeded(db: Db, issue: { + id: string; companyId: string; originKind?: string; conversationSessionGeneration: number; +}) { + if (issue.originKind !== ONBOARDING_CHAT_ORIGIN_KIND || issue.conversationSessionGeneration !== 0) return false; + const [comment] = await db.select({ id: issueComments.id }).from(issueComments).where(and( + eq(issueComments.companyId, issue.companyId), eq(issueComments.issueId, issue.id), isNull(issueComments.deletedAt), + )).limit(1); + return !comment; +} + +export async function startOnboardingGreeting(db: Db, issue: Parameters[1] & { + conversationAgentId: string | null; +}, userId: string, wakeup: ReturnType["wakeup"]) { + return withDedicatedDbConnection(db, lockDb => lockDb.transaction(async lock => { + await lock.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`onboarding-greeting:${issue.id}`}, 0))`); + if (!issue.conversationAgentId || !(await onboardingGreetingNeeded(db, issue))) return false; + const key = `onboarding-chat-greeting:${issue.id}`; + const [receipt] = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests) + .leftJoin(heartbeatRuns, eq(heartbeatRuns.id, agentWakeupRequests.runId)) + .where(and(eq(agentWakeupRequests.companyId, issue.companyId), eq(agentWakeupRequests.agentId, issue.conversationAgentId), + eq(agentWakeupRequests.idempotencyKey, key), ne(agentWakeupRequests.status, "skipped"), ne(agentWakeupRequests.status, "failed"), + ne(agentWakeupRequests.status, "timed_out"), + sql`(${heartbeatRuns.status} is null or ${heartbeatRuns.status} not in ('failed', 'cancelled', 'timed_out'))`)).limit(1); + if (receipt) return true; + const run = await wakeup(issue.conversationAgentId, { + source: "on_demand", triggerDetail: "manual", reason: ONBOARDING_CHAT_GREETING_REASON, + idempotencyKey: key, requestedByActorType: "user", requestedByActorId: userId, manualUserWake: true, + allowRunCoalescing: false, payload: { issueId: issue.id }, + contextSnapshot: { issueId: issue.id, taskId: issue.id, wakeReason: ONBOARDING_CHAT_GREETING_REASON }, + }); + if (!run) throw new Error("The welcome could not start. Please try again."); + await logActivity(db, { companyId: issue.companyId, actorType: "user", actorId: userId, + action: "issue.onboarding_welcome_started", entityType: "issue", entityId: issue.id, + details: { agentId: issue.conversationAgentId, runId: run.id } }); + return true; + })); +} diff --git a/server/src/services/onboarding-seed.ts b/server/src/services/onboarding-seed.ts index 9aff67f47f9..f929f2c26c7 100644 --- a/server/src/services/onboarding-seed.ts +++ b/server/src/services/onboarding-seed.ts @@ -1,6 +1,6 @@ import { and, eq, ne, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; -import { agents, companyOnboardingSeeds, goals, issues, projects } 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"; @@ -9,18 +9,9 @@ import { createAgentLifecycle, scheduleAgentLifecycle } from "./agent-lifecycle. import { withDedicatedDbConnection } from "@paperclipai/db"; import { PAPERCLIP_CORE_SKILL_KEYS } from "./company-skills.js"; import { goalService } from "./goals.js"; -import { projectService } from "./projects.js"; -import { issueService } from "./issues.js"; import { readBuiltInAgentMarker } from "../lib/built-in-agent-metadata.js"; import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js"; -/** - * The project the seeded first task lands in, matching the name the tenant's - * own first-run wizard uses so a later manual run reuses it instead of - * creating a second "Onboarding" project. - */ -export const ONBOARDING_SEED_PROJECT_NAME = "Onboarding"; - /** * 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 @@ -147,48 +138,13 @@ export function onboardingSeedService(db: Db) { return candidates.find((row) => !readBuiltInAgentMarker(row.metadata))?.id ?? null; } - async function issueStillExists(dbx: Db, companyId: string, issueId: string | null) { - if (!issueId) return false; - return dbx - .select({ id: issues.id }) - .from(issues) - .where(and(eq(issues.id, issueId), eq(issues.companyId, companyId))) - .then((rows) => rows.length > 0); - } - - async function resolveOnboardingProjectId( - dbx: Db, - projectSvc: ReturnType, - companyId: string, - goalId: string | null, - ) { - const existing = await dbx - .select({ id: projects.id, name: projects.name, status: projects.status }) - .from(projects) - .where(eq(projects.companyId, companyId)); - const reusable = existing.find( - (project) => - project.status !== "cancelled" - && project.name.trim().toLowerCase() === ONBOARDING_SEED_PROJECT_NAME.toLowerCase(), - ); - if (reusable) return reusable.id; - - const created = await projectSvc.create(companyId, { - name: ONBOARDING_SEED_PROJECT_NAME, - status: "in_progress", - ...(goalId ? { goalIds: [goalId] } : {}), - }); - return created.id; - } - 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; - // 2. Agent → the customer's first hire, the lead the first task is - // assigned to. + // Agent → the customer's first hire and initial chat partner. let agentId = await resolveTargetAgentId(dbx, companyId, existing?.agentId ?? null); if (agentName) { if (agentId) { @@ -221,8 +177,6 @@ export function onboardingSeedService(db: Db) { preparedAgentId: string | null, ): Promise { const goalSvc = goalService(dbx); - const projectSvc = projectService(dbx); - const issueSvc = issueService(dbx); const existing = await readRecord(dbx, companyId); if (existing && existing.revision === seed.revision) { @@ -267,44 +221,10 @@ export function onboardingSeedService(db: Db) { const agentId = preparedAgentId; - // A mission-only seed leaves the first task to the onboarding route. - let issueId = existing?.issueId ?? null; - if (firstTaskTitle) { - if (await issueStillExists(dbx, companyId, issueId)) { - await issueSvc.update( - issueId as string, - { - title: firstTaskTitle, - description: firstTaskDetails, - // Keep the task's relationships in step with a later revision that - // supplied the agent or goal after the task already existed — - // otherwise the record would report an assignee/goal the issue row - // does not actually carry. Only set them when resolved, so an - // absent value never clears an assignment the tenant made. - ...(agentId ? { assigneeAgentId: agentId } : {}), - ...(goalId ? { goalId } : {}), - }, - dbx, - ); - } else { - const projectId = await resolveOnboardingProjectId(dbx, projectSvc, companyId, goalId); - // The idempotency key is what protects two pushes that arrive at once - // — Cloud's reconcile runs off portfolio fetches, which can overlap. - // It is deliberately not revision-scoped: if the recorded issue is - // lost, a later revision should still dedupe against whatever the - // first push created. - const created = await issueSvc.create(companyId, { - title: firstTaskTitle, - ...(firstTaskDetails ? { description: firstTaskDetails } : {}), - ...(agentId ? { assigneeAgentId: agentId } : {}), - projectId, - ...(goalId ? { goalId } : {}), - status: "todo", - idempotencyKey: `onboarding-seed:${companyId}`, - }); - issueId = created.id; - } - } + // 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. diff --git a/tests/e2e/agent-chat-messages.spec.ts b/tests/e2e/agent-chat-messages.spec.ts index bccbd12dd29..1a4512cc92e 100644 --- a/tests/e2e/agent-chat-messages.spec.ts +++ b/tests/e2e/agent-chat-messages.spec.ts @@ -4,6 +4,32 @@ import { idle, json, send, setup } from "./agent-chat.shared"; test.use({ trace: "retain-on-failure" }); test.setTimeout(120_000); +test("answering questions in chat and inbox updates both open surfaces", async ({ page, request, context }) => { + const f = await setup(request); + const inbox = await context.newPage(); + try { + await page.goto(f.route); + for (const answerIn of ["chat", "inbox"] as const) { + await send(page, { action: "question" }); + await expect(page.getByRole("radio", { name: "Garden club", exact: true }).last()).toBeVisible({ timeout: 45_000 }); + if (answerIn === "chat") await inbox.goto(`/${f.company.issuePrefix}/decisions`); + const inboxQuestion = inbox.getByRole("radio", { name: "Garden club", exact: true }); + await expect(inboxQuestion).toBeVisible({ timeout: 20_000 }); + const answeringPage = answerIn === "chat" ? page : inbox; + await answeringPage.getByRole("radio", { name: "Garden club", exact: true }).last().click(); + await answeringPage.getByRole("button", { name: "Submit answers", exact: true }).last().click(); + await expect(inboxQuestion).toHaveCount(0, { timeout: 20_000 }); + await expect(page.getByRole("radio", { name: "Garden club", exact: true })).toHaveCount(0, { timeout: 20_000 }); + const chat = await json(await request.get(f.chatPath)); + await expect.poll(async () => { + const feed = await json(await request.get(`/api/companies/${f.company.id}/attention?all=true&view=mine`)); + return feed.items.filter((item: any) => item.sourceKind === "issue_thread_interaction" && item.relatedIssue?.id === chat.id).length; + }).toBe(0); + await idle(request, f.chatPath, answerIn === "chat" ? 2 : 4); + } + } finally { await inbox.close(); await f.restore(); } +}); + test("a routine delivers a first digest, unread state, source link and replyable history", async ({ page, request }) => { const f = await setup(request); try { diff --git a/tests/e2e/conference-room-typing-intro.spec.ts b/tests/e2e/conference-room-typing-intro.spec.ts index b423537efe0..b759d5d9a15 100644 --- a/tests/e2e/conference-room-typing-intro.spec.ts +++ b/tests/e2e/conference-room-typing-intro.spec.ts @@ -1,25 +1,12 @@ import { test, expect, type Page } from "@playwright/test"; import { mockOnboardingLocalAiConnection } from "./helpers/onboarding-ai-connection"; import { - expectLandsOnFirstTaskWithoutDashboardBounce, + expectLandsOnChatWithoutDashboardBounce, instrumentNavLog, } from "./helpers/onboarding-landing"; -/** - * E2E: post-wizard onboarding launch. - * - * Completing the onboarding wizard now creates the first assigned task and - * drops the user straight onto that task's detail page (not the dashboard), - * so they land in the conversation the agent will start in. The chat intro - * still has unit coverage in BoardChat tests. - * - * PAP-404: onboarding used to intermittently bounce to the company dashboard. - * The bounce only reproduces when the instance already has ≥1 company (the - * board's test ports), so the second test seeds a company first to exercise - * exactly that failing condition. - */ - -const FIRST_TASK_TITLE = "Paperclip onboarding"; +/** Post-wizard onboarding opens the standing chat without execution work. + * PAP-404: company page memory must not bounce the new chat to the dashboard. */ /** * Intercept authentication, environment checks, and hiring so no real CLI check @@ -28,6 +15,13 @@ const FIRST_TASK_TITLE = "Paperclip onboarding"; */ async function installLaunchIntercepts(page: Page, baseURL?: string) { await mockOnboardingLocalAiConnection(page); + // Keep the inert provider from starting; verify the welcome is requested only + // after navigation and the conversation composer are visible. + await page.route("**/onboarding/greeting", async route => { + await expect(page).toHaveURL(/\/chats\/[^/]+$/); + await expect(page.getByTestId("task-chat-composer-add")).toBeVisible(); + await route.fulfill({ json: { started: false } }); + }); await page.route("**/test-environment", (route) => route.fulfill({ contentType: "application/json", @@ -62,7 +56,7 @@ async function installLaunchIntercepts(page: Page, baseURL?: string) { } /** Drive the wizard from the /onboarding route through to "Get started". */ -async function runOnboardingWizard(page: Page, companyName: string) { +async function runOnboardingWizard(page: Page, companyName: string, signIn?: { source: RegExp; complete: () => Promise }) { await page.goto("/onboarding"); // Launcher card path (existing companies) — enter the wizard if the @@ -90,28 +84,21 @@ async function runOnboardingWizard(page: Page, companyName: string) { // — the row is a question, not a confirmation — so the CTA is disabled until // a tile is pressed. By role rather than by label: which adapters the tiles // offer depends on the registry this environment reports. - const source = page.getByRole("radio").first(); + const source = signIn ? page.getByRole("radio", { name: signIn.source }) : page.getByRole("radio").first(); await source.waitFor({ timeout: 30_000 }); await source.click(); - // "Connect", not "Next": this step's button starts the sign-in where there - // is one to start, so it is named for what it does. This test simulates - // successful local account connection before the environment check and hire. - // - // Waited on for enabled rather than for visible: it is already on screen, - // disabled, and clicking a disabled button raises nothing and does nothing. - const connectNext = page.getByRole("button", { name: /^Connect$/ }); - await expect(connectNext).toBeEnabled({ timeout: 30_000 }); - await connectNext.click(); + // A verified account, or pasting its authorization code, continues + // automatically through the environment check and hire. + if (signIn) await signIn.complete(); - // Step 5: review → Get started creates the first task and opens its - // detail page. + // Step 5: review → Get started opens the standing chat. const getStarted = page.getByRole("button", { name: /Get started/ }); await getStarted.waitFor({ timeout: 20_000 }); await getStarted.click(); } -async function assertFirstTaskExists(page: Page, companyName: string) { +async function assertOnlyChatExists(page: Page, companyName: string) { const companiesRes = await page.request.get("/api/companies"); expect(companiesRes.ok()).toBe(true); const companies = await companiesRes.json(); @@ -123,32 +110,69 @@ async function assertFirstTaskExists(page: Page, companyName: string) { const issuesRes = await page.request.get(`/api/companies/${company.id}/issues`); expect(issuesRes.ok()).toBe(true); const issues = await issuesRes.json(); - const firstTask = issues.find( - (candidate: { title: string }) => candidate.title === FIRST_TASK_TITLE, - ); - expect(firstTask).toBeTruthy(); - await expect(page.getByText(FIRST_TASK_TITLE).first()).toBeVisible({ - timeout: 15_000, - }); + expect(issues).toEqual([]); + const projectsRes = await page.request.get(`/api/companies/${company.id}/projects`); + expect(projectsRes.ok()).toBe(true); + expect(await projectsRes.json()).toEqual([]); + const chatsRes = await page.request.get(`/api/companies/${company.id}/chats`); + expect(chatsRes.ok()).toBe(true); + const chats = await chatsRes.json(); + expect(chats).toHaveLength(1); + expect(chats[0]).toMatchObject({ originKind: "onboarding_chat", projectId: null }); + await expect(page.getByTestId("task-chat-composer-add")).toBeVisible(); } -test.describe("First-task launch after onboarding wizard", () => { - test("creates the first task and opens its detail page", async ({ page, baseURL }) => { +test.describe("Chat launch after onboarding wizard", () => { + test("pasting a Claude code connects automatically and continues onboarding", async ({ page, baseURL }) => { + await installLaunchIntercepts(page, baseURL); + let verified = false; + let submissions = 0; + await page.route("**/ai-connections/local/attempts", route => route.fulfill({ status: 201, json: { + sessionId: "00000000-0000-4000-8000-000000000001", expiresAt: "2099-01-01T00:00:00Z", + } })); + await page.route("**/ai-connections/local/check", route => route.fulfill({ json: verified + ? { status: "ready" } + : { status: "sign_in_required", authorizationUrl: "https://claude.ai/oauth/authorize?fixture=auto-paste" }, + })); + await page.route("**/ai-connections/local/attempts/*/code", async route => { + expect(route.request().postDataJSON()).toEqual({ browserCode: "fixture-authorization-code" }); + submissions++; + verified = true; + await route.fulfill({ json: { ok: true } }); + }); + const companyName = `E2E-ClaudePaste-${Date.now()}`; + await runOnboardingWizard(page, companyName, { source: /Claude/, complete: async () => { + const code = page.getByRole("textbox", { name: "Authorization code", exact: true }); + await expect(code).toBeVisible({ timeout: 20_000 }); + await expect(page.getByRole("button", { name: "Connect", exact: true })).toBeDisabled(); + await code.evaluate(input => { + const clipboardData = new DataTransfer(); + clipboardData.setData("text/plain", "fixture-authorization-code"); + input.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true })); + }); + await expect(page.getByRole("status").filter({ hasText: "Finishing sign-in" })).toBeVisible(); + } }); + expect(submissions).toBe(1); + await assertOnlyChatExists(page, companyName); + }); + + test("opens chat without creating a task or project", async ({ page, baseURL }) => { await instrumentNavLog(page); await installLaunchIntercepts(page, baseURL); const companyName = `E2E-TypingIntro-${Date.now()}`; await runOnboardingWizard(page, companyName); - await expectLandsOnFirstTaskWithoutDashboardBounce(page); - await assertFirstTaskExists(page, companyName); + await expectLandsOnChatWithoutDashboardBounce(page); + await assertOnlyChatExists(page, companyName); + await page.screenshot({ path: test.info().outputPath("onboarding-chat.png"), fullPage: true }); }); // PAP-404 regression: the dashboard bounce only fires when the instance // already has a company for the route-sync effect to reset selection to. // Seed one first, then onboard a brand-new company and assert we still land - // on the first task without a dashboard bounce. - test("lands on the first task even when a company already exists", async ({ + // in chat without a dashboard bounce. + test("lands on chat even when a company already exists", async ({ page, baseURL, }) => { @@ -165,7 +189,7 @@ test.describe("First-task launch after onboarding wizard", () => { const companyName = `E2E-TypingIntro-Existing-${Date.now()}`; await runOnboardingWizard(page, companyName); - await expectLandsOnFirstTaskWithoutDashboardBounce(page); - await assertFirstTaskExists(page, companyName); + await expectLandsOnChatWithoutDashboardBounce(page); + await assertOnlyChatExists(page, companyName); }); }); diff --git a/tests/e2e/fixtures/agent-chat.mjs b/tests/e2e/fixtures/agent-chat.mjs index 2cbb19557a3..6408be1cc98 100644 --- a/tests/e2e/fixtures/agent-chat.mjs +++ b/tests/e2e/fixtures/agent-chat.mjs @@ -23,6 +23,10 @@ const ctx = run.contextSnapshot; const task = await api(`/issues/${ctx.issueId}`); const comment = async (body) => api(`/issues/${task.id}/comments`, "POST", { body }); +if (ctx.wakeReason === "onboarding_chat_greeting") { + await comment("Welcome to Paperclip! I'm your first agent teammate. Tell me what you'd like to achieve, or ask me to interview you so we can work it out together."); + process.exit(0); +} if (!task.conversationAgentId) { if (task.description?.includes("proactive-digest-fixture")) { await api("/agents/me/chat/messages", "POST", { diff --git a/tests/e2e/helpers/onboarding-ai-connection.ts b/tests/e2e/helpers/onboarding-ai-connection.ts index 94c1abaadea..19ded418ea5 100644 --- a/tests/e2e/helpers/onboarding-ai-connection.ts +++ b/tests/e2e/helpers/onboarding-ai-connection.ts @@ -6,6 +6,12 @@ import { expect, type Page } from "@playwright/test"; export async function mockOnboardingLocalAiConnection(page: Page) { const connectionId = randomUUID(); const grantId = randomUUID(); + const sessionId = randomUUID(); + await page.route("**/ai-connections/local/attempts", route => route.fulfill({ status: 201, json: { + sessionId, expiresAt: "2099-01-01T00:00:00Z", + } })); + await page.route("**/ai-connections/local/check", route => route.fulfill({ json: { status: "ready" } })); + await page.route("**/ai-connections/local/attempts/*", route => route.fulfill({ json: { ok: true } })); await page.route("**/ai-connections/local", async (route) => { expect(route.request().method()).toBe("POST"); expect(route.request().postDataJSON()).toMatchObject({ method: "subscription", ownership: "personal" }); diff --git a/tests/e2e/helpers/onboarding-landing.ts b/tests/e2e/helpers/onboarding-landing.ts index 3d3700502c2..6244967ad27 100644 --- a/tests/e2e/helpers/onboarding-landing.ts +++ b/tests/e2e/helpers/onboarding-landing.ts @@ -2,9 +2,9 @@ import { expect, type Page } from "@playwright/test"; /** * Regression guard for PAP-404: onboarding must land the user on the newly - * created first-task detail page and must NOT bounce to the company dashboard. + * created agent chat and must NOT bounce to the company dashboard. * - * The bounce is a navigation race: the wizard `navigate(/…/issues/…)` used to + * The bounce is a navigation race: the wizard `navigate(/…/chats/…)` used to * be clobbered by `useCompanyPageMemory`, which restores a company's remembered * page (falling back to `/dashboard`) on a non-`route_sync` selection change. * @@ -15,7 +15,7 @@ import { expect, type Page } from "@playwright/test"; * one that later self-corrects) leaves a trace in the log. */ -const ISSUE_URL = /\/issues\/[^/]+$/; +const CHAT_URL = /\/chats\/[^/]+$/; const DASHBOARD_PATH = /\/dashboard(\/|$)/; /** @@ -50,26 +50,26 @@ async function readNavLog(page: Page): Promise { } /** - * Assert the wizard settled on the first-task detail page and never rested on + * Assert the wizard settled on the agent chat and never rested on * (or bounced through) the dashboard. * * Fails if a dashboard bounce is reintroduced: the History-API log will contain - * a `/dashboard` entry and/or the settled URL will not be the issue page. + * a `/dashboard` entry and/or the settled URL will not be the chat page. */ -export async function expectLandsOnFirstTaskWithoutDashboardBounce( +export async function expectLandsOnChatWithoutDashboardBounce( page: Page, ): Promise { - // The wizard's launch handler does async work (hire + create issue) before - // navigating, so give reaching the issue page a generous budget. - await expect(page).toHaveURL(ISSUE_URL, { timeout: 30_000 }); + // The wizard's launch handler does async work (hire + open chat) before + // navigating, so give reaching the chat page a generous budget. + await expect(page).toHaveURL(CHAT_URL, { timeout: 30_000 }); const settledUrl = page.url(); // Short settle window: the page-memory effect fires on the selection change // that accompanies the launch navigate, so any bounce lands within ~1s. If - // the URL is still the issue after this window it has genuinely settled. + // the URL is still the chat after this window it has genuinely settled. await page.waitForTimeout(1_500); - expect(page.url(), "onboarding bounced away from the first task").toBe(settledUrl); - await expect(page).toHaveURL(ISSUE_URL); + expect(page.url(), "onboarding bounced away from the chat").toBe(settledUrl); + await expect(page).toHaveURL(CHAT_URL); const navLog = await readNavLog(page); const bounced = navLog.filter((path) => DASHBOARD_PATH.test(path)); diff --git a/tests/e2e/planning-mode-visual-verification.spec.ts b/tests/e2e/planning-mode-visual-verification.spec.ts index 818f8de1bec..785ae5a2b94 100644 --- a/tests/e2e/planning-mode-visual-verification.spec.ts +++ b/tests/e2e/planning-mode-visual-verification.spec.ts @@ -1,7 +1,7 @@ import { expect, test } from "@playwright/test"; import { mockOnboardingLocalAiConnection } from "./helpers/onboarding-ai-connection"; import { - expectLandsOnFirstTaskWithoutDashboardBounce, + expectLandsOnChatWithoutDashboardBounce, instrumentNavLog, } from "./helpers/onboarding-landing"; @@ -32,6 +32,7 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => { await instrumentNavLog(page); await mockOnboardingLocalAiConnection(page); + await page.route("**/onboarding/greeting", route => route.fulfill({ json: { started: false } })); await page.route("**/test-environment", (route) => route.fulfill({ @@ -88,27 +89,19 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => { // The connect step arrives with no source selected — the tile row is a // question, not a confirmation — so its CTA stays disabled until one is - // pressed. It reads "Connect", not "Next": the button starts the sign-in - // where there is one to start. The test simulates successful local account - // connection, then exercises the real first-task creation flow. - // - // Waited on for enabled rather than visible: it is already on screen, and - // clicking a disabled button raises nothing and does nothing. + // pressed. The simulated verified account then advances automatically. const source = page.getByRole("radio").first(); await source.waitFor({ timeout: 30_000 }); await source.click(); - const connectNext = page.getByRole("button", { name: /^Connect$/ }); - await expect(connectNext).toBeEnabled({ timeout: 30_000 }); - await connectNext.click(); // The review step names the agent rather than the step. await expect( page.getByRole("heading", { name: "Let's get started..." }), ).toBeVisible({ timeout: 30_000 }); await page.getByRole("button", { name: /Get started/ }).click(); - // The wizard now drops the user straight onto the first task's detail page, + // The wizard opens the standing chat, // and must not bounce through the dashboard (PAP-404). - await expectLandsOnFirstTaskWithoutDashboardBounce(page); + await expectLandsOnChatWithoutDashboardBounce(page); const baseOrigin = new URL(page.url()).origin; const companyRes = await page.request.get(`${baseOrigin}/api/companies`); @@ -119,13 +112,16 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => { const issueRes = await page.request.get(`${baseOrigin}/api/companies/${company.id}/issues`); expect(issueRes.ok()).toBe(true); const issues = await issueRes.json(); - const planningSeedIssue = issues.find( - (candidate: { id: string; identifier?: string; title: string }) => - candidate.title === TASK_TITLE, - ); - expect(planningSeedIssue).toBeTruthy(); - - const issue = planningSeedIssue; + expect(issues).toEqual([]); + const agentsRes = await page.request.get(`${baseOrigin}/api/companies/${company.id}/agents`); + const [agent] = await agentsRes.json(); + // This suite explicitly creates its legacy planning/question fixture; the + // onboarding wizard itself must leave execution work empty. + const created = await page.request.post(`${baseOrigin}/api/companies/${company.id}/issues`, { + data: { title: TASK_TITLE, assigneeAgentId: agent.id, onboardingFirstTask: true, status: "todo" }, + }); + expect(created.ok()).toBe(true); + const issue = await created.json(); const issueIdentifier = issue.identifier ?? issue.id; const issuePath = `/${company.issuePrefix ?? company.id}/issues/${issueIdentifier}`; const companyPrefix = company.issuePrefix ?? company.id; diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 8c415581222..340998e9394 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -229,7 +229,7 @@ "packages/shared/src/connector-availability.ts": "82aec0dfb2e9b8cb04e21c4bcd9aab74b087c76a", "packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a", "packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955", - "packages/shared/src/constants.ts": "698b73db1661e18bd435a9dfef5f3804fcf0612a", + "packages/shared/src/constants.ts": "9762160217907b1a3cc33f3dc9f86b46afae2cdd", "packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c", "packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2", "packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe", @@ -268,7 +268,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "0ee8c415f1dc36e4aec1a44b8e2e1a8f59885668", + "packages/shared/src/index.ts": "bc4373e3956c06613f3214706824a93050a757cf", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", diff --git a/ui/src/api/agentChats.ts b/ui/src/api/agentChats.ts index 0d565e73b22..9cba7dbd6f2 100644 --- a/ui/src/api/agentChats.ts +++ b/ui/src/api/agentChats.ts @@ -1,6 +1,12 @@ import type { Issue } from "@paperclipai/shared"; import { api } from "./client"; export const agentChatsApi = { + startOnboarding: (companyId: string, agentRef: string) => api.post( + `/companies/${companyId}/chats/${encodeURIComponent(agentRef)}/onboarding`, {}, + ), + greet: (companyId: string, agentRef: string) => api.post<{ started: boolean }>( + `/companies/${companyId}/chats/${encodeURIComponent(agentRef)}/onboarding/greeting`, {}, + ), list: (companyId: string) => api.get(`/companies/${companyId}/chats`), get: (companyId: string, agentRef: string) => api.get( diff --git a/ui/src/api/attention.test.ts b/ui/src/api/attention.test.ts index 9caf14d2720..bf820937d18 100644 --- a/ui/src/api/attention.test.ts +++ b/ui/src/api/attention.test.ts @@ -26,6 +26,7 @@ describe("attentionApi.list", () => { expect(mockApi.get).toHaveBeenCalledWith( "/companies/company-1/attention?includeDismissed=true&archived=true&activitySince=2026-08-01T00%3A00%3A00.000Z&activityUntil=2026-08-01T23%3A59%3A59.999Z&queue=release+review&sort=decide&cursor=next%2Fpage&limit=25", + { fresh: true, cache: "no-store" }, ); }); @@ -34,13 +35,14 @@ describe("attentionApi.list", () => { expect(mockApi.get).toHaveBeenCalledWith( "/companies/company-1/attention?all=true&queue=release+review", + { fresh: true, cache: "no-store" }, ); }); it("omits the query delimiter when no options are supplied", async () => { await attentionApi.list("company-1"); - expect(mockApi.get).toHaveBeenCalledWith("/companies/company-1/attention"); + expect(mockApi.get).toHaveBeenCalledWith("/companies/company-1/attention", { fresh: true, cache: "no-store" }); }); it("requests the complete task membership without decision card bodies", async () => { diff --git a/ui/src/api/attention.ts b/ui/src/api/attention.ts index e0986442652..5ccb8c68ccb 100644 --- a/ui/src/api/attention.ts +++ b/ui/src/api/attention.ts @@ -44,7 +44,8 @@ export const attentionApi = { if (options.cursor) params.set("cursor", options.cursor); if (options.limit !== undefined) params.set("limit", String(options.limit)); const query = params.toString(); - return api.get(`/companies/${companyId}/attention${query ? `?${query}` : ""}`); + // A post-answer refresh must not join a GET begun before the answer. + return api.get(`/companies/${companyId}/attention${query ? `?${query}` : ""}`, { fresh: true, cache: "no-store" }); }, /** Claim an Unassigned card: you become its addressee (PAP-749 plan §1, Rule 3). */ claim: (companyId: string, sourceKind: AttentionSourceKind, sourceId: string) => diff --git a/ui/src/api/issues.ts b/ui/src/api/issues.ts index bbc5b17fa93..bf2d4339821 100644 --- a/ui/src/api/issues.ts +++ b/ui/src/api/issues.ts @@ -614,7 +614,7 @@ export const issuesApi = { data, ), listInteractions: (id: string) => - api.get(`/issues/${id}/interactions`), + api.get(`/issues/${id}/interactions`, { fresh: true, cache: "no-store" }), listAcceptedPlanDecompositions: (id: string) => api.get( `/issues/${id}/accepted-plan-decompositions`, diff --git a/ui/src/components/AdapterLoginChrome.tsx b/ui/src/components/AdapterLoginChrome.tsx index 5d0d7e55d9f..634645eea47 100644 --- a/ui/src/components/AdapterLoginChrome.tsx +++ b/ui/src/components/AdapterLoginChrome.tsx @@ -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) => 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(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) { + 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

Preparing sign-in…

; const ready = login?.status === "ready"; + const awaitingBrowserSignIn = browserLogin && !ready && !login?.authorizationUrl && !login?.error; return
{ready ? <>

{login?.accountLabel ?? provider} is signed in. Click Connect to use this account.

{!showCommand && } : !browserLogin &&

{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.`}

} - {browserLogin && !ready && !login?.authorizationUrl && !login?.error &&

Preparing browser sign-in…

} - {browserLogin && !ready && !login?.error && login?.authorizationUrl && Preparing browser sign-in…

} + {(submitting || codeSubmitted) && !ready && !login?.error &&

Finishing sign-in…

} + {browserLogin && !ready && !submitting && !codeSubmitted && !login?.error && login?.authorizationUrl && void submitBrowserCode()} disabled={submitting} /> @@ -544,6 +571,6 @@ export function LocalProviderLoginInstructions({ adapterType, login }: {
} } {login?.error &&

{login.error}

} - {login && !login.preparing && !ready && (isolated || login.error) && } + {login && !login.preparing && !ready && !awaitingBrowserSignIn && (isolated || login.error) && } ; } diff --git a/ui/src/components/AttentionInteractionResolver.tsx b/ui/src/components/AttentionInteractionResolver.tsx index c292de0a70b..2eb0da2ad22 100644 --- a/ui/src/components/AttentionInteractionResolver.tsx +++ b/ui/src/components/AttentionInteractionResolver.tsx @@ -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); }; diff --git a/ui/src/components/OnboardingWizard.test.tsx b/ui/src/components/OnboardingWizard.test.tsx index 2e6e9993e94..bc596d08f45 100644 --- a/ui/src/components/OnboardingWizard.test.tsx +++ b/ui/src/components/OnboardingWizard.test.tsx @@ -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 }]; + 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(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(); diff --git a/ui/src/components/OnboardingWizard.tsx b/ui/src/components/OnboardingWizard.tsx index a5e1eb0f383..d74842a8279 100644 --- a/ui/src/components/OnboardingWizard.tsx +++ b/ui/src/components/OnboardingWizard.tsx @@ -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( (saved?.createdCompanyGoalId as string) ?? null ); - const [createdProjectId, setCreatedProjectId] = useState( - (saved?.createdProjectId as string) ?? null - ); - const [createdIssueRef, setCreatedIssueRef] = useState( - (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(); }} /> )} diff --git a/ui/src/components/ai-connections/useLocalAiLogin.test.tsx b/ui/src/components/ai-connections/useLocalAiLogin.test.tsx index d97385d3e1b..75e459924c5 100644 --- a/ui/src/components/ai-connections/useLocalAiLogin.test.tsx +++ b/ui/src/components/ai-connections/useLocalAiLogin.test.tsx @@ -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()); + 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()); @@ -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(resolve => { finishSubmit = resolve; })); + api.checkLocalLogin.mockResolvedValue({ status: "sign_in_required", authorizationUrl: "https://claude.ai/oauth/authorize?client_id=test" }); + flushSync(() => root.render()); + 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()); diff --git a/ui/src/components/task-chat/TaskChatComposer.tsx b/ui/src/components/task-chat/TaskChatComposer.tsx index 54898e6682d..972ebd4f009 100644 --- a/ui/src/components/task-chat/TaskChatComposer.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.tsx @@ -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}`; } } diff --git a/ui/src/context/LiveUpdatesProvider.test.ts b/ui/src/context/LiveUpdatesProvider.test.ts index fbb7981015d..ca7156853e5 100644 --- a/ui/src/context/LiveUpdatesProvider.test.ts +++ b/ui/src/context/LiveUpdatesProvider.test.ts @@ -33,12 +33,17 @@ describe("LiveUpdatesProvider issue invalidation", () => { it.each(["issue.thread_interaction_accepted", "issue.thread_interaction_answered", "decision.decided", "decision.effect_succeeded", "decision.effect_failed", "issue.conversation_session_started", "inbox.dismissed", "inbox.snoozed", "inbox.restored"])("refreshes canonical attention, history and source-chat projections after %s", action => { const client = new QueryClient(); const invalidate = vi.spyOn(client, "invalidateQueries"); + const cancel = vi.spyOn(client, "cancelQueries"); __liveUpdatesTestUtils.invalidateActivityQueries(client, "company-1", { entityType: action.startsWith("decision.") ? "decision" : "issue", entityId: "task-1", action, }, { userId: "user-1", agentId: null }); for (const queryKey of [queryKeys.attention("company-1"), ["decisions", "company-1"], ["issues", "decision-receipts"], ["issues", "chat-handoffs"], ["issues", "pending-questions"]]) { expect(invalidate).toHaveBeenCalledWith({ queryKey }); } + if (action.startsWith("issue.thread_interaction_")) { + expect(cancel).toHaveBeenCalledWith({ queryKey: queryKeys.attention("company-1") }); + expect(cancel).toHaveBeenCalledWith({ queryKey: ["issues", "interactions"] }); + } client.clear(); }); it("refreshes cached tasks whose relation summaries embed a changed blocker", () => { diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx index 65a5d0fc553..4c9ed94c52c 100644 --- a/ui/src/context/LiveUpdatesProvider.tsx +++ b/ui/src/context/LiveUpdatesProvider.tsx @@ -5,6 +5,7 @@ import { createLiveQueryRecovery } from "../lib/live-query-recovery"; import { isLiveReconciledQuery } from "../lib/live-reconcile"; import { refreshPendingTaskBrowserReads, refreshTaskBrowsers } from "../lib/task-browsers-refresh"; import { refreshRecentSubtasks, refreshRecentTaskSummaries } from "../lib/recent-subtasks-refresh"; +import { invalidateInteractionRecordViews } from "../lib/attention-record-views"; import { createContext, useCallback, @@ -1642,6 +1643,9 @@ function invalidateActivityQueries( void queryClient.resetQueries({ queryKey }); } } else if (decisionProjectionChanged) { + if (action?.startsWith("issue.thread_interaction_")) { + invalidateInteractionRecordViews(queryClient, companyId); + } queryClient.invalidateQueries({ queryKey: queryKeys.attention(companyId) }); queryClient.invalidateQueries({ queryKey: ["decisions", companyId] }); queryClient.invalidateQueries({ queryKey: queryKeys.decisionQueues.list(companyId) }); diff --git a/ui/src/lib/attention-record-views.sync.test.ts b/ui/src/lib/attention-record-views.sync.test.ts new file mode 100644 index 00000000000..1f521f51634 --- /dev/null +++ b/ui/src/lib/attention-record-views.sync.test.ts @@ -0,0 +1,62 @@ +import { QueryClient, QueryObserver } from "@tanstack/react-query"; +import { afterEach, expect, it, vi } from "vitest"; +import { attentionApi } from "../api/attention"; +import { detachInflightGets } from "../api/client"; +import { coordinatorAttentionQueryKey } from "./coordinator-attention"; +import { invalidateInteractionRecordViews } from "./attention-record-views"; +import { coordinatorTaskQuestion } from "../fixtures/coordinatorTaskQuestion"; +import { queryKeys } from "./queryKeys"; + +afterEach(() => { detachInflightGets(); vi.unstubAllGlobals(); }); + +it("publishes an answer to both task references without changing another question", () => { + const client = new QueryClient(); + const question = coordinatorTaskQuestion; + const other = { ...question, id: "another-question" }; + const uuidKey = queryKeys.issues.interactions(question.issueId); + const identifierKey = queryKeys.issues.interactions("BOB-1"); + const unrelatedKey = queryKeys.issues.interactions("unrelated-task"); + client.setQueryData(uuidKey, [question, other]); + client.setQueryData(identifierKey, [question]); + client.setQueryData(unrelatedKey, [other]); + const answered = { ...question, status: "answered" as const }; + invalidateInteractionRecordViews(client, question.companyId, answered); + expect(client.getQueryData(uuidKey)).toEqual([answered, other]); + expect(client.getQueryData(identifierKey)).toEqual([answered]); + expect(client.getQueryData(unrelatedKey)).toEqual([other]); + client.clear(); +}); + +it.each(["initial", "background"])("does not restore an answered question from a pre-answer %s inbox read", async mode => { + let reads = 0; + const oldRead = mode === "initial" ? 1 : 2; + let releaseOldRead!: () => void; + const question = { id: "question-card", sourceKind: "issue_thread_interaction", subject: { id: "question" } }; + vi.stubGlobal("fetch", vi.fn(async () => { + const read = ++reads; + if (read === oldRead) await new Promise(resolve => { releaseOldRead = resolve; }); + return new Response(JSON.stringify({ items: read <= oldRead ? [question] : [], deskBadgeCount: read <= oldRead ? 1 : 0 }), { + headers: { "Content-Type": "application/json" }, + }); + })); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const key = coordinatorAttentionQueryKey("company", "person", "mine"); + const observer = new QueryObserver(client, { queryKey: key, queryFn: () => attentionApi.list("company", { all: true, view: "mine" }) }); + const unsubscribe = observer.subscribe(() => {}); + try { + if (mode === "background") { + await vi.waitFor(() => expect(observer.getCurrentResult().data?.items).toEqual([question])); + void observer.refetch(); + } + await vi.waitFor(() => expect(reads).toBe(oldRead)); + invalidateInteractionRecordViews(client, "company"); + await vi.waitFor(() => expect(reads).toBe(oldRead + 1)); + await vi.waitFor(() => expect(observer.getCurrentResult().data?.items).toEqual([])); + releaseOldRead(); + await new Promise(resolve => setTimeout(resolve, 0)); + expect(observer.getCurrentResult().data?.items).toEqual([]); + expect(observer.getCurrentResult().data?.deskBadgeCount).toBe(0); + } finally { + releaseOldRead?.(); unsubscribe(); client.clear(); + } +}); diff --git a/ui/src/lib/attention-record-views.ts b/ui/src/lib/attention-record-views.ts index 80fa3f5a9d2..5d6e2079dde 100644 --- a/ui/src/lib/attention-record-views.ts +++ b/ui/src/lib/attention-record-views.ts @@ -1,6 +1,7 @@ import type { QueryClient } from "@tanstack/react-query"; import type { AttentionItem } from "@paperclipai/shared"; import { queryKeys } from "./queryKeys"; +import type { IssueThreadInteraction } from "./issue-thread-interactions"; /** * One record, many views (PAP-749 design review, Part 2). A card's source @@ -58,9 +59,20 @@ export function invalidateAttentionRecordViews(queryClient: QueryClient, company * the task's interaction list under both its UUID and its identifier key. * Other people's tabs get the same change from LiveUpdatesProvider. */ -export function invalidateInteractionRecordViews(queryClient: QueryClient, companyId: string) { - void queryClient.invalidateQueries({ queryKey: ["issues", "interactions"] }); - void queryClient.invalidateQueries({ queryKey: queryKeys.attention(companyId) }); - void queryClient.invalidateQueries({ queryKey: ["issues", "pending-questions"] }); - void queryClient.invalidateQueries({ queryKey: ["issues", "decision-receipts"] }); +export function invalidateInteractionRecordViews(queryClient: QueryClient, companyId: string, interaction?: IssueThreadInteraction) { + const keys = [["issues", "interactions"], queryKeys.attention(companyId), ["issues", "pending-questions"], ["issues", "decision-receipts"]]; + // Initial reads can also predate this write. Cancel before invalidation so + // they cannot restore a question that has already been answered. + for (const queryKey of keys) { + void queryClient.cancelQueries({ queryKey }); + } + if (interaction) { + // UUID and identifier routes can both be mounted. Give every cached copy + // the same canonical receipt before their authoritative reads complete. + queryClient.setQueriesData( + { queryKey: ["issues", "interactions"] }, + current => current?.map(entry => entry.id === interaction.id ? interaction : entry), + ); + } + for (const queryKey of keys) void queryClient.invalidateQueries({ queryKey }); } diff --git a/ui/src/lib/onboarding-chat.test.ts b/ui/src/lib/onboarding-chat.test.ts new file mode 100644 index 00000000000..85126bbb5b2 --- /dev/null +++ b/ui/src/lib/onboarding-chat.test.ts @@ -0,0 +1,38 @@ +// @vitest-environment jsdom +import { afterEach, expect, it, vi } from "vitest"; +import { afterVisibleConversationPaint } from "./onboarding-chat"; + +afterEach(() => vi.restoreAllMocks()); + +it("waits for a visible tab and two painted frames, then starts once", () => { + const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden"); + const frames: FrameRequestCallback[] = []; + vi.spyOn(window, "requestAnimationFrame").mockImplementation(callback => frames.push(callback)); + vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => {}); + const start = vi.fn(); + const cancel = afterVisibleConversationPaint(start); + expect(frames).toHaveLength(0); + visibility.mockReturnValue("visible"); + document.dispatchEvent(new Event("visibilitychange")); + expect(start).not.toHaveBeenCalled(); + frames.shift()!(0); + expect(start).not.toHaveBeenCalled(); + frames.shift()!(1); + expect(start).toHaveBeenCalledTimes(1); + document.dispatchEvent(new Event("visibilitychange")); + expect(frames).toHaveLength(0); + cancel(); +}); + +it("does not start after unmount, including a pending second frame", () => { + vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible"); + const frames: FrameRequestCallback[] = []; + vi.spyOn(window, "requestAnimationFrame").mockImplementation(callback => frames.push(callback)); + vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => {}); + const start = vi.fn(); + const cancel = afterVisibleConversationPaint(start); + frames.shift()!(0); + cancel(); + frames.shift()!(1); + expect(start).not.toHaveBeenCalled(); +}); diff --git a/ui/src/lib/onboarding-chat.ts b/ui/src/lib/onboarding-chat.ts new file mode 100644 index 00000000000..3fa78baf19b --- /dev/null +++ b/ui/src/lib/onboarding-chat.ts @@ -0,0 +1,24 @@ +/** The welcome starts only once the conversation has painted in a visible tab. */ +export function afterVisibleConversationPaint(start: () => void): () => void { + let firstFrame = 0; + let secondFrame = 0; + let cancelled = false; + let started = false; + const schedule = () => { + if (document.visibilityState === "hidden" || cancelled || started || firstFrame) return; + firstFrame = requestAnimationFrame(() => { + secondFrame = requestAnimationFrame(() => { + firstFrame = 0; + if (!cancelled && document.visibilityState !== "hidden") { started = true; start(); } + }); + }); + }; + document.addEventListener("visibilitychange", schedule); + schedule(); + return () => { + cancelled = true; + cancelAnimationFrame(firstFrame); + cancelAnimationFrame(secondFrame); + document.removeEventListener("visibilitychange", schedule); + }; +} diff --git a/ui/src/lib/onboarding-launch.test.ts b/ui/src/lib/onboarding-launch.test.ts index 1eff9eec331..f0bc9a67320 100644 --- a/ui/src/lib/onboarding-launch.test.ts +++ b/ui/src/lib/onboarding-launch.test.ts @@ -1,10 +1,5 @@ import { describe, expect, it } from "vitest"; -import { - buildOnboardingIssuePayload, - buildOnboardingProjectPayload, - selectDefaultCompanyGoalId, - selectReusableOnboardingProject, -} from "./onboarding-launch"; +import { selectDefaultCompanyGoalId } from "./onboarding-launch"; describe("selectDefaultCompanyGoalId", () => { it("prefers the earliest active root company goal", () => { @@ -81,78 +76,3 @@ describe("selectDefaultCompanyGoalId", () => { ).toBe("goal-1"); }); }); - -describe("onboarding launch payloads", () => { - it("reuses a non-cancelled Onboarding project by name", () => { - expect( - selectReusableOnboardingProject([ - { id: "cancelled", name: "Onboarding", status: "cancelled" }, - { id: "active", name: " onboarding ", status: "in_progress" }, - ]), - ).toEqual({ id: "active", name: " onboarding ", status: "in_progress" }); - - expect( - selectReusableOnboardingProject([ - { id: "cancelled", name: "Onboarding", status: "cancelled" }, - { id: "other", name: "Roadmap", status: "in_progress" }, - ]), - ).toBeNull(); - }); - - it("links the onboarding project and first issue to the selected goal", () => { - expect(buildOnboardingProjectPayload("goal-1")).toEqual({ - name: "Onboarding", - status: "in_progress", - goalIds: ["goal-1"], - }); - - expect( - buildOnboardingIssuePayload({ - title: " Hire your first engineer ", - assigneeAgentId: "agent-1", - projectId: "project-1", - goalId: "goal-1", - }), - ).toEqual({ - title: "Hire your first engineer", - assigneeAgentId: "agent-1", - projectId: "project-1", - goalId: "goal-1", - status: "todo", - onboardingFirstTask: true, - }); - }); - - it("sends no client description — the server owns the first task's brief", () => { - const payload = buildOnboardingIssuePayload({ - title: "Task", - assigneeAgentId: "agent-1", - projectId: "project-1", - goalId: null, - }); - expect(payload).not.toHaveProperty("description"); - expect(payload.onboardingFirstTask).toBe(true); - }); - - it("omits goal links when no default company goal exists", () => { - expect(buildOnboardingProjectPayload(null)).toEqual({ - name: "Onboarding", - status: "in_progress", - }); - - expect( - buildOnboardingIssuePayload({ - title: "Task", - assigneeAgentId: "agent-1", - projectId: "project-1", - goalId: null, - }), - ).toEqual({ - title: "Task", - assigneeAgentId: "agent-1", - projectId: "project-1", - status: "todo", - onboardingFirstTask: true, - }); - }); -}); diff --git a/ui/src/lib/onboarding-launch.ts b/ui/src/lib/onboarding-launch.ts index cea82dda433..97d7b9fc80c 100644 --- a/ui/src/lib/onboarding-launch.ts +++ b/ui/src/lib/onboarding-launch.ts @@ -1,6 +1,4 @@ -import type { Goal, Project } from "@paperclipai/shared"; - -export const ONBOARDING_PROJECT_NAME = "Onboarding"; +import type { Goal } from "@paperclipai/shared"; function goalCreatedAt(goal: Goal) { const createdAt = goal.createdAt instanceof Date ? goal.createdAt : new Date(goal.createdAt); @@ -23,46 +21,3 @@ export function selectDefaultCompanyGoalId(goals: Goal[]): string | null { null ); } - -export function buildOnboardingProjectPayload(goalId: string | null) { - return { - name: ONBOARDING_PROJECT_NAME, - status: "in_progress" as const, - ...(goalId ? { goalIds: [goalId] } : {}), - }; -} - -export function selectReusableOnboardingProject>( - projects: T[], -): T | null { - return ( - projects.find( - (project) => - project.status !== "cancelled" && - project.name.trim().toLowerCase() === ONBOARDING_PROJECT_NAME.toLowerCase(), - ) ?? null - ); -} - -export function buildOnboardingIssuePayload(input: { - title: string; - assigneeAgentId: string; - projectId: string; - goalId: string | null; -}) { - const title = input.title.trim(); - - return { - title, - // No client description: the server assembles the first task's brief from - // its own markdown and ignores any description sent here. - assigneeAgentId: input.assigneeAgentId, - projectId: input.projectId, - ...(input.goalId ? { goalId: input.goalId } : {}), - status: "todo" as const, - // Marks the single onboarding first task so the server assembles + stores - // the brief, seeds the agent greeting, and the task-detail view suppresses - // the seeded-description bubble. - onboardingFirstTask: true, - }; -} diff --git a/ui/src/pages/AgentChat.test.tsx b/ui/src/pages/AgentChat.test.tsx index cbd03234a4c..c26e1a798cf 100644 --- a/ui/src/pages/AgentChat.test.tsx +++ b/ui/src/pages/AgentChat.test.tsx @@ -9,15 +9,18 @@ import { ApiError } from "@/api/client"; import { queryKeys } from "@/lib/queryKeys"; import { AgentChat } from "./AgentChat"; -const api = vi.hoisted(() => ({ enabled: true, list: vi.fn(), get: vi.fn(), getChat: vi.fn(), ensure: vi.fn(), session: vi.fn() })); +const api = vi.hoisted(() => ({ enabled: true, list: vi.fn(), get: vi.fn(), getChat: vi.fn(), ensure: vi.fn(), session: vi.fn(), greet: vi.fn(), onReady: undefined as (() => void) | undefined })); const agentId = "18c5ad50-9d70-4e24-bd82-337e1d45a414"; vi.mock("@/api/agents", () => ({ agentsApi: { list: api.list, get: api.get } })); -vi.mock("@/api/agentChats", () => ({ agentChatsApi: { get: api.getChat, ensure: api.ensure } })); +vi.mock("@/api/agentChats", () => ({ agentChatsApi: { get: api.getChat, ensure: api.ensure, greet: api.greet } })); vi.mock("@/api/auth", () => ({ authApi: { getSession: api.session } })); vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: "company-a" }) })); vi.mock("@/hooks/useAgentChatEnabled", () => ({ useAgentChatEnabled: () => ({ enabled: api.enabled, loaded: true }) })); vi.mock("@/lib/router", () => ({ useParams: () => ({ agentRef: "18c5ad50-9d70-4e24-bd82-337e1d45a414" }), Link: ({ to, children }: { to: string; children: React.ReactNode }) => {children} })); -vi.mock("./IssueDetail", () => ({ TaskDetailSurface: ({ conversation }: { conversation: { agent: Agent } }) =>
History for {conversation.agent.name}
})); +vi.mock("./IssueDetail", () => ({ TaskDetailSurface: ({ conversation }: { conversation: { agent: Agent; onReady?: () => void } }) => { + api.onReady = conversation.onReady; + return
History for {conversation.agent.name}
; +} })); let root: Root; let container: HTMLDivElement; @@ -43,6 +46,8 @@ async function failRoster(status: number, cached = true) { beforeEach(() => { vi.clearAllMocks(); api.enabled = true; + api.onReady = undefined; + api.greet.mockResolvedValue({ started: true }); client = new QueryClient({ defaultOptions: { queries: { retry: false, retryOnMount: false, staleTime: Infinity, gcTime: Infinity } } }); client.setQueryData(queryKeys.auth.session, { user: { id: "viewer-a" } }); api.session.mockResolvedValue({ user: { id: "viewer-a" } }); @@ -52,6 +57,26 @@ beforeEach(() => { }); afterEach(() => { flushSync(() => root.unmount()); client.clear(); container.remove(); }); +it("waits for the onboarding conversation to paint before requesting its live greeting", async () => { + const frames: FrameRequestCallback[] = []; + vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => frames.push(callback)); + vi.stubGlobal("cancelAnimationFrame", vi.fn()); + client.setQueryData(queryKeys.agents.list("company-a"), [{ id: agentId, companyId: "company-a", name: "Ada" }]); + api.getChat.mockResolvedValue({ id: "welcome-chat", originKind: "onboarding_chat" }); + try { + render(); + await waitFor(() => expect(container.textContent).toContain("History for Ada")); + expect(api.greet).not.toHaveBeenCalled(); + flushSync(() => api.onReady!()); + expect(api.greet).not.toHaveBeenCalled(); + frames.shift()!(0); + expect(api.greet).not.toHaveBeenCalled(); + frames.shift()!(1); + await waitFor(() => expect(api.greet).toHaveBeenCalledTimes(1)); + expect(api.greet).toHaveBeenCalledWith("company-a", agentId); + } finally { vi.unstubAllGlobals(); } +}); + it("explains when Agent Chat is disabled without creating a conversation", async () => { api.enabled = false; api.list.mockResolvedValue([{ id: agentId, companyId: "company-a", name: "Helper" }]); diff --git a/ui/src/pages/AgentChat.tsx b/ui/src/pages/AgentChat.tsx index 472261b3e6b..329596bfb0d 100644 --- a/ui/src/pages/AgentChat.tsx +++ b/ui/src/pages/AgentChat.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { agentChatsApi } from "@/api/agentChats"; import { agentsApi } from "@/api/agents"; @@ -12,6 +12,8 @@ import { Link, useParams } from "@/lib/router"; import { agentRouteRef } from "@/lib/utils"; import { TaskDetailSurface } from "./IssueDetail"; import { isUuidLike, type Issue } from "@paperclipai/shared"; +import { afterVisibleConversationPaint } from "@/lib/onboarding-chat"; +import { Button } from "@/components/ui/button"; export function AgentChat() { const { agentRef = "" } = useParams<{ agentRef: string }>(); @@ -58,6 +60,24 @@ export function AgentChat() { const historyView = useQueryView(historyAgent); const chatView = useQueryView(chat); const creating = useRef | null>(null); + const [readyIssueId, setReadyIssueId] = useState(null); + const [greetingError, setGreetingError] = useState(null); + const [greetingAttempt, setGreetingAttempt] = useState(0); + const onReady = useCallback(() => setReadyIssueId(chat.data?.id ?? null), [chat.data?.id]); + useEffect(() => { + setGreetingError(null); + if (!enabled || !agent || !selectedCompanyId || !session.isSuccess + || readyIssueId !== chat.data?.id || chat.data?.originKind !== "onboarding_chat") return; + let cancelled = false; + const cancelPaint = afterVisibleConversationPaint(() => { + void agentChatsApi.greet(selectedCompanyId, agent.id).then(() => { + if (!cancelled) void client.invalidateQueries({ queryKey: queryKeys.issues.detail(chat.data!.id) }); + }).catch(error => { + if (!cancelled) setGreetingError(error instanceof Error ? error.message : "The welcome could not start."); + }); + }); + return () => { cancelled = true; cancelPaint(); }; + }, [enabled, agent?.id, selectedCompanyId, userId, session.isSuccess, readyIssueId, chat.data?.id, chat.data?.originKind, greetingAttempt, client]); useEffect(() => { creating.current = null; }, [selectedCompanyId, userId, agent?.id]); @@ -117,9 +137,15 @@ export function AgentChat() {

Loading conversation…

); return ( - + <> + {greetingError &&
+ {greetingError} + +
} + + ); } diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index 935b43f473d..061aa6e1ce2 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -1,4 +1,5 @@ import { createUuid } from "@/lib/uuid"; +import { invalidateInteractionRecordViews } from "@/lib/attention-record-views"; import { companyProjectsQuery } from "@/lib/company-projects-query"; import { NativeControllerContainmentRecovery } from "../components/IssueRecoveryActionCard"; import { useIssueIdBatches } from "@/hooks/useIssueIdBatches"; @@ -3256,6 +3257,7 @@ export function IssueDetail({ tasksTab }: { tasksTab?: TaskSidePanelProps["tasks /** One controller and surface for both task URLs and agent conversations. */ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskSidePanelProps["tasksTab"]; conversation?: { agent: Agent; issue: Issue | null; ensureIssue: () => Promise; + onReady?: () => void; } }) { const { issueId: routeIssueId, companyPrefix } = useParams<{ issueId: string; companyPrefix: string }>(); const issueId = conversation ? conversation.issue?.id : routeIssueId; @@ -3562,7 +3564,9 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS [linkedComment.data, windowComments], ); + const contentNavigationStartedAt = useRef(Infinity); useLayoutEffect(() => { + contentNavigationStartedAt.current = performance.now(); beginIssueDetailNavigation(); }, [issueId]); // The task page is loaded when its conversation content has painted: the @@ -3570,6 +3574,9 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS // chat with no saved task never records that mark, so it uses the generic rule. const contentPaintedAt = useIssueDetailContentPaintedAt(); usePageContentReady(contentPaintedAt !== null, contentPaintedAt, { enabled: Boolean(issueId) }); + useEffect(() => { + if (contentPaintedAt !== null && contentPaintedAt >= contentNavigationStartedAt.current) conversation?.onReady?.(); + }, [contentPaintedAt, conversation?.onReady]); useEffect(() => { if (!(import.meta.env.DEV || import.meta.env.MODE === "qa")) return; @@ -4564,6 +4571,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS ); const upsertInteractionInCache = useCallback( (interaction: IssueThreadInteraction) => { + invalidateInteractionRecordViews(queryClient, interaction.companyId, interaction); queryClient.setQueryData( queryKeys.issues.interactions(issueId!), (current) => { @@ -4581,9 +4589,6 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS return next; }, ); - queryClient.invalidateQueries({ queryKey: ["issues", "pending-questions"] }); - queryClient.invalidateQueries({ queryKey: ["issues", "decision-receipts"] }); - queryClient.invalidateQueries({ queryKey: queryKeys.attention(interaction.companyId) }); }, [issueId, queryClient], );