Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
### Dependencies

- `fpai-collect`: update `notify` from 8.2.2 to 9.0.0 and `rusqlite` from 0.42.0 to 0.43.0 (#1049)
- Update `posthog-node` from 5.73.0 to 6.0.5. The dashboard server's events now go to PostHog's Capture V1 endpoint (`/i/v1/analytics/events`) and keep the `$lib` they set, so they report `$lib: failproofai` with a `$lib_version` instead of `posthog-node`; the real delivery test checks the new endpoint, its bearer token, per-event acknowledgements and retries (#1043)

## 1.0.18-beta.0 — 2026-11-24

Expand Down
50 changes: 30 additions & 20 deletions __tests__/lib/telemetry-delivery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@ vi.mock("@/lib/telemetry-id", () => ({
}));

import { initTelemetry, trackEvent, shutdownTelemetry } from "@/lib/telemetry";
import { version } from "../../package.json";
import { trackHookEvent, flushHookTelemetry } from "@/src/hooks/hook-telemetry";

interface CapturedRequest {
url: string;
body: string;
authorization?: string;
}

interface TestServer {
Expand Down Expand Up @@ -60,12 +62,22 @@ async function startServer(opts: { failFirst?: number } = {}): Promise<TestServe
req.headers["content-encoding"] === "gzip"
? gunzipSync(raw).toString("utf-8")
: raw.toString("utf-8");
received.push({ url: req.url ?? "", body });
received.push({ url: req.url ?? "", body, authorization: req.headers.authorization });
if (opts.failFirst && hits <= opts.failFirst) {
res.writeHead(500, { "Content-Type": "application/json" }).end("{}");
return;
}
res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify({ status: 1 }));
// PostHog 6's Capture V1 acknowledges each event by UUID. The raw hook
// dispatcher still uses /capture/ and its legacy response shape.
const response = req.url === "/i/v1/analytics/events"
? {
results: Object.fromEntries(
(JSON.parse(body) as { batch: Array<{ uuid: string }> }).batch
.map(({ uuid }) => [uuid, { result: "ok" }]),
),
}
: { status: 1 };
res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(response));
});
});

Expand Down Expand Up @@ -115,6 +127,7 @@ describe("lib/telemetry delivery (real posthog-node)", () => {

afterEach(async () => {
await shutdownTelemetry().catch(() => {});
vi.restoreAllMocks();
globalThis.__FAILPROOFAI_POSTHOG__ = undefined;
delete process.env.FAILPROOFAI_POSTHOG_KEY;
delete process.env.FAILPROOFAI_POSTHOG_HOST;
Expand All @@ -136,7 +149,9 @@ describe("lib/telemetry delivery (real posthog-node)", () => {
await waitFor(() => deliveredEvents(ph!.received).includes("app_started"), 10_000);

expect(deliveredEvents(ph.received)).toContain("app_started");
expect(ph.received.map((r) => r.url)).toContain("/batch/");
expect(ph.received.map((r) => r.url)).toContain("/i/v1/analytics/events");
expect(ph.received.find((r) => r.url === "/i/v1/analytics/events")?.authorization)
.toBe("Bearer phc_delivery_test");

// The payload is the point — assert the properties survived the trip, not
// just that some request arrived.
Expand All @@ -152,33 +167,28 @@ describe("lib/telemetry delivery (real posthog-node)", () => {
failproofai_version: expect.any(String),
});

// `$lib` is NOT ours on this path, despite trackEvent() setting it to
// "failproofai": posthog-node owns that reserved property and overwrites it
// with its own name and version on every event. (The raw-fetch dispatcher in
// src/hooks/hook-telemetry.ts has no SDK to overwrite it, so its
// "failproofai-hooks" value does survive — the two paths disagree by
// construction.) Attribution that actually holds across both is `product`,
// asserted above; pinned here so nobody "fixes" trackEvent to fight the SDK.
expect((event!.properties as Record<string, unknown>).$lib).toBe("posthog-node");
// posthog-node 6 keeps the `$lib` an event sets, where 5 overwrote it with
// "posthog-node". It does not fill `$lib_version` for another library's
// name, so trackEvent sends both, as the daemon does for its own `$lib`.
expect(event!.properties).toMatchObject({ $lib: "failproofai", $lib_version: version });
}, 15_000);

it("does not log a flush error when delivery succeeds", async () => {
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {});
ph = await startServer();
process.env.FAILPROOFAI_POSTHOG_HOST = ph.url;

await initTelemetry();
trackEvent("app_started");
await waitFor(() => deliveredEvents(ph!.received).includes("app_started"), 10_000);

// posthog-node reports flush failures through a hardcoded console.error
// (`logFlushError`) on a fire-and-forget internal promise — no `.catch()` at
// our call sites can intercept it, so this is the only way to assert it.
const flushErrors = consoleError.mock.calls.filter((c) =>
String(c[0]).includes("Error while flushing PostHog"),
);
expect(flushErrors).toEqual([]);
consoleError.mockRestore();
expect(deliveredEvents(ph.received)).toContain("app_started");
// Wait for the SDK to process the acknowledgement. A request reaching the
// server is insufficient if the client rejects the response as unreadable.
await shutdownTelemetry();
expect(consoleError).not.toHaveBeenCalled();
expect(consoleWarn).not.toHaveBeenCalled();
}, 15_000);

it("retries a failed send and still delivers the event", async () => {
Expand All @@ -190,7 +200,7 @@ describe("lib/telemetry delivery (real posthog-node)", () => {
await initTelemetry();
trackEvent("app_started");

// posthog-node's first retry waits `fetchRetryDelay` (3s), so budget past it.
// Allow time for the SDK's retry backoff.
await waitFor(() => ph!.hits() >= 2, 20_000);

expect(ph.hits()).toBeGreaterThanOrEqual(2);
Expand Down
2 changes: 1 addition & 1 deletion __tests__/lib/telemetry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ describe("lib/telemetry", () => {
expect(mockCapture).toHaveBeenCalledWith({
distinctId: "test-instance-id",
event: "app_started",
properties: { $lib: "failproofai", failproofai_version: expect.any(String), product: "failproofai-oss" },
properties: { $lib: "failproofai", $lib_version: expect.any(String), failproofai_version: expect.any(String), product: "failproofai-oss" },
});
});
});
Expand Down
8 changes: 4 additions & 4 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion lib/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,18 @@ export function trackEvent(
const client = globalThis.__FAILPROOFAI_POSTHOG__;
if (!client) return;

// posthog-node 6 keeps a `$lib` the event sets (5 overwrote it with its own
// name), and sends `$lib_version` only when the event sets it too.
client.capture({
distinctId: getInstanceId(),
event: name,
properties: { ...properties, $lib: "failproofai", failproofai_version: version, product: POSTHOG_PRODUCT },
properties: {
...properties,
$lib: "failproofai",
$lib_version: version,
failproofai_version: version,
product: POSTHOG_PRODUCT,
},
});
}

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@
"jsonc-parser": "^3.3.1",
"lucide-react": "^1.33.0",
"next": "^16.3.8",
"posthog-node": "^5.50.0",
"posthog-node": "^6.0.5",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"smol-toml": "^1.9.1",
Expand Down