Files
PaperClipAI/server/src/__tests__/agent-task-run-telemetry.test.ts
T
DottaandClaude Opus 5.5 92dbf39e6f feat(analytics): attribute agent work and onboarding steps to a person on Cloud (#22260)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud sends product events straight to PostHog: server
events from `server/src/services/posthog-direct/` and browser events
from `ui/src/lib/analytics/`
> - A person-level funnel goes from sign-up to the first finished task
> - Agent-driven events (`agent.task_run`, `agent.task_completed`,
`agent.first_heartbeat`) used `workspace:<stackId>` as the distinct id,
so the funnel broke at those steps
> - The in-workspace onboarding wizard sent no step events, so we could
not see where people stop before their first agent
> - This pull request attributes agent work to the responsible person on
the Cloud direct path, and adds consent-gated onboarding step events in
the browser
> - The benefit is one PostHog person per customer across sign-up,
onboarding, agent runs, and task completion. Self-hosted output does not
change.

## Linked Issues or Issue Description

**Subsystem affected**
Cloud product analytics: Cloud direct PostHog delivery (server) and
browser product analytics (UI onboarding wizard).

**Problem or motivation**
A PostHog funnel from sign-up to the first finished task cannot follow
one person. Agent-driven events run in the background, with no signed-in
request, so they use the workspace id as the distinct id. The onboarding
wizard also sends no events, so we cannot see which step people leave.

**Proposed solution**
Give background emit sites a narrow scope that names the person
responsible for the work. Use the task creator first, then the task's
responsible user, then the run owner. Keep the signed-in request user
first. Add `attributed_via` to every Cloud direct event. Add four
browser events to the onboarding wizard. Send them through the existing
analytics module, so the consent rules stay the same.

**Alternatives considered**
A lookup in the transport at send time. We did not use it: it adds
database reads to the telemetry path and loses the emit site's context.
A new contract event for onboarding steps. We did not use it: the server
does not see the wizard steps, and the UI must never send
`PAPERCLIP_EVENTS` names.

**Additional context**
Self-hosted installs keep the collector path. The collector envelope
stays byte-identical (a test checks it).

## What Changed

- `server/src/telemetry-company-scope.ts`: add `withTelemetryActor({
companyId, person }, fn)`, `scopedTelemetryPerson()`, and
`resolveTelemetryPerson()`. The resolver picks the task creator, then
the task's responsible user, then the run owner. It ignores
`local-board`. `withTelemetryCompany` now calls `withTelemetryActor`.
- `server/src/services/posthog-direct/request-context.ts`: a signed-in
request user wins (`attributed_via: request`). Without one, the scoped
person is used.
- `server/src/services/posthog-direct/event-shape.ts`: every Cloud
direct event (including `cloud.workspace_started`) has `attributed_via`
(`request`, `task_creator`, `task_assigner`, `run_owner`, or `none`). An
event with a person keeps today's person-event shape (no
`$process_person_profile: false`).
- `server/src/services/agent-task-run-telemetry.ts`: `agent.task_run`
reads the task creator and responsible user in the existing agent query
(one left join, no new query), and the run's `responsibleUserId`.
- `server/src/routes/issues.ts`: `agent.task_completed` uses the issue
row that the route already has, and the agent actor's `onBehalfOfUserId`
as the run owner.
- `server/src/services/heartbeat/agent-status.ts`:
`agent.first_heartbeat` uses the agent's `createdByUserId` (already
loaded) as the run owner.
- `ui/src/lib/analytics/product-analytics.ts`: add
`captureProductAnalyticsEvent()`. It captures only with a browser
analytics config and granted consent. Events from before posthog-js
loads wait in a queue (at most 50) and keep their time. Withdrawn
consent or a change of signed-in person drops the queue.
- `ui/src/lib/analytics/onboarding-analytics.ts` and
`ui/src/components/OnboardingWizard.tsx`: capture `onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed` (with `step` and,
for `connect_model` and `launch`, `outcome`), and
`onboarding_dismissed`. `step` is `create_agent`, `connect_model`,
`review`, or `launch`. No event has free text.
- Docs: `packages/shared/src/telemetry/README.md` (Cloud Direct
Delivery) and `doc/cloud-browser-analytics.md` (new "Onboarding events"
section).

## Verification

- `server/src/__tests__/posthog-direct-telemetry.test.ts`: attribution
matrix (creator, assigner, run owner, none stays on
`workspace:<stackId>` with `$process_person_profile: false`), the
request user wins over the scope, and the self-hosted collector envelope
is byte-identical with a person scope.
- `server/src/__tests__/agent-task-run-telemetry.test.ts` (embedded
Postgres): `agent.task_run` scope for creator, assigner, run owner, and
nobody; another company's task is never read.
- `server/src/__tests__/issue-telemetry-routes.test.ts`:
`agent.task_completed` scope for creator and assigner.
- `server/src/__tests__/heartbeat-process-recovery.test.ts`:
`agent.first_heartbeat` scope is the agent owner.
- `ui/src/components/OnboardingWizard.test.tsx`: a launch for the old
company that settles after a switch to another company does not end the
new analytics session.
- `ui/src/lib/analytics/onboarding-analytics.test.tsx`: each transition
fires once, held events drop on a person change, a stale opening step is
not a view, dismissal fires once, nothing is captured when analytics is
off or consent is `denied` or `ask`, and queued events keep their time.
- `ui/src/lib/analytics/product-analytics-events.test.ts` still passes
(the UI never captures a `PAPERCLIP_EVENTS` name).
- Local Cloud-mode run: an isolated instance (own Postgres, trusted
Cloud tenant headers, `PAPERCLIP_POSTHOG_HOST` set to a local capture
server, never real PostHog). A stub stood in for posthog-js and sent
through the `/_ph` proxy.
- A user created a task and assigned it to the agent. `agent.task_run`
arrived with `distinct_id: paperclip-id:local-user-1`, `attributed_via:
task_creator`, the raw `task_id`, and no `$process_person_profile`. (The
run itself failed locally because the Cloud runner is not available. The
event still shows the attribution.)
- `agent.first_heartbeat` arrived with the same person and
`attributed_via: run_owner`. `server.started` kept
`workspace:stack-local` with `attributed_via: none`.
- Headless Chromium walked the wizard: `onboarding_opened`
(create_agent), `onboarding_step_viewed` (create_agent),
`onboarding_step_completed` (create_agent), `onboarding_step_viewed`
(connect_model), `onboarding_step_completed` (connect_model, `api_key`),
`onboarding_step_viewed` (review), `onboarding_step_completed` (review),
`onboarding_step_completed` (launch, `succeeded`). Each fired once, with
the signed-in user as the distinct id. Events from before posthog-js
loaded arrived with their original time.
- A second walk left the onboarding page on the connect step and sent
one `onboarding_dismissed` (connect_model).

## Risks

- Low risk for self-hosted: the collector path never reads the new
scope, and a test checks the envelope bytes.
- Cloud: agent events move from the workspace person to a real person.
Insights that count `workspace:` distinct ids for these events will
change. `attributed_via` lets a query filter or split them.
- `task_assigner` uses the task's responsible user. Paperclip does not
store who assigned a task, so this is the person who owns or delegated
the task.
- Privacy: the new data is Cloud-only and uses ids that Cloud events
already carry. No new free text, email, or name goes on an event.
**Privacy review requested** for the Cloud attribution change (per
`rules/data-paths.mdc`). The generated contract does not change:
`attributed_via` is a Cloud-only property, like `stack_id` and
`user_id`.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, headless browser).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:44:45 -06:00

397 lines
15 KiB
TypeScript

import { randomBytes, randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, companies, createDb, heartbeatRuns, issues, type Db } from "@paperclipai/db";
import { eq } from "drizzle-orm";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { scopedTelemetryCompanyId, scopedTelemetryPerson } from "../telemetry-company-scope.js";
const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() }));
const mockTrackAgentTaskRun = vi.hoisted(() => vi.fn());
vi.mock("../telemetry.js", () => ({
getTelemetryClient: () => mockTelemetryClient,
}));
vi.mock("@paperclipai/shared/telemetry", async () => {
const actual = await vi.importActual<typeof import("@paperclipai/shared/telemetry")>(
"@paperclipai/shared/telemetry",
);
return {
...actual,
trackAgentTaskRun: mockTrackAgentTaskRun,
};
});
import { emitAgentTaskRun, emitAgentTaskRunById } from "../services/agent-task-run-telemetry.ts";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
describeEmbeddedPostgres("emitAgentTaskRun", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
let companyId!: string;
let agentId!: string;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-agent-task-run-telemetry-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterEach(async () => {
vi.clearAllMocks();
await db.delete(heartbeatRuns);
await db.delete(issues);
await db.delete(agents);
await db.delete(companies);
});
afterAll(async () => {
await tempDb?.cleanup();
});
async function seedCompanyAndAgent(
agentOverrides: Partial<typeof agents.$inferInsert> = {},
) {
companyId = randomUUID();
agentId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
defaultResponsibleUserId: "responsible-user",
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "CodexCoder",
role: "engineer",
status: "active",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
...agentOverrides,
});
return { companyId, agentId };
}
it("emits one agent.task_run event for each of the five terminal states", async () => {
await seedCompanyAndAgent();
const states = ["succeeded", "interrupted", "failed", "cancelled", "timed_out"] as const;
for (const state of states) {
mockTrackAgentTaskRun.mockClear();
const runId = randomUUID();
const run = {
id: runId,
companyId,
agentId,
status: state,
startedAt: null,
finishedAt: null,
usageJson: null,
contextSnapshot: null,
} as unknown as typeof heartbeatRuns.$inferSelect;
await emitAgentTaskRun(db, run);
expect(mockTrackAgentTaskRun).toHaveBeenCalledTimes(1);
expect(mockTrackAgentTaskRun).toHaveBeenCalledWith(
mockTelemetryClient,
expect.objectContaining({ agentId, state }),
);
}
});
it("tracks agent.task_run in the run's company scope", async () => {
await seedCompanyAndAgent();
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded" }).returning();
const scopedCompanies: Array<string | undefined> = [];
const recordScope = () => scopedCompanies.push(scopedTelemetryCompanyId());
mockTrackAgentTaskRun.mockImplementationOnce(recordScope).mockImplementationOnce(recordScope);
await emitAgentTaskRun(db, run);
await emitAgentTaskRunById(db, { runId: run.id, companyId });
expect(scopedCompanies).toEqual([companyId, companyId]);
expect(scopedTelemetryCompanyId()).toBeUndefined();
});
it.each([
{ name: "task creator", issue: { createdByUserId: "user-creator", responsibleUserId: "user-assigner" }, runOwner: "user-owner", expected: { userId: "user-creator", attributedVia: "task_creator" } },
{ name: "task assigner", issue: { createdByUserId: null, responsibleUserId: "user-assigner" }, runOwner: "user-owner", expected: { userId: "user-assigner", attributedVia: "task_assigner" } },
{ name: "run owner", issue: { createdByUserId: null, responsibleUserId: null }, runOwner: "user-owner", expected: { userId: "user-owner", attributedVia: "run_owner" } },
{ name: "nobody", issue: { createdByUserId: null, responsibleUserId: null }, runOwner: null, expected: undefined },
])("tracks agent.task_run for the person responsible: $name", async ({ issue, runOwner, expected }) => {
await seedCompanyAndAgent();
const issueId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Write the report", assigneeAgentId: agentId, createdByAgentId: issue.createdByUserId ? null : agentId, ...issue });
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded",
responsibleUserId: runOwner, contextSnapshot: { issueId } }).returning();
const people: unknown[] = [];
const recordPerson = () => people.push(scopedTelemetryPerson());
mockTrackAgentTaskRun.mockImplementationOnce(recordPerson).mockImplementationOnce(recordPerson);
await emitAgentTaskRun(db, run);
await emitAgentTaskRunById(db, { runId: run.id, companyId });
expect(people).toEqual([expected, expected]);
expect(mockTrackAgentTaskRun).toHaveBeenCalledWith(mockTelemetryClient, expect.objectContaining({ taskId: issueId }));
});
it("does not read another company's task for attribution", async () => {
await seedCompanyAndAgent();
const otherCompanyId = randomUUID();
await db.insert(companies).values({ id: otherCompanyId, name: "Other", issuePrefix: `O${otherCompanyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, requireBoardApprovalForNewAgents: false });
const issueId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId: otherCompanyId, title: "Other task", createdByUserId: "user-other" });
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded", contextSnapshot: { issueId } }).returning();
const people: unknown[] = [];
mockTrackAgentTaskRun.mockImplementationOnce(() => people.push(scopedTelemetryPerson()));
await emitAgentTaskRun(db, run);
expect(people).toEqual([undefined]);
await db.delete(issues);
await db.delete(companies).where(eq(companies.id, otherCompanyId));
});
it("emits the same event from a small scoped run read without loading execution payloads", async () => {
await seedCompanyAndAgent();
const payload = randomBytes(128 * 1024).toString("base64");
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded",
startedAt: new Date("2020-01-01T00:00:00Z"), finishedAt: new Date("2020-01-01T00:00:07Z"),
contextSnapshot: { issueId: randomUUID(), prompt: payload }, runnerProfileJson: { instructions: payload },
stdoutExcerpt: payload, resultJson: { stdout: payload }, usageJson: { model: "fixture", inputTokens: 12, outputTokens: 34, cachedInputTokens: 5 },
}).returning();
await emitAgentTaskRun(db, run);
const expected = mockTrackAgentTaskRun.mock.calls[0];
mockTrackAgentTaskRun.mockClear();
const reads: unknown[][] = [];
const recorded = new Proxy(db, { get(target, key) {
if (key !== "select") return Reflect.get(target, key);
return (...fields: Parameters<Db["select"]>) => {
const builder = target.select(...fields), from = builder.from.bind(builder);
builder.from = ((...args: Parameters<typeof from>) => {
const query = from(...args);
if (args[0] === heartbeatRuns) {
const execute = query.execute.bind(query);
query.execute = async (...executeArgs: Parameters<typeof execute>) => {
const rows = await execute(...executeArgs); reads.push(rows); return rows;
};
}
return query;
}) as typeof builder.from;
return builder;
};
}});
await emitAgentTaskRunById(recorded, { companyId, runId: run.id });
expect(mockTrackAgentTaskRun).toHaveBeenCalledExactlyOnceWith(...expected);
expect(reads).toHaveLength(1);
expect(Buffer.byteLength(JSON.stringify(reads))).toBeLessThan(1024);
await emitAgentTaskRunById(recorded, { companyId: randomUUID(), runId: run.id });
expect(mockTrackAgentTaskRun).toHaveBeenCalledTimes(1);
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0]).toEqual(run);
});
it.each([null, [], 42, { issueId: 42 }, { issueId: " fixture-task " }, { issueId: "" }].map(context => ({ context })))("preserves telemetry task identity for $context", async ({ context }) => {
await seedCompanyAndAgent();
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "failed",
contextSnapshot: context as Record<string, unknown> | null }).returning();
await emitAgentTaskRun(db, run);
const expected = mockTrackAgentTaskRun.mock.calls[0];
mockTrackAgentTaskRun.mockClear();
await emitAgentTaskRunById(db, { companyId, runId: run.id });
expect(mockTrackAgentTaskRun).toHaveBeenCalledExactlyOnceWith(...expected);
});
it("omits durationSeconds when the run has no startedAt", async () => {
await seedCompanyAndAgent();
const run = {
id: randomUUID(),
companyId,
agentId,
status: "succeeded",
startedAt: null,
finishedAt: null,
usageJson: null,
contextSnapshot: null,
} as unknown as typeof heartbeatRuns.$inferSelect;
await emitAgentTaskRun(db, run);
const dims = mockTrackAgentTaskRun.mock.calls[0][1];
expect(dims).not.toHaveProperty("durationSeconds");
});
it("sends whole seconds from startedAt to finishedAt", async () => {
await seedCompanyAndAgent();
const startedAt = new Date("2026-01-01T00:00:00.000Z");
const finishedAt = new Date("2026-01-01T00:00:07.400Z");
const run = {
id: randomUUID(),
companyId,
agentId,
status: "succeeded",
startedAt,
finishedAt,
usageJson: null,
contextSnapshot: null,
} as unknown as typeof heartbeatRuns.$inferSelect;
await emitAgentTaskRun(db, run);
const dims = mockTrackAgentTaskRun.mock.calls[0][1];
expect(dims.durationSeconds).toBe(7);
expect(Number.isInteger(dims.durationSeconds)).toBe(true);
});
it("never returns a negative durationSeconds when finishedAt precedes startedAt", async () => {
await seedCompanyAndAgent();
const startedAt = new Date("2026-01-01T00:00:10.000Z");
const finishedAt = new Date("2026-01-01T00:00:05.000Z");
const run = {
id: randomUUID(),
companyId,
agentId,
status: "cancelled",
startedAt,
finishedAt,
usageJson: null,
contextSnapshot: null,
} as unknown as typeof heartbeatRuns.$inferSelect;
await emitAgentTaskRun(db, run);
const dims = mockTrackAgentTaskRun.mock.calls[0][1];
expect(dims.durationSeconds).toBe(0);
});
it("omits model, the three token dimensions, and taskId when each source is absent", async () => {
await seedCompanyAndAgent({ adapterConfig: {} });
const run = {
id: randomUUID(),
companyId,
agentId,
status: "failed",
startedAt: null,
finishedAt: null,
usageJson: null,
contextSnapshot: null,
} as unknown as typeof heartbeatRuns.$inferSelect;
await emitAgentTaskRun(db, run);
const dims = mockTrackAgentTaskRun.mock.calls[0][1];
expect(dims).not.toHaveProperty("model");
expect(dims).not.toHaveProperty("inputTokens");
expect(dims).not.toHaveProperty("outputTokens");
expect(dims).not.toHaveProperty("cachedTokens");
expect(dims).not.toHaveProperty("taskId");
});
it("sends cachedTokens: 0 when usage exists and carries no cached value", async () => {
await seedCompanyAndAgent();
const run = {
id: randomUUID(),
companyId,
agentId,
status: "succeeded",
startedAt: null,
finishedAt: null,
usageJson: { inputTokens: 12, outputTokens: 34 },
contextSnapshot: null,
} as unknown as typeof heartbeatRuns.$inferSelect;
await emitAgentTaskRun(db, run);
const dims = mockTrackAgentTaskRun.mock.calls[0][1];
expect(dims.inputTokens).toBe(12);
expect(dims.outputTokens).toBe(34);
expect(dims.cachedTokens).toBe(0);
});
it("emits with no taskId when contextSnapshot carries no issueId", async () => {
await seedCompanyAndAgent();
const run = {
id: randomUUID(),
companyId,
agentId,
status: "succeeded",
startedAt: null,
finishedAt: null,
usageJson: null,
contextSnapshot: { wakeReason: "issue_commented" },
} as unknown as typeof heartbeatRuns.$inferSelect;
await emitAgentTaskRun(db, run);
const dims = mockTrackAgentTaskRun.mock.calls[0][1];
expect(dims).not.toHaveProperty("taskId");
});
it("passes the raw task identifier to trackAgentTaskRun without hashing it", async () => {
await seedCompanyAndAgent();
const rawIssueId = randomUUID();
const run = {
id: randomUUID(),
companyId,
agentId,
status: "succeeded",
startedAt: null,
finishedAt: null,
usageJson: null,
contextSnapshot: { issueId: rawIssueId },
} as unknown as typeof heartbeatRuns.$inferSelect;
await emitAgentTaskRun(db, run);
const dims = mockTrackAgentTaskRun.mock.calls[0][1];
expect(dims.taskId).toBe(rawIssueId);
expect(dims.taskId).not.toMatch(/^[0-9a-f]{32}$/);
});
it("does not throw out of the status write when the emit fails", async () => {
await seedCompanyAndAgent();
mockTrackAgentTaskRun.mockImplementationOnce(() => {
throw new Error("telemetry backend unreachable");
});
const run = {
id: randomUUID(),
companyId,
agentId,
status: "succeeded",
startedAt: null,
finishedAt: null,
usageJson: null,
contextSnapshot: null,
} as unknown as typeof heartbeatRuns.$inferSelect;
await expect(emitAgentTaskRun(db, run)).resolves.toBeUndefined();
});
it("omits adapterType and agentRole when the agent row is absent", async () => {
await seedCompanyAndAgent();
const run = {
id: randomUUID(),
companyId,
agentId: randomUUID(),
status: "succeeded",
startedAt: null,
finishedAt: null,
usageJson: null,
contextSnapshot: null,
} as unknown as typeof heartbeatRuns.$inferSelect;
await emitAgentTaskRun(db, run);
const dims = mockTrackAgentTaskRun.mock.calls[0][1];
expect(dims).not.toHaveProperty("adapterType");
expect(dims).not.toHaveProperty("agentRole");
});
});