mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
Emit Cloud chat.started when a chat with an agent starts (#23558)
<!-- claude-projects-attribution: {"github_login":"nguyenm7"} -->
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud measures activation with a funnel: account created,
org named, agent named, model connected, chat launched, first agent run
succeeded, first task created
> - `model.connected`, `agent.task_run` and `task.created` come from the
server, but "chat launched" comes only from the browser
(`onboarding_step_completed` with `step=launch`)
> - `task.created` skips chats on purpose, so a person who only chats
with their agent has no server-side step after "first agent run"
> - #23403 added a Cloud-only direct PostHog path
(`trackCloudPostHogEvent`) for onboarding events that must not depend on
the browser
> - This pull request uses that path to emit `chat.started` when the
chat owner's first message or first question-card answer commits
> - The benefit is a server-side "chat started" step that counts a real
action by the person, once per chat, whichever way they reached the chat
## Linked Issues or Issue Description
Refs #23403
**What existing behavior does this improve?**
Server-side activation funnels on Paperclip Cloud.
**Current behavior**
The only "chat launched" signal is the browser `launch` step. Browser
events can be lost (wizard skipped or resumed, navigation, ad blockers
on older builds). On the server, a chat creates an issue but
`emitTaskCreatedAfterCommit` returns early for it, so no event records
that the chat started.
**Proposed behavior**
When the chat owner's first turn commits (their first message, or their
first answer to a question card such as the onboarding welcome card),
the server emits the Cloud-only event `chat.started` with `surface`
(`onboarding_chat` | `agent_chat`) and `agent_id`. Creating or preparing
a chat emits nothing, because onboarding prepares the chat before the
person clicks Launch. The Launch click itself is already relayed
server-side as `onboarding_step_completed` (`step=launch`).
**Reason and benefit**
Funnel steps should come from real product actions that the server
records. With `chat.started`, a funnel can count "chat launched" from
the server and see people who chat but never create a task.
**Breaking changes**
None. The event is new and is Cloud-only.
## What Changed
- `server/src/services/product-telemetry.ts`: add `CHAT_STARTED_EVENT`
and `emitChatStartedIfFirstOwnerTurn`. It runs inside the transaction
that wrote the person's turn and locks the chat's issue row. It checks
that the actor is the chat owner (not an agent, run, or system actor),
and that the owner has no other message and no other answered question
card in the chat. Cancelled or skipped cards do not count. Then it emits
`chat.started` through `trackCloudPostHogEvent` after commit.
- Callers: `addComment` (`issues.ts`), `answerQuestions`
(`issue-thread-interactions.ts`), both headless comment paths
(`headless-comment-group-commit.ts` and the serialized insert in
`routes/headless-channels-schemas.ts`), and the headless one-line
resolve (`headless-events-schedules-interactions.ts`).
- `server/src/__tests__/chat-started-telemetry.test.ts`: unit tests for
the first turn, both surfaces, and every case that must not emit.
- `server/src/__tests__/product-telemetry.test.ts`: embedded-Postgres
tests. Chat creation and system or other-person messages emit nothing.
The owner's first message emits once. A first message after a cancelled
card still emits. A rolled-back first message and a task comment emit
nothing.
- `docs/api/onboarding-telemetry.md`: document the server-emitted
`chat.started` event.
## Verification
- `npx vitest run server/src/__tests__/chat-started-telemetry.test.ts`:
10 passed (helper unit tests).
- `pnpm --filter @paperclipai/server typecheck`: passed.
- The cases in `product-telemetry.test.ts` need embedded Postgres, which
could not start in my environment (it runs as root). CI runs them.
## Risks
- Low. The event is fire-and-forget after commit, inside a `try`. It
does nothing on self-hosted installs, when `PAPERCLIP_POSTHOG_DIRECT=0`,
or when the PostHog environment is not set.
- One event per chat: the check runs under the chat's issue row lock,
and a rolled-back write emits nothing. `/new` in an existing chat does
not emit again.
- Two extra indexed reads run on a person's chat message or answer, and
only on chats.
### Open questions for reviewers
1. **Consent.** Like `model.connected` and the #23403 relay, this server
event is not gated by the browser cookie banner. This PR does not add a
consent check. The only switch is the existing
`PAPERCLIP_POSTHOG_DIRECT=0`. If people who decline cookies must be
excluded from server-side product events, that should be one rule for
all Cloud direct events, not a rule in this PR.
2. **New name or existing name.** This PR adds a new name,
`chat.started`, instead of emitting `onboarding_step_completed`
(`step=launch`) from the server. A new name keeps the browser and server
signals separate, so the two funnels can be compared and the existing
insights do not double count. The other choice is to emit the existing
name with a `source: server` property. Please say which one you prefer.
Not in this PR: "Agent named" has no clean server moment (the setup
agent is saved with a default name before the person names it, and
`agent.created` fires at launch), and `agent.task_run` still does not
say whether a run was a chat reply or a task. That needs a new
registered dimension in the telemetry contract, so it is a follow-up.
## Model Used
Claude Code (Anthropic Claude, agentic coding with tool use and code
execution).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
https://claude.ai/code/session_01KmUZthscGtSrd1KaWnwzWm
---
_Generated by [Claude Code](https://claude.ai/code)_
---------
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
8379dedd93
commit
fc09515c7e
9 files changed
+316
-5
No files matched your search
@@ -75,3 +75,13 @@ and triggering message IDs as the send. It uses the run's triggering input to
|
|||||||
attribute the reply. A stored browser receipt suppresses repeat displays in
|
attribute the reply. A stored browser receipt suppresses repeat displays in
|
||||||
the same chat, including after reload. Count unique people in the funnel.
|
the same chat, including after reload. Count unique people in the funnel.
|
||||||
Historical run success cannot establish that a person saw a reply.
|
Historical run success cannot establish that a person saw a reply.
|
||||||
|
|
||||||
|
## Server-Emitted Chat Event
|
||||||
|
|
||||||
|
The browser events above depend on the wizard and on the browser. So Paperclip Cloud also emits `chat.started` from the server when a person actually starts a chat.
|
||||||
|
|
||||||
|
| Event | When | Properties |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `chat.started` | The chat owner's first turn in a chat with an agent commits: their first message (from the app or the headless API), or their first answer to a question card such as the onboarding welcome card. It fires once per chat. Opening or preparing a chat, cancelled or skipped question cards (including a headless one-line skip), system or agent messages, other people's messages, and rolled-back writes emit nothing. | `surface`: `onboarding_chat` \| `agent_chat`; `agent_id` |
|
||||||
|
|
||||||
|
Onboarding prepares the chat before the person clicks Launch, so chat creation is not used as the signal. `task.created` does not fire for chats, so `chat.started` is the server-side "chat started" step for activation funnels. The event goes only through direct PostHog delivery. Self-hosted installs and `PAPERCLIP_POSTHOG_DIRECT=0` emit nothing. The event uses the chat owner's user id as its distinct id, the same as the other server-side Cloud events.
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { issueComments, issues, issueThreadInteractions } from "@paperclipai/db";
|
||||||
|
|
||||||
|
const cloudEvents = vi.hoisted(() => [] as Array<{ event: string; properties: unknown; context: unknown }>);
|
||||||
|
|
||||||
|
vi.mock("../telemetry.js", () => ({
|
||||||
|
getTelemetryClient: () => null,
|
||||||
|
trackCloudPostHogEvent: (event: string, properties?: unknown, context?: unknown) => {
|
||||||
|
cloudEvents.push({ event, properties, context });
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { emitChatStartedIfFirstOwnerTurn } from "../services/product-telemetry.ts";
|
||||||
|
|
||||||
|
type Rows = { issue: unknown[]; comments: unknown[]; answers: unknown[] };
|
||||||
|
|
||||||
|
/** Minimal stand-in for the select chains the helper runs. */
|
||||||
|
function fakeTx(rows: Rows) {
|
||||||
|
const byTable = new Map<unknown, unknown[]>([
|
||||||
|
[issues, rows.issue],
|
||||||
|
[issueComments, rows.comments],
|
||||||
|
[issueThreadInteractions, rows.answers],
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
select: () => ({
|
||||||
|
from: (table: unknown) => ({
|
||||||
|
where: () => {
|
||||||
|
const result = Promise.resolve(byTable.get(table) ?? []);
|
||||||
|
return Object.assign(result, { limit: () => result, for: () => result });
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
} as never;
|
||||||
|
}
|
||||||
|
|
||||||
|
const chat = {
|
||||||
|
companyId: "company-1",
|
||||||
|
originKind: "onboarding_chat",
|
||||||
|
conversationAgentId: "agent-1",
|
||||||
|
conversationUserId: "user-1",
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("chat.started telemetry", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
cloudEvents.length = 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
it("emits once the chat owner's first turn is written", async () => {
|
||||||
|
await emitChatStartedIfFirstOwnerTurn(
|
||||||
|
fakeTx({ issue: [chat], comments: [], answers: [] }), { issueId: "chat-1", actor: { userId: "user-1" }, commentIds: ["c-1"] });
|
||||||
|
expect(cloudEvents).toEqual([
|
||||||
|
{ event: "chat.started", properties: { surface: "onboarding_chat", agent_id: "agent-1" }, context: { userId: "user-1", companyId: "company-1" } },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses the agent_chat surface outside onboarding", async () => {
|
||||||
|
await emitChatStartedIfFirstOwnerTurn(
|
||||||
|
fakeTx({ issue: [{ ...chat, originKind: "manual" }], comments: [], answers: [] }), { issueId: "chat-1", actor: { userId: "user-1" } });
|
||||||
|
expect(cloudEvents.map((entry) => entry.properties)).toEqual([{ surface: "agent_chat", agent_id: "agent-1" }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
["an earlier message", { issue: [chat], comments: [{ id: "c" }], answers: [] }, { userId: "user-1" }],
|
||||||
|
["an earlier answered card", { issue: [chat], comments: [], answers: [{ id: "i" }] }, { userId: "user-1" }],
|
||||||
|
["another person", { issue: [chat], comments: [], answers: [] }, { userId: "user-2" }],
|
||||||
|
["an agent", { issue: [chat], comments: [], answers: [] }, { userId: "user-1", agentId: "agent-1" }],
|
||||||
|
["a run", { issue: [chat], comments: [], answers: [] }, { userId: "user-1", runId: "run-1" }],
|
||||||
|
["the system", { issue: [chat], comments: [], answers: [] }, { userId: "user-1", systemId: "onboarding" }],
|
||||||
|
["a task", { issue: [{ ...chat, conversationAgentId: null }], comments: [], answers: [] }, { userId: "user-1" }],
|
||||||
|
["the local board", { issue: [{ ...chat, conversationUserId: "local-board" }], comments: [], answers: [] }, { userId: "local-board" }],
|
||||||
|
])("emits nothing after %s", async (_label, rows, actor) => {
|
||||||
|
await emitChatStartedIfFirstOwnerTurn(fakeTx(rows as Rows), { issueId: "chat-1", actor });
|
||||||
|
expect(cloudEvents).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,7 +4,7 @@ import { eq } from "drizzle-orm";
|
|||||||
import { mkdtemp, realpath, rm } from "node:fs/promises";
|
import { mkdtemp, realpath, rm } from "node:fs/promises";
|
||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { agents, companies, companyMemberships, createDb, issues } from "@paperclipai/db";
|
import { agents, companies, companyMemberships, createDb, issueComments, issues, issueThreadInteractions } from "@paperclipai/db";
|
||||||
import {
|
import {
|
||||||
getEmbeddedPostgresTestSupport,
|
getEmbeddedPostgresTestSupport,
|
||||||
startEmbeddedPostgresTestDatabase,
|
startEmbeddedPostgresTestDatabase,
|
||||||
@@ -14,9 +14,13 @@ import { scopedTelemetryCompanyId, scopedTelemetryPerson } from "../telemetry-co
|
|||||||
const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() }));
|
const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() }));
|
||||||
const calls = vi.hoisted(() => [] as Array<{ event: string; dims: Record<string, unknown>; companyId: string | undefined }>);
|
const calls = vi.hoisted(() => [] as Array<{ event: string; dims: Record<string, unknown>; companyId: string | undefined }>);
|
||||||
const people = vi.hoisted(() => [] as Array<{ event: string; person: unknown }>);
|
const people = vi.hoisted(() => [] as Array<{ event: string; person: unknown }>);
|
||||||
|
const cloudEvents = vi.hoisted(() => [] as Array<{ event: string; properties: unknown; context: unknown }>);
|
||||||
|
|
||||||
vi.mock("../telemetry.js", () => ({
|
vi.mock("../telemetry.js", () => ({
|
||||||
getTelemetryClient: () => mockTelemetryClient,
|
getTelemetryClient: () => mockTelemetryClient,
|
||||||
|
trackCloudPostHogEvent: (event: string, properties?: unknown, context?: unknown) => {
|
||||||
|
cloudEvents.push({ event, properties, context });
|
||||||
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@paperclipai/shared/telemetry", async () => {
|
vi.mock("@paperclipai/shared/telemetry", async () => {
|
||||||
@@ -91,6 +95,7 @@ describeEmbeddedPostgres("product telemetry emit sites", () => {
|
|||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
calls.length = 0;
|
calls.length = 0;
|
||||||
people.length = 0;
|
people.length = 0;
|
||||||
|
cloudEvents.length = 0;
|
||||||
companyId = randomUUID();
|
companyId = randomUUID();
|
||||||
agentId = randomUUID();
|
agentId = randomUUID();
|
||||||
await db.insert(companies).values({
|
await db.insert(companies).values({
|
||||||
@@ -155,6 +160,93 @@ describeEmbeddedPostgres("product telemetry emit sites", () => {
|
|||||||
expect(sent("task.created")).toEqual([]);
|
expect(sent("task.created")).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("emits Cloud chat.started on the chat owner's first message, not when the chat is created", async () => {
|
||||||
|
const chat = await issueService(db).create(companyId, {
|
||||||
|
title: "Chat with Coder", originKind: "onboarding_chat", status: "in_review", conversationState: "waiting",
|
||||||
|
conversationAgentId: agentId, conversationUserId: "user-1", assigneeAgentId: agentId, createdByUserId: "user-1",
|
||||||
|
});
|
||||||
|
expect(sent("task.created")).toEqual([]);
|
||||||
|
expect(cloudEvents).toEqual([]);
|
||||||
|
|
||||||
|
await issueService(db).addComment(chat.id, "Welcome!", {}, { authorType: "system" });
|
||||||
|
await issueService(db).addComment(chat.id, "Not the owner", { userId: "user-2" });
|
||||||
|
expect(cloudEvents).toEqual([]);
|
||||||
|
|
||||||
|
await issueService(db).addComment(chat.id, "Hi", { userId: "user-1" });
|
||||||
|
await issueService(db).addComment(chat.id, "Hi again", { userId: "user-1" });
|
||||||
|
expect(cloudEvents).toEqual([
|
||||||
|
{ event: "chat.started", properties: { surface: "onboarding_chat", agent_id: agentId }, context: { userId: "user-1", companyId } },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("still emits chat.started on the first message after the owner cancelled a question card", async () => {
|
||||||
|
const chat = await issueService(db).create(companyId, {
|
||||||
|
title: "Chat with Coder", originKind: "onboarding_chat", status: "in_review", conversationState: "waiting",
|
||||||
|
conversationAgentId: agentId, conversationUserId: "user-1", assigneeAgentId: agentId, createdByUserId: "user-1",
|
||||||
|
});
|
||||||
|
await db.insert(issueThreadInteractions).values({
|
||||||
|
companyId, issueId: chat.id, kind: "ask_user_questions", status: "cancelled", resolvedByUserId: "user-1",
|
||||||
|
payload: { version: 1, questions: [] } as never,
|
||||||
|
});
|
||||||
|
await issueService(db).addComment(chat.id, "Hi", { userId: "user-1" });
|
||||||
|
expect(cloudEvents.map((entry) => entry.event)).toEqual(["chat.started"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not treat a headless skip's decision comment as the owner's first message", async () => {
|
||||||
|
const chat = await issueService(db).create(companyId, {
|
||||||
|
title: "Chat with Coder", status: "in_review", conversationState: "waiting",
|
||||||
|
conversationAgentId: agentId, conversationUserId: "user-1", assigneeAgentId: agentId, createdByUserId: "user-1",
|
||||||
|
});
|
||||||
|
// What a headless one-line reject leaves behind: a user comment recording
|
||||||
|
// the decision, referenced from the skipped card's result.
|
||||||
|
const [decision] = await db.insert(issueComments).values({
|
||||||
|
companyId, issueId: chat.id, authorType: "user", authorUserId: "user-1", body: "Rejected",
|
||||||
|
}).returning();
|
||||||
|
await db.insert(issueThreadInteractions).values({
|
||||||
|
companyId, issueId: chat.id, kind: "ask_user_questions", status: "rejected", resolvedByUserId: "user-1",
|
||||||
|
payload: { version: 1, questions: [] } as never,
|
||||||
|
result: { version: 1, outcome: "skipped", answers: [], commentId: decision.id } as never,
|
||||||
|
});
|
||||||
|
expect(cloudEvents).toEqual([]);
|
||||||
|
|
||||||
|
await issueService(db).addComment(chat.id, "Hi", { userId: "user-1" });
|
||||||
|
expect(cloudEvents.map((entry) => entry.event)).toEqual(["chat.started"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps a first message that resolved a confirmation card as the owner's first turn", async () => {
|
||||||
|
const chat = await issueService(db).create(companyId, {
|
||||||
|
title: "Chat with Coder", status: "in_review", conversationState: "waiting",
|
||||||
|
conversationAgentId: agentId, conversationUserId: "user-1", assigneeAgentId: agentId, createdByUserId: "user-1",
|
||||||
|
});
|
||||||
|
const first = await issueService(db).addComment(chat.id, "No, do it differently", { userId: "user-1" });
|
||||||
|
await db.insert(issueThreadInteractions).values({
|
||||||
|
companyId, issueId: chat.id, kind: "request_confirmation", status: "rejected", resolvedByUserId: "user-1",
|
||||||
|
payload: { version: 1, prompt: "Proceed?" } as never,
|
||||||
|
result: { version: 1, outcome: "rejected", commentId: first.id } as never,
|
||||||
|
});
|
||||||
|
await issueService(db).addComment(chat.id, "Second message", { userId: "user-1" });
|
||||||
|
expect(cloudEvents.map((entry) => entry.event)).toEqual(["chat.started"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("emits no chat.started for a first message whose transaction rolls back, or on a task", async () => {
|
||||||
|
const chat = await issueService(db).create(companyId, {
|
||||||
|
title: "Chat with Coder", status: "in_review", conversationState: "waiting",
|
||||||
|
conversationAgentId: agentId, conversationUserId: "user-1", assigneeAgentId: agentId, createdByUserId: "user-1",
|
||||||
|
});
|
||||||
|
await expect(db.transaction(async (tx) => {
|
||||||
|
await issueService(tx as unknown as typeof db).addComment(chat.id, "Hi", { userId: "user-1" }, undefined, tx);
|
||||||
|
throw new Error("rollback");
|
||||||
|
})).rejects.toThrow("rollback");
|
||||||
|
const task = await issueService(db).create(companyId, { title: "Task", createdByUserId: "user-1" });
|
||||||
|
await issueService(db).addComment(task.id, "On a task", { userId: "user-1" });
|
||||||
|
expect(cloudEvents).toEqual([]);
|
||||||
|
|
||||||
|
await issueService(db).addComment(chat.id, "Hi", { userId: "user-1" });
|
||||||
|
expect(cloudEvents).toEqual([
|
||||||
|
{ event: "chat.started", properties: { surface: "agent_chat", agent_id: agentId }, context: { userId: "user-1", companyId } },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
it("emits task.completed once per transition to done", async () => {
|
it("emits task.completed once per transition to done", async () => {
|
||||||
const id = await seedIssue({ status: "in_progress" });
|
const id = await seedIssue({ status: "in_progress" });
|
||||||
await issueService(db).update(id, { status: "done", actorAgentId: agentId });
|
await issueService(db).update(id, { status: "done", actorAgentId: agentId });
|
||||||
|
|||||||
@@ -101,6 +101,7 @@ import {
|
|||||||
touchChannelsLastActivity,
|
touchChannelsLastActivity,
|
||||||
} from "../services/headless-common.js";
|
} from "../services/headless-common.js";
|
||||||
import { executeCoalescedHeadlessComment } from "../services/headless-comment-group-commit.js";
|
import { executeCoalescedHeadlessComment } from "../services/headless-comment-group-commit.js";
|
||||||
|
import { emitChatStartedIfFirstOwnerTurn } from "../services/product-telemetry.js";
|
||||||
import {
|
import {
|
||||||
createBatchIssuesPlan,
|
createBatchIssuesPlan,
|
||||||
mutateIssueKvLabels,
|
mutateIssueKvLabels,
|
||||||
@@ -813,6 +814,14 @@ export function headlessChannelsSchemasRoutes(
|
|||||||
.set({ updatedAt: now })
|
.set({ updatedAt: now })
|
||||||
.where(eq(issues.id, targetIssue.id));
|
.where(eq(issues.id, targetIssue.id));
|
||||||
|
|
||||||
|
if (inserted && !actor.agentId) {
|
||||||
|
await emitChatStartedIfFirstOwnerTurn(tx as unknown as Db, {
|
||||||
|
issueId: targetIssue.id,
|
||||||
|
actor: { userId: authorUserId },
|
||||||
|
commentIds: [inserted.id],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
await touchChannelsLastActivity(tx, [targetIssue.channelId], now);
|
await touchChannelsLastActivity(tx, [targetIssue.channelId], now);
|
||||||
|
|
||||||
await logActivity(
|
await logActivity(
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import type {
|
|||||||
} from "@paperclipai/shared";
|
} from "@paperclipai/shared";
|
||||||
import { notFound } from "../errors.js";
|
import { notFound } from "../errors.js";
|
||||||
import { logger } from "../middleware/logger.js";
|
import { logger } from "../middleware/logger.js";
|
||||||
|
import { emitChatStartedIfFirstOwnerTurn } from "./product-telemetry.js";
|
||||||
import {
|
import {
|
||||||
createActivityDetailsRedactor,
|
createActivityDetailsRedactor,
|
||||||
logActivitiesBatch,
|
logActivitiesBatch,
|
||||||
@@ -221,6 +222,25 @@ async function runCoalescedCommentsBatch(
|
|||||||
xid: sql<string>`pg_current_xact_id()::text`,
|
xid: sql<string>`pg_current_xact_id()::text`,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// A person's first message in a chat counts as the chat starting. The
|
||||||
|
// issue rows were locked by the update above; visit them in a fixed order.
|
||||||
|
const ownerTurns = new Map<string, { issueId: string; userId: string; commentIds: string[] }>();
|
||||||
|
for (const row of insertedRows) {
|
||||||
|
if (row.authorType !== "user" || !row.authorUserId || row.authorAgentId) continue;
|
||||||
|
const key = `${row.issueId}:${row.authorUserId}`;
|
||||||
|
const turn = ownerTurns.get(key) ?? { issueId: row.issueId, userId: row.authorUserId, commentIds: [] };
|
||||||
|
turn.commentIds.push(row.id);
|
||||||
|
ownerTurns.set(key, turn);
|
||||||
|
}
|
||||||
|
for (const key of [...ownerTurns.keys()].sort()) {
|
||||||
|
const turn = ownerTurns.get(key)!;
|
||||||
|
await emitChatStartedIfFirstOwnerTurn(tx as unknown as Db, {
|
||||||
|
issueId: turn.issueId,
|
||||||
|
actor: { userId: turn.userId },
|
||||||
|
commentIds: turn.commentIds,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const insertedById = new Map(insertedRows.map((row) => [row.id, row]));
|
const insertedById = new Map(insertedRows.map((row) => [row.id, row]));
|
||||||
const firstXid = insertedRows[0]?.xid;
|
const firstXid = insertedRows[0]?.xid;
|
||||||
if (firstXid) {
|
if (firstXid) {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { emitChatStartedIfFirstOwnerTurn } from "./product-telemetry.js";
|
||||||
import { and, asc, desc, eq, inArray, isNull, ne, sql } from "drizzle-orm";
|
import { and, asc, desc, eq, inArray, isNull, ne, sql } from "drizzle-orm";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { Db } from "@paperclipai/db";
|
import type { Db } from "@paperclipai/db";
|
||||||
@@ -910,6 +911,17 @@ async function resolveInteractionOnIssue(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// In a chat, the owner's one-line answer or confirmation decision is a
|
||||||
|
// chat turn. Skipping a question card is not, the same as cancelling it.
|
||||||
|
if (!actor.agentId && !(isAsk && nextStatus === "rejected")) {
|
||||||
|
await emitChatStartedIfFirstOwnerTurn(tx as unknown as Db, {
|
||||||
|
issueId: issue.id,
|
||||||
|
actor: { userId: actor.userId },
|
||||||
|
commentIds: [comment!.id],
|
||||||
|
interactionId: updatedInteraction.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
await tx.insert(activityLog).values({
|
await tx.insert(activityLog).values({
|
||||||
companyId: issue.companyId,
|
companyId: issue.companyId,
|
||||||
actorType: actor.principalType === "agent" ? "agent" : "user",
|
actorType: actor.principalType === "agent" ? "agent" : "user",
|
||||||
|
|||||||
@@ -156,7 +156,7 @@ import {
|
|||||||
publishCommittedBoardEvent,
|
publishCommittedBoardEvent,
|
||||||
} from "./headless-common.js";
|
} from "./headless-common.js";
|
||||||
import type { BoardEventView } from "@paperclipai/shared";
|
import type { BoardEventView } from "@paperclipai/shared";
|
||||||
import { emitPlanApprovedAfterCommit } from "./product-telemetry.js";
|
import { emitPlanApprovedAfterCommit, emitChatStartedIfFirstOwnerTurn } from "./product-telemetry.js";
|
||||||
import { authorizationService } from "./authorization.js";
|
import { authorizationService } from "./authorization.js";
|
||||||
import { isCloudManagedInstance } from "./cloud-instance.js";
|
import { isCloudManagedInstance } from "./cloud-instance.js";
|
||||||
import { resolveDeploymentMode } from "../config-file.js";
|
import { resolveDeploymentMode } from "../config-file.js";
|
||||||
@@ -7118,6 +7118,7 @@ export function issueThreadInteractionService(
|
|||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
if (!row) throw interactionAlreadyResolvedError();
|
if (!row) throw interactionAlreadyResolvedError();
|
||||||
|
await emitChatStartedIfFirstOwnerTurn(tx as unknown as Db, { issueId: issue.id, actor, interactionId: row.id });
|
||||||
const answered = hydrateInteraction(row) as AskUserQuestionsInteraction;
|
const answered = hydrateInteraction(row) as AskUserQuestionsInteraction;
|
||||||
// This answer updates conversation history only. It must not resume
|
// This answer updates conversation history only. It must not resume
|
||||||
// the completed source run or enqueue new work for the closed task.
|
// the completed source run or enqueue new work for the closed task.
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ import { assertHandedOffRunTaskOwnership } from "../run-task-ownership.js";
|
|||||||
import { retryIdempotentDatabaseOperation } from "../database-retry.js";
|
import { retryIdempotentDatabaseOperation } from "../database-retry.js";
|
||||||
import { externalConversationStateSql, nonIdleSlackIssueCondition, resumeSlackConversation } from "./slack-conversation-state.js";
|
import { externalConversationStateSql, nonIdleSlackIssueCondition, resumeSlackConversation } from "./slack-conversation-state.js";
|
||||||
import { documentService } from "./documents.js";
|
import { documentService } from "./documents.js";
|
||||||
import { emitArtifactCreatedAfterCommit, emitTaskCreatedAfterCommit, emitTaskStatusTransitionAfterCommit } from "./product-telemetry.js";
|
import { emitArtifactCreatedAfterCommit, emitTaskCreatedAfterCommit, emitTaskStatusTransitionAfterCommit, emitChatStartedIfFirstOwnerTurn } from "./product-telemetry.js";
|
||||||
import { hasUnfinishedBlockers } from "./issue-dependency-wakeups.js";
|
import { hasUnfinishedBlockers } from "./issue-dependency-wakeups.js";
|
||||||
import { parseTaskSearch, taskSearchCtes, taskSearchScore } from "./task-search.js";
|
import { parseTaskSearch, taskSearchCtes, taskSearchScore } from "./task-search.js";
|
||||||
import { createdFromIssueCondition } from "./issue-creation-origin.js";
|
import { createdFromIssueCondition } from "./issue-creation-origin.js";
|
||||||
@@ -14295,6 +14295,7 @@ export function issueService(db: Db) {
|
|||||||
: existing;
|
: existing;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const insertedNewComment = !comment;
|
||||||
if (!comment) {
|
if (!comment) {
|
||||||
[comment] = await measureRunPhase("response.write", () => insertIssueComment(dbOrTx, {
|
[comment] = await measureRunPhase("response.write", () => insertIssueComment(dbOrTx, {
|
||||||
companyId: issue.companyId,
|
companyId: issue.companyId,
|
||||||
@@ -14318,6 +14319,9 @@ export function issueService(db: Db) {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
if (!comment) throw new Error("Failed to create issue comment");
|
if (!comment) throw new Error("Failed to create issue comment");
|
||||||
|
if (insertedNewComment && authorType === "user" && issue.conversationAgentId) {
|
||||||
|
await emitChatStartedIfFirstOwnerTurn(dbOrTx, { issueId, actor, commentIds: [comment.id] });
|
||||||
|
}
|
||||||
if (options?.completionReply && actor.agentId && createdByRunId) await acknowledgeChatCompletionReply(dbOrTx, createdByRunId, comment.id);
|
if (options?.completionReply && actor.agentId && createdByRunId) await acknowledgeChatCompletionReply(dbOrTx, createdByRunId, comment.id);
|
||||||
|
|
||||||
const boundAttachments: Array<{
|
const boundAttachments: Array<{
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import { afterTransactionCommit } from "@paperclipai/db";
|
import { and, eq, ne, notInArray, sql } from "drizzle-orm";
|
||||||
|
import { afterTransactionCommit, issueComments, issues, issueThreadInteractions, type Db } from "@paperclipai/db";
|
||||||
import { hasUnfinishedBlockers } from "./issue-dependency-wakeups.js";
|
import { hasUnfinishedBlockers } from "./issue-dependency-wakeups.js";
|
||||||
import {
|
import {
|
||||||
|
ONBOARDING_CHAT_ORIGIN_KIND,
|
||||||
ONBOARDING_FIRST_TASK_ORIGIN_KIND,
|
ONBOARDING_FIRST_TASK_ORIGIN_KIND,
|
||||||
|
type AgentChatSurface,
|
||||||
type IssueUnblockDescriptor,
|
type IssueUnblockDescriptor,
|
||||||
} from "@paperclipai/shared";
|
} from "@paperclipai/shared";
|
||||||
import {
|
import {
|
||||||
@@ -15,7 +18,7 @@ import {
|
|||||||
type TelemetryClient,
|
type TelemetryClient,
|
||||||
} from "@paperclipai/shared/telemetry";
|
} from "@paperclipai/shared/telemetry";
|
||||||
import { logger } from "../middleware/logger.js";
|
import { logger } from "../middleware/logger.js";
|
||||||
import { getTelemetryClient } from "../telemetry.js";
|
import { getTelemetryClient, trackCloudPostHogEvent } from "../telemetry.js";
|
||||||
import { resolveTelemetryPerson, withTelemetryActor } from "../telemetry-company-scope.js";
|
import { resolveTelemetryPerson, withTelemetryActor } from "../telemetry-company-scope.js";
|
||||||
|
|
||||||
export type TelemetryActorKind = "user" | "agent" | "system";
|
export type TelemetryActorKind = "user" | "agent" | "system";
|
||||||
@@ -45,6 +48,91 @@ function emitAfterCommit(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cloud-only event for the moment a person starts a chat with an agent: their
|
||||||
|
* first message, or their first answer to a question card (such as the
|
||||||
|
* onboarding welcome card), in that chat. Opening or preparing a chat is not
|
||||||
|
* enough, because onboarding prepares the chat before the person launches it.
|
||||||
|
* `task.created` skips chats on purpose, so without this event a person who
|
||||||
|
* only chats has no server-side "chat started" step.
|
||||||
|
*/
|
||||||
|
export const CHAT_STARTED_EVENT = "chat.started";
|
||||||
|
|
||||||
|
type ChatTurnStore = Pick<Db, "select">;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call inside the transaction that has just written a person's chat message
|
||||||
|
* or question answer, passing the ids it wrote. When that write is the chat
|
||||||
|
* owner's first turn in the chat, this emits `chat.started` once the
|
||||||
|
* transaction commits. It locks the chat's issue row first (a no-op for
|
||||||
|
* callers that already hold it), so two concurrent first turns cannot both
|
||||||
|
* count. Agent, run, and system writes, other people's writes, and cancelled
|
||||||
|
* or skipped question cards never count.
|
||||||
|
*
|
||||||
|
* It goes through the Cloud direct PostHog path only, so it does nothing on
|
||||||
|
* self-hosted installs and with `PAPERCLIP_POSTHOG_DIRECT=0`. The properties
|
||||||
|
* hold no free text: only the chat surface and the agent id that
|
||||||
|
* `agent.task_run` also carries.
|
||||||
|
*/
|
||||||
|
export async function emitChatStartedIfFirstOwnerTurn(
|
||||||
|
tx: ChatTurnStore,
|
||||||
|
input: {
|
||||||
|
issueId: string;
|
||||||
|
actor: { userId?: string | null; agentId?: string | null; runId?: string | null; systemId?: string | null };
|
||||||
|
/** Owner comments this transaction wrote in the chat. */
|
||||||
|
commentIds?: string[];
|
||||||
|
/** The question card this transaction answered. */
|
||||||
|
interactionId?: string;
|
||||||
|
},
|
||||||
|
): Promise<void> {
|
||||||
|
const { actor, issueId } = input;
|
||||||
|
if (!actor.userId || actor.agentId || actor.runId || actor.systemId) return;
|
||||||
|
const [chat] = await tx.select({
|
||||||
|
companyId: issues.companyId,
|
||||||
|
originKind: issues.originKind,
|
||||||
|
conversationAgentId: issues.conversationAgentId,
|
||||||
|
conversationUserId: issues.conversationUserId,
|
||||||
|
}).from(issues).where(eq(issues.id, issueId)).for("update");
|
||||||
|
if (!chat?.conversationAgentId || chat.conversationUserId !== actor.userId) return;
|
||||||
|
const person = resolveTelemetryPerson({ taskCreatedByUserId: chat.conversationUserId });
|
||||||
|
if (!person) return;
|
||||||
|
const commentIds = input.commentIds ?? [];
|
||||||
|
const [priorMessage] = await tx.select({ id: issueComments.id }).from(issueComments).where(and(
|
||||||
|
eq(issueComments.companyId, chat.companyId),
|
||||||
|
eq(issueComments.issueId, issueId),
|
||||||
|
eq(issueComments.authorType, "user"),
|
||||||
|
eq(issueComments.authorUserId, person.userId),
|
||||||
|
...(commentIds.length > 0 ? [notInArray(issueComments.id, commentIds)] : []),
|
||||||
|
// A headless skip of a question card writes a user comment that only
|
||||||
|
// records the skip (its id is in the card's result). It is not a chat
|
||||||
|
// turn. Comments linked from other cards, such as a real message that
|
||||||
|
// resolved a confirmation card, still count.
|
||||||
|
sql`not exists (select 1 from ${issueThreadInteractions} skipped
|
||||||
|
where skipped.company_id = ${chat.companyId}::uuid and skipped.issue_id = ${issueId}::uuid
|
||||||
|
and skipped.kind = 'ask_user_questions' and skipped.status = 'rejected'
|
||||||
|
and skipped.result->>'commentId' = ${issueComments.id}::text)`,
|
||||||
|
)).limit(1);
|
||||||
|
if (priorMessage) return;
|
||||||
|
const [priorAnswer] = await tx.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and(
|
||||||
|
eq(issueThreadInteractions.companyId, chat.companyId),
|
||||||
|
eq(issueThreadInteractions.issueId, issueId),
|
||||||
|
eq(issueThreadInteractions.status, "answered"),
|
||||||
|
eq(issueThreadInteractions.resolvedByUserId, person.userId),
|
||||||
|
...(input.interactionId ? [ne(issueThreadInteractions.id, input.interactionId)] : []),
|
||||||
|
)).limit(1);
|
||||||
|
if (priorAnswer) return;
|
||||||
|
const surface: AgentChatSurface = chat.originKind === ONBOARDING_CHAT_ORIGIN_KIND ? "onboarding_chat" : "agent_chat";
|
||||||
|
const properties = { surface, agent_id: chat.conversationAgentId };
|
||||||
|
const context = { userId: person.userId, companyId: chat.companyId };
|
||||||
|
afterTransactionCommit(() => {
|
||||||
|
try {
|
||||||
|
trackCloudPostHogEvent(CHAT_STARTED_EVENT, properties, context);
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn({ err, event: CHAT_STARTED_EVENT }, "failed to emit product telemetry");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function emitTaskCreatedAfterCommit(issue: {
|
export function emitTaskCreatedAfterCommit(issue: {
|
||||||
companyId: string;
|
companyId: string;
|
||||||
originKind: string | null;
|
originKind: string | null;
|
||||||
|
|||||||
Reference in new issue
Block a user