mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-27 11:40:00 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - First-party telemetry tells the team which product steps people finish > - Telemetry did not record when a model is connected, when a task is created, completed, or blocked, when a plan is created or approved, or when an artifact is created > - Telemetry also did not tell why an agent run failed, so failures could not be grouped by cause > - This pull request syncs the new telemetry contract and sends these events from the server once per real change > - The benefit is a product funnel and a failure breakdown that use only enums, booleans, and counts ## Linked Issues or Issue Description **Subsystem affected** Server telemetry (`packages/shared/src/telemetry`, `server/src/services/product-telemetry.ts`) and the emit sites in the issue, document, work product, interaction, and AI connection services. **Problem or motivation** The team cannot measure the main product path. There is no event for a new model connection, a new task, a completed task, a blocked task, a new plan, an approved plan, or a new artifact. `agent.task_run` tells that a run failed, but not why. The signup funnel also must know when the onboarding wizard created the first task. **Proposed solution** Register the events in the telemetry backend. Sync the generated contract here. Add typed helpers. Send each event once, after the transaction that makes the change commits. Use fixed enums for every kind, reason, and cause. **Alternatives considered** A post-commit action queue on the issue service only. The native status path and many other callers use an external transaction without that queue, so most agent completions would not send an event. A generic after-commit hook on the database client covers every caller. **Roadmap alignment** This is telemetry for existing features. It adds no new product feature. **Additional context** This change depends on paperclipai/telemetry-backend#150, which is merged. Deploy that backend change before this change ships. Until then, the collector rejects the new event names. ## What Changed - Sync `generated/paperclip-telemetry.ts` from the backend branch as a direct copy. Regenerate `posthog-direct/enum-fallbacks.generated.ts` with `scripts/generate-posthog-direct-fixtures.mjs`. The loader golden file did not change. - Add `afterTransactionCommit()` to `@paperclipai/db`. It runs a callback after the outermost transaction commits. It drops the callback on rollback. Outside a transaction it runs the callback at once. A callback that throws never fails the committed work. - Add helpers `trackModelConnected`, `trackTaskCreated`, `trackTaskCompleted`, `trackTaskBlocked`, `trackPlanCreated`, `trackPlanApproved`, and `trackArtifactCreated`. Add `failureCause` to `trackAgentTaskRun`. Assign the new events to `operational_enum_count` retention. - Add `server/src/services/product-telemetry.ts`. It sends each event after commit inside `withTelemetryCompany()`, so Cloud direct delivery gets `company_id` for background writes. - Emit sites: - `model.connected`: `aiConnectionService.save`, for a new connection only. A reconnect sends nothing. `first_for_company` is true when the company had no earlier model connection. - `task.created`: `issueService.create`, after the insert. A deduplicated create, a company import, and a chat conversation send nothing. `created_by_kind` is `routine` for routine runs, `onboarding` for the onboarding wizard's first task, and otherwise `user`, `agent`, or `system`. - `task.completed` and `task.blocked`: `issueService.update`, when the status changes to `done` or `blocked`. The same status again sends nothing. - `plan.created`: `documentService.upsertIssueDocument`, for the first revision of the `plan` document. - `plan.approved`: the accept path of a `request_confirmation` that targets the task's `plan` document. - `artifact.created`: `workProductService.createForIssue` (`direct`), the promotion route (`promotion`), and a run file deliverable (`run_deliverable`). - `agent.task_run.failure_cause`: `emitAgentTaskRun`, for `failed`, `timed_out`, and `interrupted` runs only. - `blocked_reason` mapping: unfinished blocking tasks give `waiting_on_task`. Otherwise an unblock owner of a person or the board gives `waiting_for_person`, and an agent owner gives `waiting_for_agent`. A system write with neither gives `needs_recovery`. A person or agent write with neither gives `unspecified`. - `failure_cause` mapping (stored `errorCode`, with `resultJson.providerFailure.category` for generic provider and adapter codes): - `missing_access`: auth and permission codes (`acpx_auth_required`, `provider_auth_failed`, `user_secret_missing`, `github_access_denied`, `github_repo_not_accessible`, `permission_denied`, `project_access_denied`, `configuration_incomplete`, `connection_unavailable`, `signing_secret_unconfigured`), and provider category `authentication` or `permission`. - `provider_limit`: `provider_quota`, `native_provider_usage_limit`, `native_provider_overloaded`, `github_rate_limited`, `ai_connection_busy`, and provider category `rate_limit`, `quota_exhausted`, or `overloaded`. - `provider_error`: `native_provider_model_rejected`, `provider_transport_failed`, `codex_transient_upstream`, `provider_failed`, `provider_tool_definition_invalid`, and the other provider categories. - `waiting_for_person`: `execution_reconciliation_required`, every code in `EXECUTION_RECONCILIATION_CAUSES`, `issue_waiting_for_response`, and `issue_continuation_waiting_on_review`. - `task_changed`: the task was reassigned, paused, closed, blocked, or stopped by a person (`operator_interrupted`, `cancelled`, `interrupted`, `issue_*` lifecycle codes, `agent_paused`, `queued_comment_discarded`). - `platform_error`: process, server, workspace, sandbox, runner, and storage codes (`process_lost`, `server_shutdown_interrupted`, `setup_failed`, `workspace_*`, `environment_provider_unavailable`, `controller_lease_lost`, and others). - `agent_error`: `adapter_failed` without a provider failure, `invalid_output`, `invalid_response`, `tool_error`, `acpx_turn_failed`, `test_run_failed`, `prompt_injection_blocked`, `tool_execution_outcome_unknown`, `timeout`. - `unknown`: any other code, or no code. - On Cloud direct delivery, every new emit site names the responsible person with `withTelemetryActor()` and `resolveTelemetryPerson()`, as `agent.task_run` does: the task creator, else the task's responsible user, else the run owner. `task.created` uses the creating user, else the agent's on-behalf user. `model.connected` uses the user who owns the connection. A live request still wins. The self-hosted collector envelope does not change. - `failure_cause` builds on the run failure code sets in `continuation-cause.ts`. A test fails when a code in those sets has no telemetry code. The provider failure category decides only for `adapter_failed`, `provider_failed`, or no code. - Work product providers outside `paperclip`, `github`, `vercel`, and `s3` are sent as `custom`. - The dispatch workspace check and execution recovery write `blocked` directly. They call the same after-commit helper, with the task's real blockers and unblock owner. The blocker read runs in a savepoint in the issue dependency layer, so a failed read never aborts the block write. - Update the telemetry README with the emit rules, the after-commit rule, and the `failure_cause` source. - Refresh `tests/runner-e2e/source-sdk-public-inputs.json`, because its check reported a change. ## Privacy Review Privacy review requested. Every new dimension is a fixed enum, a boolean, or a count. No dimension carries a title, a body, a plan step, a connection or account name, an email, a URL, a repository name, a prompt, an error message, or an endpoint address. `failure_cause` is a code that the server picks. The run's error text is never sent. The tests check that a provider message and a connection name do not reach the event. ## Verification - `pnpm vitest run packages/shared/src/telemetry/`: 7 files pass, including the new `product-events.test.ts` (helper payloads, omitted optional values, collector envelope with only registered dimensions, retention class). - `packages/db/src/after-transaction-commit.test.ts`: 4 pass (after commit, rollback drop, savepoint, outside a transaction). - `server/src/__tests__/product-telemetry.test.ts`: 14 pass. They check that each event fires once with the right kind and company scope, that a rollback sends nothing, that a repeated status sends nothing, that a later plan revision sends nothing, and that a reconnect sends nothing. - `server/src/__tests__/agent-task-run-telemetry.test.ts`: 35 pass, including the `failure_cause` mapping table and the emit path. - `server/src/__tests__/issue-thread-interactions-service.test.ts -t Plan`: `plan.approved` fires for a plan confirmation and not for an unrelated confirmation. - `server/src/__tests__/posthog-direct-telemetry.test.ts`: the Cloud direct path sends `company_id`, `user_id`, and `attributed_via` for background lifecycle events, an event with no person stays on the workspace, and `failure_cause` passes through. A self-hosted test checks that a person scope leaves the collector events unchanged. - Existing telemetry tests (connector, interaction, run finalizer, heartbeat, AI connection): 299 pass. - `pnpm --filter @paperclipai/shared typecheck`, `pnpm --filter @paperclipai/db typecheck`, and `pnpm --filter @paperclipai/server typecheck`: pass. - `pnpm verify` returned exit 2 (global CI input changed). Required CI supplies the broad coverage. ## Risks - Merge order: merge and deploy paperclipai/telemetry-backend#150 first. If this change ships first, the collector quarantines the new events. The product behavior does not change. - `afterTransactionCommit` uses the existing open-transaction marker in the database client. A callback that a savepoint registers runs when the outer transaction commits, even if that savepoint rolled back. - `task.blocked` adds one small indexed read inside the update transaction, only when a task enters `blocked`. - `failure_cause` adds one small read for a failed run when the caller did not pass the error code. It runs off the run's critical path, as before. - Low risk otherwise. No schema migration. No change to existing event dimensions. > 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 - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code, with tool use (shell, Git, tests). ## 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 - [ ] 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
275 lines
15 KiB
TypeScript
275 lines
15 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { eq } from "drizzle-orm";
|
|
import { mkdtemp, realpath, rm } from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { agents, companies, companyMemberships, createDb, issues } from "@paperclipai/db";
|
|
import {
|
|
getEmbeddedPostgresTestSupport,
|
|
startEmbeddedPostgresTestDatabase,
|
|
} from "./helpers/embedded-postgres.js";
|
|
import { scopedTelemetryCompanyId, scopedTelemetryPerson } from "../telemetry-company-scope.js";
|
|
|
|
const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() }));
|
|
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 }>);
|
|
|
|
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");
|
|
const record = (event: string) => (_client: unknown, dims: Record<string, unknown>) => {
|
|
calls.push({ event, dims, companyId: scopedTelemetryCompanyId() });
|
|
people.push({ event, person: scopedTelemetryPerson() ?? null });
|
|
};
|
|
return {
|
|
...actual,
|
|
trackTaskCreated: record("task.created"),
|
|
trackTaskCompleted: record("task.completed"),
|
|
trackTaskBlocked: record("task.blocked"),
|
|
trackPlanCreated: record("plan.created"),
|
|
trackPlanApproved: record("plan.approved"),
|
|
trackArtifactCreated: record("artifact.created"),
|
|
trackModelConnected: record("model.connected"),
|
|
};
|
|
});
|
|
|
|
import { issueService } from "../services/issues.ts";
|
|
import { documentService } from "../services/documents.ts";
|
|
import { workProductService } from "../services/work-products.ts";
|
|
import { aiConnectionService } from "../services/ai-connections.ts";
|
|
import { hasUnfinishedBlockers } from "../services/issue-dependency-wakeups.ts";
|
|
import { emitSystemTaskBlockedAfterCommit, taskBlockedReason, telemetryActorKind } from "../services/product-telemetry.ts";
|
|
|
|
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
|
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
|
|
|
describe("product telemetry classification", () => {
|
|
it("classifies the acting kind", () => {
|
|
expect(telemetryActorKind({ agentId: "a", userId: "u" })).toBe("agent");
|
|
expect(telemetryActorKind({ userId: "u" })).toBe("user");
|
|
expect(telemetryActorKind({})).toBe("system");
|
|
});
|
|
|
|
it.each([
|
|
[{ hasOpenBlockers: true, unblockDescriptor: { owner: "board" as const, action: "x" }, actorKind: "agent" as const }, "waiting_on_task"],
|
|
[{ hasOpenBlockers: false, unblockDescriptor: { owner: "board" as const, action: "x" }, actorKind: "agent" as const }, "waiting_for_person"],
|
|
[{ hasOpenBlockers: false, unblockDescriptor: { owner: { userId: "u" }, action: "x" }, actorKind: "agent" as const }, "waiting_for_person"],
|
|
[{ hasOpenBlockers: false, unblockDescriptor: { owner: { agentId: "a" }, action: "x" }, actorKind: "user" as const }, "waiting_for_agent"],
|
|
[{ hasOpenBlockers: false, unblockDescriptor: null, actorKind: "system" as const }, "needs_recovery"],
|
|
[{ hasOpenBlockers: false, unblockDescriptor: null, actorKind: "user" as const }, "unspecified"],
|
|
])("maps %o to %s", (input, expected) => {
|
|
expect(taskBlockedReason(input)).toBe(expected);
|
|
});
|
|
});
|
|
|
|
describeEmbeddedPostgres("product telemetry emit sites", () => {
|
|
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
|
let db: ReturnType<typeof createDb>;
|
|
let companyId: string;
|
|
let agentId: string;
|
|
|
|
let home: string;
|
|
|
|
beforeAll(async () => {
|
|
home = await realpath(await mkdtemp(path.join(os.tmpdir(), "paperclip-product-telemetry-")));
|
|
vi.stubEnv("PAPERCLIP_HOME", home);
|
|
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "product-telemetry-fixture");
|
|
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-product-telemetry-");
|
|
db = createDb(tempDb.connectionString);
|
|
}, 60_000);
|
|
|
|
afterAll(async () => {
|
|
await tempDb?.cleanup();
|
|
vi.unstubAllEnvs();
|
|
if (home) await rm(home, { recursive: true, force: true });
|
|
});
|
|
|
|
beforeEach(async () => {
|
|
calls.length = 0;
|
|
people.length = 0;
|
|
companyId = randomUUID();
|
|
agentId = randomUUID();
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Paperclip",
|
|
issuePrefix: `P${companyId.replace(/-/g, "").slice(0, 5).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false,
|
|
});
|
|
await db.insert(agents).values({
|
|
id: agentId, companyId, name: "Coder", role: "engineer", status: "active",
|
|
adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {},
|
|
});
|
|
});
|
|
|
|
async function seedIssue(values: Partial<typeof issues.$inferInsert> = {}) {
|
|
const id = randomUUID();
|
|
await db.insert(issues).values({ id, companyId, title: `Task ${id.slice(0, 6)}`, status: "todo", priority: "medium", ...values });
|
|
return id;
|
|
}
|
|
|
|
const sent = (event: string) => calls.filter((call) => call.event === event);
|
|
|
|
it("emits task.created once per committed task in the company scope, with the creator kind", async () => {
|
|
const parent = await issueService(db).create(companyId, { title: "Parent", createdByUserId: "user-1" });
|
|
await issueService(db).create(companyId, { title: "Child", parentId: parent.id, createdByAgentId: agentId });
|
|
await issueService(db).create(companyId, { title: "First task", createdByUserId: "user-1", originKind: "onboarding_first_task" });
|
|
|
|
expect(sent("task.created")).toEqual([
|
|
{ event: "task.created", dims: { createdByKind: "user", isSubtask: false }, companyId },
|
|
{ event: "task.created", dims: { createdByKind: "agent", isSubtask: true }, companyId },
|
|
{ event: "task.created", dims: { createdByKind: "onboarding", isSubtask: false }, companyId },
|
|
]);
|
|
expect(scopedTelemetryCompanyId()).toBeUndefined();
|
|
expect(people.map((entry) => entry.person)).toEqual([
|
|
{ userId: "user-1", attributedVia: "task_creator" },
|
|
{ userId: "user-1", attributedVia: "task_assigner" },
|
|
{ userId: "user-1", attributedVia: "task_creator" },
|
|
]);
|
|
});
|
|
|
|
it("attributes agent-driven lifecycle events to the task's person on the direct path", async () => {
|
|
const fromPerson = await seedIssue({ status: "in_progress", createdByUserId: "creator-1", responsibleUserId: "owner-1" });
|
|
const fromOwner = await seedIssue({ status: "in_progress", responsibleUserId: "owner-1" });
|
|
const unowned = await seedIssue({ status: "in_progress" });
|
|
people.length = 0;
|
|
await issueService(db).update(fromPerson, { status: "done", actorAgentId: agentId });
|
|
await issueService(db).update(fromOwner, { status: "done", actorAgentId: agentId });
|
|
await issueService(db).update(unowned, { status: "done", actorAgentId: agentId });
|
|
|
|
expect(people).toEqual([
|
|
{ event: "task.completed", person: { userId: "creator-1", attributedVia: "task_creator" } },
|
|
{ event: "task.completed", person: { userId: "owner-1", attributedVia: "task_assigner" } },
|
|
{ event: "task.completed", person: null },
|
|
]);
|
|
});
|
|
|
|
it("emits nothing for a create whose transaction rolls back", async () => {
|
|
await expect(db.transaction(async (tx) => {
|
|
await issueService(tx as unknown as typeof db).create(companyId, { title: "Rolled back", createdByUserId: "user-1" }, tx);
|
|
throw new Error("rollback");
|
|
})).rejects.toThrow("rollback");
|
|
expect(sent("task.created")).toEqual([]);
|
|
});
|
|
|
|
it("emits task.completed once per transition to done", async () => {
|
|
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 });
|
|
await issueService(db).update(id, { status: "todo", actorUserId: "user-1" });
|
|
await issueService(db).update(id, { status: "done" });
|
|
|
|
expect(sent("task.completed").map((call) => [call.dims, call.companyId])).toEqual([
|
|
[{ completedByKind: "agent", isSubtask: false }, companyId],
|
|
[{ completedByKind: "system", isSubtask: false }, companyId],
|
|
]);
|
|
});
|
|
|
|
it("emits task.blocked with the blocking reason at the transition", async () => {
|
|
const blocker = await seedIssue({ status: "todo" });
|
|
const waiting = await seedIssue({ status: "todo" });
|
|
const recovering = await seedIssue({ status: "in_progress" });
|
|
const forPerson = await seedIssue({ status: "in_progress" });
|
|
const cancelledBlocker = await seedIssue({ status: "cancelled" });
|
|
const waitingOnCancelled = await seedIssue({ status: "todo" });
|
|
await issueService(db).update(waiting, { status: "blocked", blockedByIssueIds: [blocker], actorAgentId: agentId });
|
|
await issueService(db).update(recovering, { status: "blocked" });
|
|
await issueService(db).update(forPerson, { status: "blocked", unblockDescriptor: { owner: "board", action: "Approve" }, actorAgentId: agentId });
|
|
await issueService(db).update(forPerson, { status: "blocked", actorAgentId: agentId });
|
|
await issueService(db).update(waitingOnCancelled, { status: "blocked", blockedByIssueIds: [cancelledBlocker], actorUserId: "user-1" });
|
|
|
|
expect(sent("task.blocked").map((call) => call.dims)).toEqual([
|
|
{ blockedReason: "waiting_on_task", blockedByKind: "agent" },
|
|
{ blockedReason: "needs_recovery", blockedByKind: "system" },
|
|
{ blockedReason: "waiting_for_person", blockedByKind: "agent" },
|
|
{ blockedReason: "waiting_on_task", blockedByKind: "user" },
|
|
]);
|
|
});
|
|
|
|
it("emits a direct system block with the task's real blockers and unblock owner", async () => {
|
|
const blocker = await seedIssue({ status: "cancelled" });
|
|
const dependent = await seedIssue({ status: "blocked" });
|
|
const ownerWait = await seedIssue({ status: "blocked", unblockDescriptor: { owner: { userId: "user-1" }, action: "Share access" } });
|
|
const recovery = await seedIssue({ status: "blocked" });
|
|
await issueService(db).update(dependent, { blockedByIssueIds: [blocker] });
|
|
calls.length = 0;
|
|
const load = async (id: string) => (await db.select().from(issues).where(eq(issues.id, id)))[0]!;
|
|
await db.transaction(async (tx) => {
|
|
await emitSystemTaskBlockedAfterCommit(tx, await load(dependent), "in_progress");
|
|
await emitSystemTaskBlockedAfterCommit(tx, await load(ownerWait), "todo");
|
|
await emitSystemTaskBlockedAfterCommit(tx, await load(recovery), "in_progress");
|
|
await emitSystemTaskBlockedAfterCommit(tx, await load(recovery), "blocked");
|
|
expect(sent("task.blocked")).toEqual([]);
|
|
});
|
|
|
|
expect(sent("task.blocked").map((call) => [call.dims, call.companyId])).toEqual([
|
|
[{ blockedReason: "waiting_on_task", blockedByKind: "system" }, companyId],
|
|
[{ blockedReason: "waiting_for_person", blockedByKind: "system" }, companyId],
|
|
[{ blockedReason: "needs_recovery", blockedByKind: "system" }, companyId],
|
|
]);
|
|
});
|
|
|
|
it("keeps the block write when the blocker read fails", async () => {
|
|
const id = await seedIssue({ status: "in_progress" });
|
|
await db.transaction(async (tx) => {
|
|
await tx.update(issues).set({ status: "blocked" }).where(eq(issues.id, id));
|
|
expect(await hasUnfinishedBlockers(tx, { companyId: "not-a-uuid", id })).toBe(false);
|
|
await tx.update(issues).set({ updatedAt: new Date() }).where(eq(issues.id, id));
|
|
});
|
|
expect((await db.select({ status: issues.status }).from(issues).where(eq(issues.id, id)))[0]?.status).toBe("blocked");
|
|
});
|
|
|
|
it("emits plan.created for the first plan revision only", async () => {
|
|
const id = await seedIssue();
|
|
const documents = documentService(db);
|
|
const first = await documents.upsertIssueDocument({ issueId: id, key: "plan", format: "markdown", body: "1. Do it", createdByAgentId: agentId });
|
|
await documents.upsertIssueDocument({ issueId: id, key: "plan", format: "markdown", body: "1. Do it well",
|
|
baseRevisionId: first.document.latestRevisionId, createdByAgentId: agentId });
|
|
await documents.upsertIssueDocument({ issueId: id, key: "notes", format: "markdown", body: "Not a plan", createdByUserId: "user-1" });
|
|
|
|
expect(sent("plan.created")).toEqual([
|
|
{ event: "plan.created", dims: { createdByKind: "agent", atTaskCreation: false }, companyId },
|
|
]);
|
|
});
|
|
|
|
it("emits artifact.created with the work product type and provider", async () => {
|
|
const id = await seedIssue();
|
|
await workProductService(db).createForIssue(id, companyId, {
|
|
type: "pull_request", provider: "github", title: "Fix", status: "open", url: "https://example.invalid/pr/1",
|
|
});
|
|
await workProductService(db).createForIssue(id, companyId, {
|
|
type: "preview_url", provider: "acme-private-deploys", title: "Preview", status: "active",
|
|
});
|
|
expect(sent("artifact.created")).toEqual([
|
|
{ event: "artifact.created", dims: { artifactType: "pull_request", provider: "github", creationFlow: "direct" }, companyId },
|
|
{ event: "artifact.created", dims: { artifactType: "preview_url", provider: "custom", creationFlow: "direct" }, companyId },
|
|
]);
|
|
expect(JSON.stringify(sent("artifact.created"))).not.toContain("acme");
|
|
expect(people.filter((entry) => entry.event === "artifact.created").map((entry) => entry.person)).toEqual([null, null]);
|
|
const owned = await seedIssue({ createdByUserId: "creator-1" });
|
|
people.length = 0;
|
|
await workProductService(db).createForIssue(owned, companyId, { type: "branch", provider: "github", title: "Branch", status: "active" });
|
|
expect(people).toEqual([{ event: "artifact.created", person: { userId: "creator-1", attributedVia: "task_creator" } }]);
|
|
});
|
|
|
|
it("emits model.connected for a new model connection and not for its reconnect", async () => {
|
|
await db.insert(companyMemberships).values({ companyId, principalId: "alice", principalType: "user", status: "active", membershipRole: "member" });
|
|
const service = aiConnectionService(db);
|
|
const first = await service.save(companyId, "alice", { provider: "anthropic", method: "api_key", ownership: "personal", name: "Alice key",
|
|
apiKey: "fixture-key", agentIds: [], allAgents: true }, "fixture-key");
|
|
await service.save(companyId, "alice", { provider: "openrouter", method: "api_key", ownership: "shared", name: "Shared router",
|
|
apiKey: "fixture-router", agentIds: [], allAgents: true, routing: { kind: "openrouter", protocol: "chat", auth: "bearer", models: [] } }, "fixture-router");
|
|
await service.save(companyId, "alice", { provider: "anthropic", method: "api_key", ownership: "personal", name: "Alice key",
|
|
apiKey: "fixture-key-2", agentIds: [], allAgents: true, connectionId: first.connectionId }, "fixture-key-2");
|
|
|
|
expect(sent("model.connected")).toEqual([
|
|
{ event: "model.connected", dims: { provider: "anthropic", connectionMethod: "api_key", ownership: "personal", routingKind: null, firstForCompany: true }, companyId },
|
|
{ event: "model.connected", dims: { provider: "openrouter", connectionMethod: "api_key", ownership: "shared", routingKind: "openrouter", firstForCompany: false }, companyId },
|
|
]);
|
|
expect(JSON.stringify(sent("model.connected"))).not.toContain("Alice");
|
|
});
|
|
});
|