Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add sanitized browser error reporting and response outcome analytics (#1392)

Regan Bell919613d6b47d
diff --git a/plugins/web-ui/README.md b/plugins/web-ui/README.md
index 7c83c8bee..7d085ec9d 100644
--- a/plugins/web-ui/README.md
+++ b/plugins/web-ui/README.md
@@ -302,9 +302,42 @@ performance capture and feature flags are disabled. Event properties exclude cha
content, URLs, query strings, titles and referrers. Delivery is best effort.
Set the same variables on core to capture `app_published` after a successful new
-application or version deployment. Core events use the application's creator and
+application or version deployment. Publications use the application's creator and
company, matching browser identity. No key means no analytics requests.
+Core also captures `response_completed` and `response_failed` when a human turn
+reaches its final run state, including when a separate worker executes it.
+`completion_boundary=run` means processing finished, not confirmed delivery to the
+user. Successful silent or reaction-only results count as completed processing.
+`result_status` distinguishes those results; `surface` identifies web or Slack.
+Automation, automatic openers, impersonated turns, stopped turns, refusals, queued
+results and pending approvals do not emit outcomes. Retries emit only at the final
+run state. Stable insert IDs support deduplication. These best-effort events are
+not a complete reliability ledger and contain no response text or raw errors.
+
+## Optional browser error reporting
+
+Set `SENTRY_BROWSER_DSN` on the web server to enable browser error reporting.
+Use a public HTTPS DSN without a secret key, such as
+`https://[email protected]/1`. Backend `SENTRY_DSN` is never exposed or
+used as a browser fallback. The authenticated `/me` response supplies the public
+DSN and an optional `SENTRY_RELEASE` (or `GIT_SHA`). The server adds only the DSN
+origin to the web application's connection policy.
+
+Reporting starts after authentication and stops on sign-out or an authentication
+failure. It is disabled during impersonation and when the browser DSN is unset.
+Only uncaught errors and unhandled promise rejections are collected. Events retain
+standard error types, release, and same-origin compiled asset filenames with line
+and column numbers. Fingerprints use the sanitized error type, capture mechanism,
+and last retained stack position. Identical asset locations group across release
+label changes; changed asset hashes start separate groups. Without a retained
+frame, grouping falls back to the sanitized type and mechanism.
+Other stack frames and function names are omitted. Messages,
+URLs, requests, user identities, content, attachments, breadcrumbs, replay, logs,
+and tracing are excluded. A final transport gate rejects unsanitized SDK failures
+and non-event envelopes. Requests omit cookies and referrers. The ingestion
+server can still see the network source IP. Delivery is best effort.
+
## Personal AI accounts
Open **Settings → AI access**, or use the account label beside the model picker.
diff --git a/plugins/web-ui/package-lock.json b/plugins/web-ui/package-lock.json
index d1a140500..66e86a51b 100644
--- a/plugins/web-ui/package-lock.json
+++ b/plugins/web-ui/package-lock.json
@@ -13,6 +13,7 @@
"@earendil-works/pi-ai": "0.77.0",
"@earendil-works/pi-web-ui": "0.75.3",
"@mariozechner/mini-lit": "^0.2.0",
+ "@sentry/browser": "10.75.0",
"@sentry/node": "10.75.0",
"@tanstack/ai": "0.54.0",
"@tanstack/ai-client": "0.31.1",
@@ -2204,6 +2205,36 @@
"win32"
]
},
+ "node_modules/@sentry/browser": {
+ "version": "10.75.0",
+ "resolved": "https://registry.npmjs.org/@sentry/browser/-/browser-10.75.0.tgz",
+ "integrity": "sha512-CKGSJLWISQ6LgMaGnMpY+XvwWQ2iiHTayUs6SGLIvYeaGo2GTjS/Z4pnbCVHb2t1VxLZksyehgcC6ZYGJeQpzQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@sentry/browser-utils": "10.75.0",
+ "@sentry/conventions": "^0.16.0",
+ "@sentry/core": "10.75.0",
+ "@sentry/feedback": "10.75.0",
+ "@sentry/replay": "10.75.0",
+ "@sentry/replay-canvas": "10.75.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@sentry/browser-utils": {
+ "version": "10.75.0",
+ "resolved": "https://registry.npmjs.org/@sentry/browser-utils/-/browser-utils-10.75.0.tgz",
+ "integrity": "sha512-yZfdQ87RLat/7retF8zA6Z9zCAT12IyaPvIiu+bbi1E1V1OqDpS8MKNa/6LF69Ap7DVTORi9ITEgjlAqTXF0xQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@sentry/conventions": "^0.16.0",
+ "@sentry/core": "10.75.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@sentry/conventions": {
"version": "0.16.0",
"resolved": "https://registry.npmjs.org/@sentry/conventions/-/conventions-0.16.0.tgz",
@@ -2225,6 +2256,18 @@
"node": ">=18"
}
},
+ "node_modules/@sentry/feedback": {
+ "version": "10.75.0",
+ "resolved": "https://registry.npmjs.org/@sentry/feedback/-/feedback-10.75.0.tgz",
+ "integrity": "sha512-YLVAFQXELJAOg7ke4oLkd8t5l0fJUockLlTQJg/2Trh7SB5Q4mkSwlnAkEAqDQ618vnpFsG/tnYMwtfZeffHjA==",
+ "license": "MIT",
+ "dependencies": {
+ "@sentry/core": "10.75.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@sentry/node": {
"version": "10.75.0",
"resolved": "https://registry.npmjs.org/@sentry/node/-/node-10.75.0.tgz",
@@ -2302,6 +2345,32 @@
"@opentelemetry/sdk-trace-base": "^1.30.1 || ^2.1.0"
}
},
+ "node_modules/@sentry/replay": {
+ "version": "10.75.0",
+ "resolved": "https://registry.npmjs.org/@sentry/replay/-/replay-10.75.0.tgz",
+ "integrity": "sha512-p4xxEo/ayiMZG9tygr09YjqYAd52uq8Qi0EVoRRgUe70nQda0HVPVW519JLq0G+Th/5O5sKME9y1layLU3xlPg==",
+ "license": "MIT",
+ "dependencies": {
+ "@sentry/browser-utils": "10.75.0",
+ "@sentry/core": "10.75.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@sentry/replay-canvas": {
+ "version": "10.75.0",
+ "resolved": "https://registry.npmjs.org/@sentry/replay-canvas/-/replay-canvas-10.75.0.tgz",
+ "integrity": "sha512-LNokI5Ud22nZ/o2il/2SfbNIARupWrbS6Mh9jZroZTjD38FN0Oi9vIexj6h1HN81C6+lP2Tmpaj+fl3/wOizzA==",
+ "license": "MIT",
+ "dependencies": {
+ "@sentry/core": "10.75.0",
+ "@sentry/replay": "10.75.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@sentry/server-utils": {
"version": "10.75.0",
"resolved": "https://registry.npmjs.org/@sentry/server-utils/-/server-utils-10.75.0.tgz",
diff --git a/plugins/web-ui/package.json b/plugins/web-ui/package.json
index 0c44faa3d..82e3153d6 100644
--- a/plugins/web-ui/package.json
+++ b/plugins/web-ui/package.json
@@ -21,6 +21,7 @@
"@earendil-works/pi-ai": "0.77.0",
"@earendil-works/pi-web-ui": "0.75.3",
"@mariozechner/mini-lit": "^0.2.0",
+ "@sentry/browser": "10.75.0",
"@sentry/node": "10.75.0",
"@tanstack/ai": "0.54.0",
"@tanstack/ai-client": "0.31.1",
diff --git a/plugins/web-ui/server/browser-error-config.ts b/plugins/web-ui/server/browser-error-config.ts
new file mode 100644
index 000000000..a0a383e15
--- /dev/null
+++ b/plugins/web-ui/server/browser-error-config.ts
@@ -0,0 +1,26 @@
+export function browserErrorConfig(env: NodeJS.ProcessEnv): { dsn: string; release?: string } | undefined {
+ const dsn = env.SENTRY_BROWSER_DSN?.trim();
+ if (!dsn) return undefined;
+ const invalid = () => new Error("SENTRY_BROWSER_DSN must be a public HTTPS DSN without a secret key");
+ let url: URL;
+ try {
+ url = new URL(dsn);
+ } catch {
+ throw invalid();
+ }
+ if (
+ url.protocol !== "https:" ||
+ !/^[a-zA-Z0-9]{1,128}$/.test(url.username) ||
+ url.password ||
+ !/^\/[1-9][0-9]*$/.test(url.pathname) ||
+ url.search ||
+ url.hash
+ ) {
+ throw invalid();
+ }
+ const release = env.SENTRY_RELEASE ?? env.GIT_SHA;
+ return {
+ dsn: url.href,
+ ...(release && /^[a-zA-Z0-9_.@+-]{1,128}$/.test(release) ? { release } : {}),
+ };
+}
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index 821eec71c..96ae13596 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -1,4 +1,5 @@
import "./instrument.ts";
+import { browserErrorConfig } from "./browser-error-config.ts";
import { flushErrorReporting, reportBackendError } from "../../chassis/src/error-reporting.ts";
import { appEditSlug } from "../src/app-edit.ts";
import { composioCallbackUrl } from "./composio-return.ts";
@@ -191,13 +192,16 @@ if (
}
const analyticsConfig = analyticsKey ? { apiKey: analyticsKey, host: analyticsHost.origin } : undefined;
+const browserErrors = browserErrorConfig(process.env);
+const browserErrorOrigin = browserErrors ? new URL(browserErrors.dsn).origin : undefined;
+
const SPA_CSP = [
"default-src 'self'",
"script-src 'self' 'wasm-unsafe-eval'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob: https:",
"font-src 'self' data:",
- `connect-src 'self'${analyticsConfig ? ` ${analyticsConfig.host}` : ""}`,
+ `connect-src 'self'${analyticsConfig ? ` ${analyticsConfig.host}` : ""}${browserErrorOrigin ? ` ${browserErrorOrigin}` : ""}`,
"frame-src 'self' data: https:",
"worker-src 'self' blob:",
"frame-ancestors 'self'",
@@ -678,7 +682,13 @@ function namespacedSendKey(user: string, raw: unknown): string | undefined {
return SEND_KEY_PATTERN.test(key) ? `web:${encodeURIComponent(user)}:${key}` : undefined;
}
-async function postTurnAndMint(res: ServerResponse, turn: unknown, user: string, threadRef: string): Promise<void> {
+async function postTurnAndMint(
+ req: IncomingMessage,
+ res: ServerResponse,
+ turn: Record<string, unknown>,
+ user: string,
+ threadRef: string,
+): Promise<void> {
const startedAt = performance.now();
let runId: string | undefined;
res.once("finish", () => {
@@ -688,7 +698,11 @@ async function postTurnAndMint(res: ServerResponse, turn: unknown, user: string,
elapsedMs: Math.round(performance.now() - startedAt),
});
});
- const r = await coreFetch("POST", `/v1/turns?async=1`, JSON.stringify(turn));
+ const r = await coreFetch(
+ "POST",
+ `/v1/turns?async=1`,
+ JSON.stringify({ ...turn, ...(resolveIdentity(req)?.impersonator ? { analyticsSuppressed: true } : {}) }),
+ );
if (r.status >= 200 && r.status < 300) {
try {
const parsed = JSON.parse(r.text) as Record<string, unknown> & { runId?: string };
@@ -1258,6 +1272,7 @@ const apiRoutes: readonly WebRoute[] = [
org: ORG,
companyName: companyBranding.orgName?.trim() || null,
...(analyticsConfig && !resolveIdentity(req)?.impersonator ? { analytics: analyticsConfig } : {}),
+ ...(browserErrors && !resolveIdentity(req)?.impersonator ? { browserErrors } : {}),
mode: AUTH_MODE,
slackWorkspaceUrl: workspaceUrl,
individualModelAuth: parsed.individualModelAuth === true,
@@ -2239,7 +2254,7 @@ const apiRoutes: readonly WebRoute[] = [
const replay: Record<string, unknown> = { ...record.request, approval };
delete replay.idempotencyKey;
if (idempotencyKey) replay.idempotencyKey = idempotencyKey;
- return postTurnAndMint(res, replay, user, threadRef);
+ return postTurnAndMint(req, res, replay, user, threadRef);
},
},
{
@@ -2327,7 +2342,7 @@ const apiRoutes: readonly WebRoute[] = [
...(proactiveOpener ? { proactiveOpener: true } : {}),
...(idempotencyKey ? { idempotencyKey } : {}),
};
- return postTurnAndMint(res, turn, user, threadRef);
+ return postTurnAndMint(req, res, turn, user, threadRef);
},
},
{
diff --git a/plugins/web-ui/src/browser-errors.ts b/plugins/web-ui/src/browser-errors.ts
new file mode 100644
index 000000000..8a64c098b
--- /dev/null
+++ b/plugins/web-ui/src/browser-errors.ts
@@ -0,0 +1,126 @@
+import type { init, ErrorEvent, StackFrame } from "@sentry/browser";
+import type { Me } from "./shell-state";
+
+const ERROR_TYPES = new Set([
+ "Error",
+ "TypeError",
+ "RangeError",
+ "ReferenceError",
+ "SyntaxError",
+ "URIError",
+ "EvalError",
+ "AggregateError",
+ "UnhandledRejection",
+]);
+let client: ReturnType<typeof init>;
+let generation = 0;
+
+function safeFrame(frame: StackFrame, origin: string): StackFrame[] {
+ try {
+ const url = new URL(frame.filename ?? "", origin);
+ const filename = url.pathname.match(/\/assets\/([a-zA-Z0-9_-]{1,100}-[a-zA-Z0-9_-]{8}\.js)$/)?.[1];
+ if (url.origin !== origin || !filename) return [];
+ const position = (value: number | undefined) => (Number.isSafeInteger(value) && value! > 0 ? value : undefined);
+ return [{ filename, lineno: position(frame.lineno), colno: position(frame.colno), in_app: true }];
+ } catch {
+ return [];
+ }
+}
+
+export function sanitizeBrowserError(event: ErrorEvent, origin: string, release?: string): ErrorEvent {
+ const sanitized: ErrorEvent = {
+ type: undefined,
+ event_id: /^[a-f0-9]{32}$/.test(event.event_id ?? "") ? event.event_id : undefined,
+ timestamp: Number.isFinite(event.timestamp) ? event.timestamp : undefined,
+ platform: "javascript",
+ level: "error",
+ release,
+ tags: { service: "web-ui-browser" },
+ exception: {
+ values: (event.exception?.values?.slice(-5) ?? [{}]).map((exception) => ({
+ type: ERROR_TYPES.has(exception.type ?? "") ? exception.type : "Error",
+ value: "Browser error; details omitted",
+ stacktrace: {
+ frames: exception.stacktrace?.frames?.slice(-50).flatMap((frame) => safeFrame(frame, origin)) ?? [],
+ },
+ mechanism: {
+ handled: false,
+ type:
+ exception.mechanism?.type === "auto.browser.global_handlers.onunhandledrejection"
+ ? "onunhandledrejection"
+ : "onerror",
+ },
+ })),
+ },
+ };
+ sanitized.fingerprint = [
+ "web-ui-browser-v1",
+ ...(sanitized.exception?.values ?? []).flatMap((exception) => {
+ const frame = exception.stacktrace?.frames?.at(-1);
+ return [
+ exception.type ?? "Error",
+ exception.mechanism?.type ?? "onerror",
+ frame ? `${frame.filename}:${frame.lineno ?? 0}:${frame.colno ?? 0}` : "no-app-frame",
+ ];
+ }),
+ ];
+ return sanitized;
+}
+
+export function stopBrowserErrors(): void {
+ generation++;
+ if (client) client.getOptions().enabled = false;
+ client = undefined;
+}
+
+export async function initializeBrowserErrors(me: Me): Promise<void> {
+ stopBrowserErrors();
+ if (!me.browserErrors?.dsn || me.impersonatedBy) return;
+ const current = generation;
+ const { dsn, release } = me.browserErrors;
+ try {
+ const sdk = await import("@sentry/browser");
+ if (current !== generation) return;
+ const safeEvents = new WeakSet<ErrorEvent>();
+ client = sdk.init({
+ dsn,
+ release,
+ defaultIntegrations: false,
+ integrations: [sdk.globalHandlersIntegration()],
+ sendDefaultPii: false,
+ maxBreadcrumbs: 0,
+ attachStacktrace: true,
+ sendClientReports: false,
+ enableLogs: false,
+ tracesSampleRate: 0,
+ tracePropagationTargets: [],
+ transportOptions: { fetchOptions: { credentials: "omit", referrerPolicy: "no-referrer" } },
+ transport: (options) => {
+ const transport = sdk.makeFetchTransport(options);
+ return {
+ flush: (timeout) => transport.flush(timeout),
+ send: (envelope) => {
+ const [item] = envelope[1];
+ if (
+ current !== generation ||
+ envelope[1].length !== 1 ||
+ item?.[0].type !== "event" ||
+ !safeEvents.has(item[1] as ErrorEvent)
+ )
+ return Promise.resolve({});
+ return transport.send(envelope);
+ },
+ };
+ },
+ beforeSend: (event, hint) => {
+ if (current !== generation) return null;
+ hint.attachments = [];
+ const sanitized = sanitizeBrowserError(event, window.location.origin, release);
+ safeEvents.add(sanitized);
+ return sanitized;
+ },
+ });
+ } catch {
+ if (current === generation) client = undefined;
+ }
+}
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index cf974574e..3d6e9680d 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -1,4 +1,5 @@
-import { captureMessage } from "./product-analytics.ts";
+import { stopBrowserErrors } from "./browser-errors.ts";
+import { captureMessage, stopAnalytics } from "./product-analytics.ts";
import { streamedAnswer } from "./timeline.ts";
import { EventType } from "@tanstack/ai/client";
import { fetchServerSentEvents, StreamProcessor } from "@tanstack/ai-client";
@@ -675,6 +676,8 @@ export function reportSigninRequired(detail: SigninRequired): void {
export async function webFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const response = await fetch(input, init);
if (response.status !== 401) return response;
+ stopBrowserErrors();
+ stopAnalytics();
let body: unknown;
try {
body = await response.clone().json();
diff --git a/plugins/web-ui/src/shell-state.ts b/plugins/web-ui/src/shell-state.ts
index df6172484..8e2abeda3 100644
--- a/plugins/web-ui/src/shell-state.ts
+++ b/plugins/web-ui/src/shell-state.ts
@@ -3,6 +3,7 @@ import type { SuggestedActivity } from "../../chassis/src/suggested-activities.t
export type AuthMode = "portal" | "dev";
export interface Me {
+ browserErrors?: { dsn: string; release?: string };
analytics?: { apiKey: string; host: string };
companyName?: string | null;
welcomeCohort?: string;
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index 606576dd9..68330cd40 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -1,3 +1,4 @@
+import { initializeBrowserErrors, stopBrowserErrors } from "./browser-errors";
import { initializeAnalytics, capturePageview, stopAnalytics } from "./product-analytics";
import { captureConnectionReturn } from "./connection-return";
import { renderModelConnectGate } from "./model-connect";
@@ -223,6 +224,7 @@ const ICON = {
export async function signOut(): Promise<void> {
stopAnalytics();
+ stopBrowserErrors();
const portal = authMode === "portal";
if (!portal) {
try {
@@ -441,6 +443,7 @@ export type AuthGate =
export function renderAuthGate(gate: AuthGate): void {
stopAnalytics();
+ stopBrowserErrors();
shellMounted = false;
const body = (() => {
switch (gate.kind) {
@@ -1034,6 +1037,7 @@ export async function boot(): Promise<void> {
}
resetKeychainState();
appState.me = (await r.json()) as Me;
+ void initializeBrowserErrors(appState.me);
void initializeAnalytics(appState.me, isView(wanted) && canView(wanted) ? wanted : "chats");
authMode = appState.me.mode ?? "portal";
clearPortalAttempt();
diff --git a/plugins/web-ui/test/browser-error-routes.test.ts b/plugins/web-ui/test/browser-error-routes.test.ts
new file mode 100644
index 000000000..9d53305a1
--- /dev/null
+++ b/plugins/web-ui/test/browser-error-routes.test.ts
@@ -0,0 +1,55 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { mintPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../chassis/src/portal-identity.ts";
+
+let coreStatus = 200;
+const core = createServer((req, res) => {
+ res.writeHead(coreStatus, { "content-type": "application/json" });
+ res.end("{}");
+});
+await new Promise<void>((resolve) => core.listen(0, "127.0.0.1", resolve));
+const secret = "browser-error-route-test-secret";
+process.env.CORE_API_URL = `http://127.0.0.1:${(core.address() as AddressInfo).port}`;
+process.env.CORE_ORG_ID = "acme";
+process.env.CORE_SIGNING_SECRET = secret;
+process.env.PORTAL_IDENTITY_SECRET = secret;
+process.env.ALLOW_UNSIGNED_TEST_IDENTITY = "0";
+delete process.env.POSTHOG_API_KEY;
+process.env.SENTRY_BROWSER_DSN = "https://[email protected]/1";
+process.env.SENTRY_RELEASE = "release-1";
+const { handler } = await import("../server/index.ts");
+const surface = createServer((req, res) => void handler(req, res));
+await new Promise<void>((resolve) => surface.listen(0, "127.0.0.1", resolve));
+const base = `http://127.0.0.1:${(surface.address() as AddressInfo).port}`;
+const headers = (imp?: string) => ({
+ "content-type": "application/json",
+ [PORTAL_IDENTITY_HEADER]: mintPortalIdentity(
+ { p: "[email protected]", exp: Date.now() + 60_000, ...(imp ? { imp } : {}) },
+ secret,
+ ),
+});
+
+test.after(() => {
+ surface.closeAllConnections();
+ surface.close();
+ core.closeAllConnections();
+ core.close();
+});
+
+test("browser error config requires authentication and excludes impersonation", async () => {
+ assert.equal((await fetch(`${base}/me`)).status, 401);
+ const response = await fetch(`${base}/me`, { headers: headers() });
+ const body = await response.json();
+ assert.deepEqual(body.browserErrors, { dsn: "https://[email protected]/1", release: "release-1" });
+ const csp = (await fetch(`${base}/connectors/oauth/test/callback`)).headers.get("content-security-policy")!;
+ const directives = csp.split(";").map((directive) => directive.trim().split(/\s+/));
+ assert.deepEqual(
+ directives.find(([name]) => name === "connect-src"),
+ ["connect-src", "'self'", "https://sentry.example.com"],
+ );
+ assert.equal((await (await fetch(`${base}/me`, { headers: headers("admin") })).json()).browserErrors, undefined);
+ coreStatus = 503;
+ assert.equal((await fetch(`${base}/me`, { headers: headers() })).status, 503);
+});
diff --git a/plugins/web-ui/test/browser-errors.test.ts b/plugins/web-ui/test/browser-errors.test.ts
new file mode 100644
index 000000000..76c906948
--- /dev/null
+++ b/plugins/web-ui/test/browser-errors.test.ts
@@ -0,0 +1,173 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { sanitizeBrowserError, initializeBrowserErrors, stopBrowserErrors } from "../src/browser-errors.ts";
+import { browserErrorConfig } from "../server/browser-error-config.ts";
+import type { Me } from "../src/shell-state.ts";
+
+const origin = "https://app.example.com";
+
+test("browser errors discard content and retain only local asset stack positions", () => {
+ const event = sanitizeBrowserError(
+ {
+ type: undefined,
+ event_id: "a".repeat(32),
+ timestamp: 123,
+ message: "secret",
+ user: { email: "[email protected]" },
+ request: { url: `${origin}/s/secret`, headers: { authorization: "secret" } },
+ breadcrumbs: [{ message: "secret" }],
+ extra: { content: "secret" },
+ contexts: { trace: { trace_id: "secret", span_id: "secret" } },
+ tags: { secret: "secret" },
+ release: "secret",
+ exception: {
+ values: [
+ {
+ type: "TypeError",
+ value: "secret",
+ mechanism: { type: "auto.browser.global_handlers.onunhandledrejection", data: { secret: "secret" } },
+ stacktrace: {
+ frames: [
+ {
+ filename: `${origin}/web/assets/main-Abc12345.js?secret#secret`,
+ function: "secret",
+ lineno: 42,
+ colno: 8,
+ vars: { secret: "secret" },
+ pre_context: ["secret"],
+ },
+ { filename: "https://secret.example.com/assets/main-Abc12345.js", lineno: 2 },
+ { filename: `${origin}/s/secret`, lineno: 3 },
+ { filename: "data:secret", lineno: 4 },
+ { filename: `${origin}/assets/main-Abc12345.js`, lineno: -1, colno: Infinity },
+ ],
+ },
+ },
+ { type: "secret", value: "secret" },
+ ],
+ },
+ },
+ origin,
+ "release-1",
+ );
+ assert.equal(JSON.stringify(event).includes("secret"), false);
+ assert.equal(JSON.stringify(event).includes("https:"), false);
+ assert.equal(event.release, "release-1");
+ assert.deepEqual(event.tags, { service: "web-ui-browser" });
+ assert.equal(event.exception?.values?.[0]?.type, "TypeError");
+ assert.equal(event.exception?.values?.[1]?.type, "Error");
+ assert.deepEqual(event.exception?.values?.[0]?.stacktrace?.frames, [
+ { filename: "main-Abc12345.js", lineno: 42, colno: 8, in_app: true },
+ { filename: "main-Abc12345.js", lineno: undefined, colno: undefined, in_app: true },
+ ]);
+ assert.equal(event.exception?.values?.[0]?.mechanism?.type, "onunhandledrejection");
+});
+
+test("browser config is opt-in and does not expose a backend secret DSN", () => {
+ assert.equal(browserErrorConfig({ SENTRY_DSN: "https://public:[email protected]/1" }), undefined);
+ assert.deepEqual(
+ browserErrorConfig({ SENTRY_BROWSER_DSN: "https://[email protected]/1", GIT_SHA: "abc1234" }),
+ {
+ dsn: "https://[email protected]/1",
+ release: "abc1234",
+ },
+ );
+ for (const dsn of [
+ "broken",
+ "http://[email protected]/1",
+ "https://public:[email protected]/1",
+ "https://sentry.example.com/1",
+ "https://[email protected]/secret",
+ "https://[email protected]/1?secret",
+ "https://[email protected]/1#secret",
+ ])
+ assert.throws(() => browserErrorConfig({ SENTRY_BROWSER_DSN: dsn }), /public HTTPS DSN/);
+});
+
+test("disabled and impersonated reporting never requires a browser SDK", async () => {
+ await initializeBrowserErrors({} as Me);
+ await initializeBrowserErrors({
+ browserErrors: { dsn: "https://[email protected]/1" },
+ impersonatedBy: "admin",
+ } as Me);
+ stopBrowserErrors();
+});
+
+test("browser grouping separates minified locations without using private content", () => {
+ const makeEvent = (colno: number, secret = "secret", asset = "main-Abc12345.js") => ({
+ type: undefined,
+ fingerprint: [secret],
+ message: secret,
+ exception: {
+ values: [
+ {
+ type: "TypeError",
+ value: secret,
+ stacktrace: {
+ frames: [
+ { filename: `${origin}/assets/caller-Abc12345.js`, lineno: 1, colno: 12 },
+ { filename: `${origin}/assets/${asset}?${secret}`, lineno: 1, colno, function: secret },
+ { filename: `https://external.example.com/${secret}`, lineno: 1, colno: 99 },
+ ],
+ },
+ },
+ ],
+ },
+ });
+ const first = sanitizeBrowserError(makeEvent(100), origin, "release-1").fingerprint;
+ assert.deepEqual(first, ["web-ui-browser-v1", "TypeError", "onerror", "main-Abc12345.js:1:100"]);
+ assert.notDeepEqual(first, sanitizeBrowserError(makeEvent(101), origin, "release-1").fingerprint);
+ assert.deepEqual(
+ first,
+ sanitizeBrowserError(makeEvent(100, "other-private-content"), origin, "release-2").fingerprint,
+ );
+ assert.notDeepEqual(first, sanitizeBrowserError(makeEvent(100, "secret", "main-Def67890.js"), origin).fingerprint);
+ const fallback = sanitizeBrowserError(
+ { type: undefined, exception: { values: [{ type: "secret", value: "secret", mechanism: { type: "secret" } }] } },
+ origin,
+ ).fingerprint;
+ assert.deepEqual(fallback, ["web-ui-browser-v1", "Error", "onerror", "no-app-frame"]);
+});
+
+test("SDK processing failures cannot bypass browser event redaction", async () => {
+ const realFetch = globalThis.fetch;
+ const realWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
+ const sent: string[] = [];
+ globalThis.fetch = async (_input, init) => {
+ sent.push(String(init?.body));
+ return new Response("{}", { status: 200 });
+ };
+ Object.defineProperty(globalThis, "window", { configurable: true, value: { location: { origin } } });
+ try {
+ await initializeBrowserErrors({
+ user: "test",
+ org: "test",
+ browserErrors: { dsn: "https://[email protected]/1" },
+ });
+ const sdk = await import("@sentry/browser");
+ const client = sdk.getClient()!;
+ sdk.captureException(new Error("private original event"));
+ await sdk.flush(1000);
+ assert.equal(sent.length, 1);
+ assert.equal(sent[0]!.includes("private"), false);
+ const beforeSend = client.getOptions().beforeSend;
+ client.getOptions().beforeSend = () => {
+ throw new Error("private SDK failure");
+ };
+ sdk.captureException(new Error("private trigger"));
+ await sdk.flush(1000);
+ assert.equal(sent.length, 1);
+ client.getOptions().beforeSend = beforeSend;
+ client.addEventProcessor(() => {
+ throw new Error("private processor failure");
+ });
+ sdk.captureException(new Error("private processor trigger"));
+ await sdk.flush(1000);
+ assert.equal(sent.length, 1);
+ } finally {
+ stopBrowserErrors();
+ globalThis.fetch = realFetch;
+ if (realWindow) Object.defineProperty(globalThis, "window", realWindow);
+ else Reflect.deleteProperty(globalThis, "window");
+ }
+});
diff --git a/plugins/web-ui/test/product-analytics-routes.test.ts b/plugins/web-ui/test/product-analytics-routes.test.ts
index 6eeb5d544..cf74a8631 100644
--- a/plugins/web-ui/test/product-analytics-routes.test.ts
+++ b/plugins/web-ui/test/product-analytics-routes.test.ts
@@ -5,7 +5,13 @@ import type { AddressInfo } from "node:net";
import { mintPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../chassis/src/portal-identity.ts";
let coreStatus = 200;
-const core = createServer((req, res) => {
+const turns: Record<string, unknown>[] = [];
+const core = createServer(async (req, res) => {
+ if (req.url?.startsWith("/v1/turns")) {
+ let body = "";
+ for await (const chunk of req) body += chunk;
+ turns.push(JSON.parse(body));
+ }
res.writeHead(coreStatus, { "content-type": "application/json" });
if (req.url?.startsWith("/v1/approvals/approval-1?")) {
res.end(
@@ -60,3 +66,20 @@ test("analytics config is authenticated, company-scoped and omitted during imper
coreStatus = 503;
assert.equal((await fetch(`${base}/me`, { headers: headers() })).status, 503);
});
+
+test("authenticated impersonation suppresses analytics on turns and approval replay", async () => {
+ coreStatus = 200;
+ for (const impersonator of [undefined, "admin"]) {
+ for (const path of ["/api/turn", "/api/approvals/approval-1"]) {
+ const response = await fetch(`${base}${path}`, {
+ method: "POST",
+ headers: headers(impersonator),
+ body: JSON.stringify({ text: "test turn", approved: true, analyticsSuppressed: false }),
+ });
+ assert.equal(response.status, 200);
+ const turn = turns.at(-1)!;
+ assert.equal(turn.analyticsSuppressed, impersonator ? true : undefined);
+ assert.equal(JSON.stringify(turn).includes("admin"), false);
+ }
+ }
+});
diff --git a/plugins/web-ui/test/signin-return.test.ts b/plugins/web-ui/test/signin-return.test.ts
index 6bb546c54..a9d5a741c 100644
--- a/plugins/web-ui/test/signin-return.test.ts
+++ b/plugins/web-ui/test/signin-return.test.ts
@@ -1,6 +1,8 @@
import assert from "node:assert/strict";
import { afterEach, test } from "node:test";
import { JSDOM } from "jsdom";
+import { getClient } from "@sentry/browser";
+import { initializeBrowserErrors, stopBrowserErrors } from "../src/browser-errors.ts";
import { webFetch } from "../src/core-bridge.ts";
import { currentInAppLocation, SIGNIN_REQUIRED_EVENT, signinRedirect } from "../src/signin-return.ts";
@@ -30,6 +32,7 @@ const realWindow = globalThis.window;
const realEvent = globalThis.Event;
afterEach(() => {
+ stopBrowserErrors();
globalThis.fetch = realFetch;
Object.defineProperty(globalThis, "window", { configurable: true, writable: true, value: realWindow });
Object.defineProperty(globalThis, "Event", { configurable: true, writable: true, value: realEvent });
@@ -58,7 +61,15 @@ test("webFetch redirects a 401 through the same-origin sign-in endpoint", async
target.addEventListener(SIGNIN_REQUIRED_EVENT, () => signinRequired++);
globalThis.fetch = async () => Response.json({ loginUrl: "/auth/login" }, { status: 401 });
+ await initializeBrowserErrors({
+ user: "test",
+ org: "test",
+ browserErrors: { dsn: "https://[email protected]/1" },
+ });
+ const client = getClient()!;
+ assert.notEqual(client.getOptions().enabled, false);
const response = await webFetch("/api/me");
+ assert.equal(client.getOptions().enabled === false, response.status === 401);
assert.equal(response.status, 401);
assert.deepEqual(assigned, ["/auth/login?returnTo=%2Fcrons%2Fjob-1%3Ftab%3Druns%23output"]);
@@ -71,7 +82,15 @@ test("webFetch dispatches the sign-in fallback for an unusable 401 body", async
target.addEventListener(SIGNIN_REQUIRED_EVENT, () => signinRequired++);
globalThis.fetch = async () => new Response("not json", { status: 401 });
+ await initializeBrowserErrors({
+ user: "test",
+ org: "test",
+ browserErrors: { dsn: "https://[email protected]/1" },
+ });
+ const client = getClient()!;
+ assert.notEqual(client.getOptions().enabled, false);
const response = await webFetch("/api/me");
+ assert.equal(client.getOptions().enabled === false, response.status === 401);
assert.equal(response.status, 401);
assert.deepEqual(assigned, []);
@@ -84,7 +103,15 @@ test("webFetch leaves non-401 responses alone", async () => {
target.addEventListener(SIGNIN_REQUIRED_EVENT, () => signinRequired++);
globalThis.fetch = async () => Response.json({ error: "forbidden" }, { status: 403 });
+ await initializeBrowserErrors({
+ user: "test",
+ org: "test",
+ browserErrors: { dsn: "https://[email protected]/1" },
+ });
+ const client = getClient()!;
+ assert.notEqual(client.getOptions().enabled, false);
const response = await webFetch("/api/me");
+ assert.equal(client.getOptions().enabled === false, response.status === 401);
assert.equal(response.status, 403);
assert.deepEqual(assigned, []);
diff --git a/src/api/app-turn.ts b/src/api/app-turn.ts
index 240011376..f58e3ff98 100644
--- a/src/api/app-turn.ts
+++ b/src/api/app-turn.ts
@@ -295,6 +295,9 @@ export function createTurnMethods(
text: req.text,
...(req.gatewayContext ? { gatewayContext: req.gatewayContext } : {}),
...(req.proactiveOpener ? { proactiveOpener: true } : {}),
+ ...(req.analyticsSuppressed || (sameApprovedMessage && approvedRequest?.analyticsSuppressed)
+ ? { analyticsSuppressed: true }
+ : {}),
...(req.conversationHeader ? { conversationHeader: req.conversationHeader } : {}),
...(req.priorTurns?.length ? { priorTurns: req.priorTurns } : {}),
...(req.overheard?.length ? { overheard: req.overheard } : {}),
diff --git a/src/core/orchestrator/turn-helpers.ts b/src/core/orchestrator/turn-helpers.ts
index 8863b6082..f5c3570f6 100644
--- a/src/core/orchestrator/turn-helpers.ts
+++ b/src/core/orchestrator/turn-helpers.ts
@@ -249,6 +249,8 @@ export function replayableRequest(input: OrchestratorInput): TurnRequest {
},
text: input.text,
...(input.gatewayContext ? { gatewayContext: input.gatewayContext } : {}),
+ ...(input.analyticsSuppressed ? { analyticsSuppressed: true } : {}),
+ ...(input.proactiveOpener ? { proactiveOpener: true } : {}),
...turnOriginRequestFields(input.origin),
...(input.conversationHeader ? { conversationHeader: input.conversationHeader } : {}),
...(input.priorTurns?.length ? { priorTurns: input.priorTurns } : {}),
diff --git a/src/types.ts b/src/types.ts
index 08b977b13..0805d271c 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -642,6 +642,7 @@ export interface TurnRequest {
clientSentAt?: number;
approval?: { requestId: string; approved: boolean; scope?: ApprovalScope };
proactiveOpener?: boolean;
+ analyticsSuppressed?: boolean;
spawned?: boolean;
idempotencyKey?: string;
redeliveryKey?: string;
diff --git a/src/util/product-analytics.ts b/src/util/product-analytics.ts
index 8cc82538f..6e7453616 100644
--- a/src/util/product-analytics.ts
+++ b/src/util/product-analytics.ts
@@ -1,41 +1,76 @@
+import { resolveTurnOrigin } from "../core/turn-origin.ts";
+import type { Run } from "../runs/run-store.ts";
+
export function createProductAnalytics(
companyId: string,
config: { apiKey?: string; host?: string } = {},
send: typeof fetch = fetch,
-): { appPublished(principal: string, deploymentId: string, version: number): Promise<void> } {
+): {
+ appPublished(principal: string, deploymentId: string, version: number): Promise<void>;
+ responseFinished(run: Run): Promise<void>;
+} {
const apiKey = config.apiKey?.trim();
const host = (config.host?.trim() || "https://us.i.posthog.com").replace(/\/$/, "");
let inFlight = 0;
+ async function capture(
+ event: string,
+ principal: string,
+ insertId: string,
+ properties: Record<string, string> = {},
+ ): Promise<void> {
+ if (!apiKey || !companyId || !principal || inFlight >= 16) return;
+ inFlight++;
+ try {
+ const response = await send(`${host}/i/v0/e/`, {
+ method: "POST",
+ redirect: "error",
+ signal: AbortSignal.timeout(2_000),
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ api_key: apiKey,
+ event,
+ timestamp: new Date().toISOString(),
+ properties: {
+ distinct_id: JSON.stringify([companyId, principal]),
+ company_id: companyId,
+ $groups: { company: companyId },
+ $insert_id: insertId,
+ $geoip_disable: true,
+ surface: "core",
+ ...properties,
+ },
+ }),
+ });
+ await response.body?.cancel();
+ } catch {
+ return;
+ } finally {
+ inFlight--;
+ }
+ }
return {
- async appPublished(principal, deploymentId, version) {
- if (!apiKey || !companyId || !principal || inFlight >= 16) return;
- inFlight++;
- try {
- const response = await send(`${host}/i/v0/e/`, {
- method: "POST",
- redirect: "error",
- signal: AbortSignal.timeout(2_000),
- headers: { "content-type": "application/json" },
- body: JSON.stringify({
- api_key: apiKey,
- event: "app_published",
- timestamp: new Date().toISOString(),
- properties: {
- distinct_id: JSON.stringify([companyId, principal]),
- company_id: companyId,
- $groups: { company: companyId },
- $insert_id: `${deploymentId}:${version}:app_published`,
- $geoip_disable: true,
- surface: "core",
- },
- }),
- });
- await response.body?.cancel();
- } catch {
+ appPublished: (principal, deploymentId, version) =>
+ capture("app_published", principal, `${deploymentId}:${version}:app_published`),
+ async responseFinished(run) {
+ if (
+ resolveTurnOrigin(run.request).kind !== "human" ||
+ run.request.botActor ||
+ run.request.analyticsSuppressed ||
+ run.request.proactiveOpener ||
+ run.result?.stopped ||
+ (run.status !== "done" && run.status !== "failed")
+ )
return;
- } finally {
- inFlight--;
- }
+ const status = run.result?.status;
+ let event: string | undefined;
+ if (run.status === "failed" || status === "failed") event = "response_failed";
+ else if (status === "ok" || status === "silent" || status === "react") event = "response_completed";
+ if (!event) return;
+ await capture(event, run.request.actor.id, `${companyId}:${run.id}:${event}`, {
+ surface: run.request.surface === "web" || run.request.surface === "slack" ? run.request.surface : "core",
+ completion_boundary: "run",
+ result_status: status ?? "failed",
+ });
},
};
}
diff --git a/src/wiring.ts b/src/wiring.ts
index 1a6599316..8395a02b4 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1457,6 +1457,10 @@ export function buildApp(
},
})
: undefined;
+ const productAnalytics = createProductAnalytics(config.orgId, config.productAnalytics);
+ runs.onTerminal((run) => {
+ void productAnalytics.responseFinished(run);
+ });
const ledger = runStore.ledger;
let processes: ProcessRegistry | undefined;
@@ -1607,7 +1611,7 @@ export function buildApp(
const deployGitSecret = config.signingSecret;
const deployGitBase = config.apiBaseUrl;
const deployService = createDeployService({
- appPublished: createProductAnalytics(config.orgId, config.productAnalytics).appPublished,
+ appPublished: productAnalytics.appPublished,
deployStore,
provider: deployProvider,
deployDir: join(config.dataDir, "deployments"),
diff --git a/test/product-analytics.test.ts b/test/product-analytics.test.ts
index 74a49641c..1ae630004 100644
--- a/test/product-analytics.test.ts
+++ b/test/product-analytics.test.ts
@@ -1,5 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
+import { createMemoryRunStore } from "../src/runs/memory-run-store.ts";
+import type { Run } from "../src/runs/run-store.ts";
import { createProductAnalytics } from "../src/util/product-analytics.ts";
test("disabled analytics makes no requests", async () => {
@@ -9,6 +11,7 @@ test("disabled analytics makes no requests", async () => {
return new Response("ok");
});
await analytics.appPublished("person", "app", 1);
+ await analytics.responseFinished(await humanRun());
assert.equal(requests, 0);
});
@@ -36,6 +39,7 @@ test("delivery failures cannot fail publication and concurrent requests are boun
throw Error("offline");
});
await assert.doesNotReject(failing.appPublished("person", "app", 1));
+ await assert.doesNotReject(failing.responseFinished(await humanRun()));
const releases: Array<() => void> = [];
const bounded = createProductAnalytics("company", { apiKey: "token" }, async () => {
await new Promise<void>((resolve) => releases.push(resolve));
@@ -46,3 +50,104 @@ test("delivery failures cannot fail publication and concurrent requests are boun
releases.forEach((release) => release());
await Promise.all(requests);
});
+
+test("human run outcomes keep identity and deduplication without response content", async () => {
+ const bodies: Record<string, any>[] = [];
+ const analytics = createProductAnalytics("company", { apiKey: "token" }, async (_url, init) => {
+ bodies.push(JSON.parse(String(init?.body)));
+ return new Response("ok");
+ });
+ const run = await humanRun();
+ for (const status of ["ok", "silent", "react", "failed"] as const) {
+ run.result = { status, reply: "private reply", reason: "secret error https://private.test" };
+ await analytics.responseFinished(run);
+ }
+ await analytics.responseFinished(run);
+ assert.deepEqual(
+ bodies.map((body) => body.event),
+ ["response_completed", "response_completed", "response_completed", "response_failed", "response_failed"],
+ );
+ assert.equal(bodies[3]!.properties.$insert_id, bodies[4]!.properties.$insert_id);
+ assert.equal(bodies[0]!.properties.$insert_id, `company:${run.id}:response_completed`);
+ assert.deepEqual(bodies[0]!.properties, {
+ distinct_id: JSON.stringify(["company", "person"]),
+ company_id: "company",
+ $groups: { company: "company" },
+ $insert_id: `company:${run.id}:response_completed`,
+ $geoip_disable: true,
+ surface: "web",
+ completion_boundary: "run",
+ result_status: "ok",
+ });
+ assert.doesNotMatch(JSON.stringify(bodies), /private|secret/);
+});
+
+test("non-human, stopped and non-completion results do not produce response outcomes", async () => {
+ let requests = 0;
+ const analytics = createProductAnalytics("company", { apiKey: "token" }, async () => {
+ requests++;
+ return new Response("ok");
+ });
+ const run = await humanRun();
+ for (const kind of ["automation", "ambient", "direct"] as const) {
+ await analytics.responseFinished({ ...run, request: { ...run.request, origin: { kind } } });
+ }
+ await analytics.responseFinished({ ...run, request: { ...run.request, botActor: true } });
+ for (const flag of ["analyticsSuppressed", "proactiveOpener"] as const) {
+ for (const status of ["ok", "failed"] as const) {
+ await analytics.responseFinished({ ...run, request: { ...run.request, [flag]: true }, result: { status } });
+ }
+ }
+ for (const status of ["queued", "pending_approval", "refused"] as const) {
+ await analytics.responseFinished({ ...run, result: { status } });
+ }
+ for (const status of ["ok", "silent", "failed"] as const) {
+ await analytics.responseFinished({ ...run, result: { status, stopped: true } });
+ }
+ for (const status of ["pending", "running"] as const) {
+ await analytics.responseFinished({ ...run, status });
+ }
+ await analytics.responseFinished({ ...run, result: null });
+ assert.equal(requests, 0);
+});
+
+test("terminal listener reports only exhausted failures and accepted completions, not retries or stale leases", async () => {
+ const events: string[] = [];
+ const analytics = createProductAnalytics("company", { apiKey: "token" }, async (_url, init) => {
+ events.push(JSON.parse(String(init?.body)).event);
+ return new Response("ok");
+ });
+ const { runs } = createMemoryRunStore();
+ runs.onTerminal((run) => {
+ void analytics.responseFinished(run);
+ });
+ const request = (await humanRun()).request;
+ const { run } = await runs.enqueue({ sessionId: "thread", request, maxAttempts: 2 });
+ let claimed = (await runs.claim("worker", 10_000))!;
+ await runs.fail(run.id, claimed.leaseToken!, "private first error");
+ assert.deepEqual(events, []);
+ claimed = (await runs.claim("worker", 10_000))!;
+ assert.equal(await runs.complete(run.id, "stale-lease", { status: "ok" }), false);
+ assert.deepEqual(events, []);
+ await runs.fail(run.id, claimed.leaseToken!, "private final error");
+ assert.deepEqual(events, ["response_failed"]);
+ await runs.enqueue({ sessionId: "thread", request });
+ claimed = (await runs.claim("worker", 10_000))!;
+ await runs.complete(claimed.id, claimed.leaseToken!, { status: "ok" });
+ assert.deepEqual(events, ["response_failed", "response_completed"]);
+});
+
+async function humanRun(): Promise<Run> {
+ const { runs } = createMemoryRunStore();
+ const { run } = await runs.enqueue({
+ sessionId: "thread",
+ request: {
+ actor: { id: "person", type: "internal" },
+ conversation: { kind: "dm", threadRef: "thread", audience: [] },
+ origin: { kind: "human" },
+ surface: "web",
+ text: "private prompt",
+ },
+ });
+ return { ...run, status: "done", result: { status: "ok" }, finishedAt: Date.now() };
+}
diff --git a/test/worker-reaper.test.ts b/test/worker-reaper.test.ts
index ecd94ea7a..537d82042 100644
--- a/test/worker-reaper.test.ts
+++ b/test/worker-reaper.test.ts
@@ -14,6 +14,7 @@ import { buildApp } from "../src/wiring.ts";
import type { LeaderLease } from "../src/persistence/leader-lease.ts";
import type { OrchestratorInput } from "../src/core/orchestrator.ts";
import type { Principal } from "../src/types.ts";
+import { replayableRequest } from "../src/core/orchestrator/turn-helpers.ts";
import { testConfig } from "./support/test-config.ts";
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
@@ -776,3 +777,55 @@ test("final shutdown bounds tracked worker drain without claiming ownership is d
await built.runtime.backgroundDrained();
}
});
+
+test("buildApp captures human run outcomes through the shared terminal hook", async (t) => {
+ const events: string[] = [];
+ t.mock.method(globalThis, "fetch", async (_url: string, init: RequestInit) => {
+ events.push(JSON.parse(String(init.body)).event);
+ return new Response("ok");
+ });
+ const built = buildApp(testConfig({ productAnalytics: { apiKey: "test-token" } }));
+ try {
+ const request: OrchestratorInput = { ...turn, origin: { kind: "human" }, surface: "slack" };
+ for (const result of [{ status: "ok" }, { status: "failed" }, { status: "ok", stopped: true }] as const) {
+ await built.runs.enqueue({ sessionId: "t1", request });
+ const run = (await built.runs.claim("worker", 10_000))!;
+ await built.runs.complete(run.id, run.leaseToken!, result);
+ }
+ assert.deepEqual(events, ["response_completed", "response_failed"]);
+ } finally {
+ await built.runtime.stop();
+ }
+});
+
+test("web admission and replay preserve analytics exclusions", async (t) => {
+ const events: string[] = [];
+ t.mock.method(globalThis, "fetch", async (_url: string, init: RequestInit) => {
+ events.push(JSON.parse(String(init.body)).event);
+ return new Response("ok");
+ });
+ const built = buildApp(testConfig({ productAnalytics: { apiKey: "test-token" } }));
+ try {
+ for (const flag of ["analyticsSuppressed", "proactiveOpener"] as const) {
+ for (const status of ["ok", "failed"] as const) {
+ const admitted = await built.app.turn({
+ surface: "web",
+ actor: { externalId: "U1" },
+ conversation: { kind: "dm", threadRef: `excluded-${flag}-${status}` },
+ text: "test message",
+ liveActor: true,
+ async: true,
+ [flag]: true,
+ });
+ assert.ok(admitted.runId);
+ const run = (await built.runs.claimById(admitted.runId, "worker", 10_000))!;
+ assert.equal(run.request[flag], true);
+ assert.equal(replayableRequest(run.request)[flag], true);
+ await built.runs.complete(run.id, run.leaseToken!, { status });
+ }
+ }
+ assert.deepEqual(events, []);
+ } finally {
+ await built.runtime.stop();
+ }
+});