From da00e353f4f42483298830bac004d768e0856723 Mon Sep 17 00:00:00 2001 From: Scott Tong Date: Tue, 17 Nov 2026 13:18:50 -0800 Subject: [PATCH] Keep standing chats out of the execution task sequence Co-Authored-By: Paperclip --- .../src/__tests__/agent-conversations.test.ts | 9 +++- .../__tests__/onboarding-chat-route.test.ts | 24 +++++++++- server/src/services/heartbeat/task-context.ts | 6 +++ .../src/services/heartbeat/task-markdown.ts | 8 ++-- server/src/services/issues.ts | 47 ++++++++++--------- 5 files changed, 66 insertions(+), 28 deletions(-) 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 index e1bed0187fb..6e36d727eb0 100644 --- a/server/src/__tests__/onboarding-chat-route.test.ts +++ b/server/src/__tests__/onboarding-chat-route.test.ts @@ -3,7 +3,7 @@ import express from "express"; import request from "supertest"; import { eq } from "drizzle-orm"; import { expect, it, vi } from "vitest"; -import { agents, agentWakeupRequests, authUsers, companyOnboardingSeeds, goals, heartbeatRuns, issues, projects } from "@paperclipai/db"; +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"; @@ -30,6 +30,26 @@ describeEmbeddedPostgres("onboarding chat", () => { 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" }); @@ -124,7 +144,7 @@ describeEmbeddedPostgres("onboarding chat", () => { 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 }); + 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/services/heartbeat/task-context.ts b/server/src/services/heartbeat/task-context.ts index a24543528a4..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, diff --git a/server/src/services/heartbeat/task-markdown.ts b/server/src/services/heartbeat/task-markdown.ts index d3bc2dc86dd..ef0bde0f691 100644 --- a/server/src/services/heartbeat/task-markdown.ts +++ b/server/src/services/heartbeat/task-markdown.ts @@ -7,6 +7,7 @@ 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: { @@ -92,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); diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 3d14f402788..59c3397c0f1 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,