mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
## 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>
112 lines
5.1 KiB
TypeScript
112 lines
5.1 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
import { PAPERCLIP_ENUM_DESCRIPTIONS, type TelemetryEvent } from "@paperclipai/shared/telemetry";
|
|
import golden from "../services/posthog-direct/__fixtures__/loader-golden.json" with { type: "json" };
|
|
import { UNKNOWN_ENUM_FALLBACKS } from "../services/posthog-direct/enum-fallbacks.generated.js";
|
|
import {
|
|
buildPostHogDirectEvent,
|
|
resolveDistinctId,
|
|
} from "../services/posthog-direct/event-shape.js";
|
|
|
|
// The golden fixture is produced by running the telemetry backend's own ingest
|
|
// and loader on one collector envelope. Regenerate it with
|
|
// `node scripts/generate-posthog-direct-fixtures.mjs <telemetry-backend-dir>`.
|
|
|
|
const config = { stackId: "stack-123", environment: "staging" };
|
|
const meta = {
|
|
app: golden.envelope.app,
|
|
schemaVersion: golden.envelope.schemaVersion,
|
|
installId: golden.envelope.installId,
|
|
version: golden.envelope.version,
|
|
ingestedAt: golden.ingestedAt,
|
|
};
|
|
|
|
type LoaderEvent = (typeof golden.loaderEvents)[number];
|
|
|
|
// The Cloud direct path emits the raw task id where the collector path emits
|
|
// its salted hash. Everything else in the event is the same input.
|
|
function directInput(event: (typeof golden.envelope.events)[number]): TelemetryEvent {
|
|
const dimensions = { ...event.dimensions } as Record<string, string | number | boolean>;
|
|
if (dimensions.task_id === golden.hashedTaskId) dimensions.task_id = golden.rawTaskId;
|
|
return { name: event.name, occurredAt: event.occurredAt, dimensions };
|
|
}
|
|
|
|
describe("Cloud direct PostHog event shape", () => {
|
|
const direct = golden.envelope.events.map((event) =>
|
|
buildPostHogDirectEvent(directInput(event), undefined, meta, config),
|
|
);
|
|
const sent = direct.filter((event) => event !== null);
|
|
|
|
it("drops exactly the events the backend quarantines", () => {
|
|
expect(sent.map((event) => event!.event)).toEqual(golden.loaderEvents.map((event) => event.event));
|
|
expect(direct.find((_, i) => golden.envelope.events[i]!.name === "question_response.delivery")).toBeNull();
|
|
});
|
|
|
|
it("matches the loader output except for the intended Cloud differences", () => {
|
|
golden.loaderEvents.forEach((loader: LoaderEvent, index) => {
|
|
const ours = sent[index]!;
|
|
const inputDims = golden.envelope.events.find((e) => e.name === loader.event)!.dimensions as Record<string, unknown>;
|
|
const hasPrivateRef = "task_id" in inputDims;
|
|
|
|
// Same envelope-level fields; uuid differs only when the dimensions do.
|
|
expect(ours.event).toBe(loader.event);
|
|
expect(ours.timestamp).toBe(loader.timestamp);
|
|
expect(ours.disableGeoip).toBe(loader.disableGeoip);
|
|
expect(ours.sendFeatureFlags).toBe(loader.sendFeatureFlags);
|
|
if (hasPrivateRef) expect(ours.uuid).not.toBe(loader.uuid);
|
|
else expect(ours.uuid).toBe(loader.uuid);
|
|
|
|
// Intended differences: real ids and Cloud workspace properties.
|
|
const intended = {
|
|
distinct_id: "workspace:stack-123",
|
|
stack_id: "stack-123",
|
|
attributed_via: "none",
|
|
environment: "staging",
|
|
$groups: { workspace: "stack-123" },
|
|
...("agent_id" in inputDims ? { agent_id: inputDims.agent_id } : {}),
|
|
...(hasPrivateRef ? { task_id: golden.rawTaskId } : {}),
|
|
};
|
|
expect(ours.distinct_id).toBe("workspace:stack-123");
|
|
expect(ours.properties).toEqual({ ...loader.properties, ...intended });
|
|
// Key order matches too, so the stored property layout is identical.
|
|
expect(Object.keys(ours.properties).slice(0, Object.keys(loader.properties).length - 2)).toEqual(
|
|
Object.keys(loader.properties).filter((key) => key !== "distinct_id" && key !== "$process_person_profile"),
|
|
);
|
|
});
|
|
});
|
|
|
|
it("uses the acting user as distinct_id and links the browser session", () => {
|
|
const event = buildPostHogDirectEvent(
|
|
{ name: "routine.created", occurredAt: "2026-11-17T11:58:06.000Z", dimensions: {} },
|
|
{ userId: "user-1", companyId: "company-1", sessionId: "sess-1", windowId: "win-1" },
|
|
meta,
|
|
config,
|
|
)!;
|
|
expect(event.distinct_id).toBe("user-1");
|
|
expect(event.properties).toMatchObject({
|
|
distinct_id: "user-1",
|
|
user_id: "user-1",
|
|
company_id: "company-1",
|
|
attributed_via: "request",
|
|
$session_id: "sess-1",
|
|
$window_id: "win-1",
|
|
$groups: { workspace: "stack-123" },
|
|
});
|
|
expect(event.properties).not.toHaveProperty("$process_person_profile");
|
|
});
|
|
|
|
it("falls back to the workspace id without an acting user", () => {
|
|
expect(resolveDistinctId(config, undefined)).toBe("workspace:stack-123");
|
|
expect(resolveDistinctId(config, { companyId: "company-1", sessionId: "sess-1" })).toBe("workspace:stack-123");
|
|
expect(resolveDistinctId(config, { userId: "user-9" })).toBe("user-9");
|
|
});
|
|
|
|
it("keeps every generated fallback rule tied to an enum in the shared contract", () => {
|
|
const domains = PAPERCLIP_ENUM_DESCRIPTIONS as Record<string, Record<string, Record<string, string>>>;
|
|
for (const [eventName, rules] of Object.entries(UNKNOWN_ENUM_FALLBACKS)) {
|
|
for (const [key, rule] of Object.entries(rules)) {
|
|
expect(Object.keys(domains[eventName]?.[key] ?? {}), `${eventName}.${key}`).toContain(rule.fallback);
|
|
}
|
|
}
|
|
});
|
|
});
|