Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): give a codex turn one trace id (#105852)

Vojta Bartošd6ae6a9ea782
diff --git a/products/desktop/packages/agent/src/acp-extensions.test.ts b/products/desktop/packages/agent/src/acp-extensions.test.ts
index ce6457c7c9f4..d2f56944339b 100644
--- a/products/desktop/packages/agent/src/acp-extensions.test.ts
+++ b/products/desktop/packages/agent/src/acp-extensions.test.ts
@@ -4,6 +4,7 @@ import {
isNotification,
POSTHOG_METHODS,
POSTHOG_NOTIFICATIONS,
+ withTurnTraceId,
} from "./acp-extensions";
describe("isNotification", () => {
@@ -70,3 +71,50 @@ describe("isMethod", () => {
expect(isMethod(undefined, POSTHOG_METHODS.REFRESH_SESSION)).toBe(false);
});
});
+
+describe("withTurnTraceId", () => {
+ // A codex turn reports no trace id of its own, so the stamped run id is the
+ // only thing a rating on it can open.
+ it.each([
+ [
+ "names the stamped run on a turn that reports none",
+ { params: { sessionId: "s", stopReason: "end_turn" } },
+ "run-1",
+ "run-1",
+ ],
+ [
+ "keeps the trace id the adapter reported",
+ { params: { sessionId: "s", traceId: "trace-abc" } },
+ "run-1",
+ "trace-abc",
+ ],
+ [
+ "names nothing when no header stamped the run",
+ { params: { sessionId: "s" } },
+ null,
+ undefined,
+ ],
+ ])("%s", (_name, message, stamped, expected) => {
+ const result = withTurnTraceId(
+ {
+ jsonrpc: "2.0",
+ method: POSTHOG_NOTIFICATIONS.TURN_COMPLETE,
+ ...message,
+ },
+ stamped,
+ ) as { params: { traceId?: string; sessionId: string } };
+
+ expect(result.params.traceId).toBe(expected);
+ expect(result.params.sessionId).toBe("s");
+ });
+
+ it("leaves a notification of another kind alone", () => {
+ const message = {
+ jsonrpc: "2.0",
+ method: POSTHOG_NOTIFICATIONS.TASK_COMPLETE,
+ params: { sessionId: "s" },
+ };
+
+ expect(withTurnTraceId(message, "run-1")).toBe(message);
+ });
+});
diff --git a/products/desktop/packages/agent/src/acp-extensions.ts b/products/desktop/packages/agent/src/acp-extensions.ts
index 9162b2616604..e4e3d22bdf13 100644
--- a/products/desktop/packages/agent/src/acp-extensions.ts
+++ b/products/desktop/packages/agent/src/acp-extensions.ts
@@ -190,3 +190,33 @@ export function isMethod(
): boolean {
return matchesExt(method, expected);
}
+
+/**
+ * Names `traceId` on a turn-complete notification that reports none.
+ *
+ * The codex adapter mints this notification itself and reports no trace id, so
+ * a rating on the turn has nothing to open. The gateway groups the run's
+ * generations under the run id, which makes that id the turn's trace.
+ */
+export function withTurnTraceId(
+ message: Record<string, unknown>,
+ traceId: string | null | undefined,
+): Record<string, unknown> {
+ if (
+ !traceId ||
+ !isNotification(
+ message.method as string | undefined,
+ POSTHOG_NOTIFICATIONS.TURN_COMPLETE,
+ )
+ ) {
+ return message;
+ }
+ const params = message.params;
+ if (typeof params !== "object" || params === null) {
+ return message;
+ }
+ if (typeof (params as { traceId?: unknown }).traceId === "string") {
+ return message;
+ }
+ return { ...message, params: { ...params, traceId } };
+}
diff --git a/products/desktop/packages/agent/src/adapters/acp-connection.ts b/products/desktop/packages/agent/src/adapters/acp-connection.ts
index 4140f8b0afbc..1331379bae8b 100644
--- a/products/desktop/packages/agent/src/adapters/acp-connection.ts
+++ b/products/desktop/packages/agent/src/adapters/acp-connection.ts
@@ -1,6 +1,7 @@
import { AgentSideConnection, ndJsonStream } from "@agentclientprotocol/sdk";
import type { ContextWikiEnv } from "@posthog/harness/extensions/context-wiki";
import type { Adapter } from "@posthog/shared";
+import { withTurnTraceId } from "../acp-extensions";
import type { ModelInfo } from "../gateway-models";
import type { SessionLogWriter } from "../session-log-writer";
import type { PostHogAPIConfig, ProcessSpawnedCallback } from "../types";
@@ -23,6 +24,8 @@ export type AcpConnectionConfig = {
logWriter?: SessionLogWriter;
/** Receives every parsed ACP wire message with the event id the session log stored it under. */
onWireMessage?: (message: Record<string, unknown>, eventId: string) => void;
+ /** Gateway trace id the run's headers stamped, for a turn that reports none. */
+ stampedRunTraceId?: string | null;
/** Shared id source so wire events and server-born events stay on one sequence. */
eventIdSource?: NextEventId;
taskRunId?: string;
@@ -124,8 +127,11 @@ function installWireTaps(
return;
}
const eventId = nextEventId();
- logWriter.appendNotification(taskRunId, message, eventId);
- config.onWireMessage?.(message, eventId);
+ // Named before the log stores the event, because a reload of the thread
+ // reads the stored copy rather than the broadcast one.
+ const stamped = withTurnTraceId(message, config.stampedRunTraceId);
+ logWriter.appendNotification(taskRunId, stamped, eventId);
+ config.onWireMessage?.(stamped, eventId);
};
return {
diff --git a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts
index d2da7a051541..7017b114d2d3 100644
--- a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts
@@ -610,6 +610,27 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {
expect(env.anthropicCustomHeaders).not.toContain("X-PostHog-Service-Tier");
});
+ // The header outranks `traceparent`, so giving it to Claude would replace the
+ // per-turn ids its CLI mints with one id for the whole run.
+ it("names the run as X-PostHog-Trace-Id for codex only", () => {
+ const codex = buildServer().configureEnvironment({
+ originProduct: "signal_report",
+ aiStage: "scout",
+ taskRunId: "run-1",
+ runtimeAdapter: "codex",
+ });
+ const claude = buildServer().configureEnvironment({
+ originProduct: "signal_report",
+ aiStage: "scout",
+ taskRunId: "run-1",
+ runtimeAdapter: "claude",
+ });
+
+ expect(codex.openaiCustomHeaders?.["X-PostHog-Trace-Id"]).toBe("run-1");
+ expect(codex.anthropicCustomHeaders).not.toContain("X-PostHog-Trace-Id");
+ expect(claude.openaiCustomHeaders?.["X-PostHog-Trace-Id"]).toBeUndefined();
+ });
+
it("keeps non-signals products on their existing ai_product name", () => {
const env = buildServer().configureEnvironment({ isInternal: true });
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 7441e4c2ae44..1d07bdb0a26f 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -509,6 +509,7 @@ export class AgentServer {
private runUsage = new RunUsageAccumulator();
private runUsageRunId: string | null = null;
private detectedPrUrl: string | null = null;
+ private stampedRunTraceId: string | null = null;
private slackArtifactDelivery: SlackArtifactDelivery | null = null;
private slackChartDelivery = false;
private slackReplyContext = false;
@@ -1569,7 +1570,7 @@ export class AgentServer {
}
this.recordTurnUsage(result.usage);
- const turnTraceId = this.promptResultTraceId(result);
+ const turnTraceId = this.turnTraceId(result);
this.broadcastTurnComplete(result.stopReason, turnTraceId);
if (result.stopReason === "end_turn") {
@@ -2025,6 +2026,11 @@ export class AgentServer {
executionEnvironment: "cloud",
});
+ // Only that stamped header makes the run id a trace the generations land
+ // in. Unconditional so a re-init on this instance drops a stale run's id.
+ this.stampedRunTraceId =
+ gatewayEnv.openaiCustomHeaders?.["X-PostHog-Trace-Id"] ?? null;
+
if (this.config.repoReadyFile && gatewayEnv.anthropicBaseUrl) {
// Authed so this cache-warm matches the session's own authed fetch
// (the models cache is keyed on auth presence).
@@ -2137,6 +2143,7 @@ export class AgentServer {
eventIdSource: this.nextEventId,
onWireMessage: (message, eventId) =>
this.handleAcpTransportMessage(message, eventId),
+ stampedRunTraceId: this.stampedRunTraceId,
logger: this.logger,
claudeGatewayEnv:
runtimeAdapter !== "codex" && claudeSubscriptionToken === null
@@ -2956,7 +2963,7 @@ export class AgentServer {
}
this.recordTurnUsage(result.usage);
- const turnTraceId = this.promptResultTraceId(result);
+ const turnTraceId = this.turnTraceId(result);
this.broadcastTurnComplete(result.stopReason, turnTraceId);
if (result.stopReason === "end_turn") {
@@ -3352,7 +3359,7 @@ export class AgentServer {
}
this.recordTurnUsage(result.usage);
- const turnTraceId = this.promptResultTraceId(result);
+ const turnTraceId = this.turnTraceId(result);
this.broadcastTurnComplete(result.stopReason, turnTraceId);
if (result.stopReason === "end_turn") {
@@ -4790,6 +4797,13 @@ export class AgentServer {
if (this.config.serviceTier) {
openaiCustomHeaders["X-PostHog-Service-Tier"] = this.config.serviceTier;
}
+ // Codex sends no trace header, so the gateway stamps a fresh id per
+ // request and a run's generations each land in a trace of one. Codex-only:
+ // this header outranks `traceparent`, so setting it for Claude would
+ // replace the per-turn ids its CLI mints with one id for the whole run.
+ if (taskRunId && runtimeAdapter === "codex") {
+ openaiCustomHeaders["X-PostHog-Trace-Id"] = taskRunId;
+ }
} else {
customHeaders = buildPosthogScopedPropertyHeaderLines(
gatewayProperties,
@@ -5606,11 +5620,12 @@ export class AgentServer {
this.broadcastEvent(event);
}
- /** The per-turn gateway trace id the Claude adapter reports via `PromptResponse._meta`. */
- private promptResultTraceId(result: PromptResponse): string | null {
+ /** The turn's gateway trace id: the one the Claude adapter reports via
+ * `PromptResponse._meta`, else the run id the codex headers stamped. */
+ private turnTraceId(result: PromptResponse): string | null {
const traceId = (result._meta as { traceId?: unknown } | undefined)
?.traceId;
- return typeof traceId === "string" ? traceId : null;
+ return typeof traceId === "string" ? traceId : this.stampedRunTraceId;
}
private broadcastTurnComplete(