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.

feat(posthog-ai): relay gateway trace ids to sandbox feedback (#90659)

Jake Ruth5918b2ab74a8
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index bc6d5ac311dc..8443d1613624 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -161,7 +161,7 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
sessionId={feedbackTaskId}
turnIndex={trailer.turnIndex}
run={feedbackRun}
- isLastTurn={trailer.isLastTurn}
+ traceId={trailer.traceId}
turnText={trailer.turnText}
/>
) : null,
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
index 3f7ade76a2e9..050039b14ffa 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
@@ -149,6 +149,7 @@ import {
toSdkEffort,
} from "./session/options";
import { SettingsManager } from "./session/settings";
+import { generateTraceparentHookNonce } from "./session/traceparent-hook";
import {
buildSideQuestionPrompt,
collectSideQuestionAnswer,
@@ -969,7 +970,27 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
session.turnQueue = session.turnQueue.filter((t) => t !== turn);
session.activeTurn = null;
this.dispatchQueuedInput(session);
- turn.resolve(result);
+ // Attach the turn's gateway trace id (from the traceparent hook) so the
+ // server can stamp it on `_posthog/turn_complete`. Cleared here so a
+ // turn whose hook never fired cannot inherit the previous turn's id.
+ const traceId = session.currentTurnTraceId;
+ session.currentTurnTraceId = undefined;
+ if (
+ !traceId &&
+ session.traceparentHookInstalled &&
+ !turn.isLocalOnlyCommand
+ ) {
+ // Loud on purpose: an SDK or CLI change that stops surfacing hook
+ // output would otherwise degrade feedback attribution silently.
+ this.logger.warn("Gateway turn settled without a trace id", {
+ sessionId: session.sdkSessionId,
+ });
+ }
+ turn.resolve(
+ traceId
+ ? { ...result, _meta: { ...(result._meta ?? {}), traceId } }
+ : result,
+ );
};
// Reject the active turn without tearing down the consumer.
@@ -986,6 +1007,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
declinePendingSteers(turn, "turn_failed");
session.turnQueue = session.turnQueue.filter((t) => t !== turn);
session.activeTurn = null;
+ session.currentTurnTraceId = undefined;
this.toolUseStreamCache.clear();
this.dispatchQueuedInput(session);
turn.reject(error);
@@ -1005,6 +1027,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
: [...session.turnQueue];
session.activeTurn = null;
session.turnQueue = [];
+ session.currentTurnTraceId = undefined;
this.toolUseStreamCache.clear();
for (const turn of turns) {
if (!turn.settled) {
@@ -2794,6 +2817,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
);
const taskState: TaskState = new Map();
+ const traceparentHookNonce = generateTraceparentHookNonce();
const options = buildSessionOptions({
cwd,
mcpServers,
@@ -2804,6 +2828,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
systemPrompt,
userProvidedOptions: meta?.claudeCode?.options,
sessionId,
+ taskId: resolveTaskId(meta),
isResume,
forkSession,
additionalDirectories: [
@@ -2829,6 +2854,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
taskState,
getCurrentModelId: () => this.session?.modelId,
gatewayEnv: this.options?.gatewayEnv,
+ traceparentHookNonce,
machineAuth: this.options?.machineAuth,
bedrockGatewayVariant,
contextWiki: this.options?.contextWiki,
@@ -2882,6 +2908,10 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
rules: estimateRulesTokens(readClaudeMdQuietly(cwd, this.logger)),
},
taskState,
+ traceparentHookNonce,
+ traceparentHookInstalled:
+ typeof options.extraArgs?.settings === "string" &&
+ options.extraArgs.settings.includes(traceparentHookNonce),
// Custom properties
cwd,
diff --git a/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.ts b/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.ts
index 75c128ecca9c..c17b6bc7acbb 100644
--- a/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.ts
@@ -29,6 +29,7 @@ import type { Logger } from "../../../utils/logger";
import { tryParsePartialJson } from "../../../utils/partial-json";
import { classifyAgentError } from "../../error-classification";
import { type EnrichedReadCache, registerHookCallback } from "../hooks";
+import { traceIdFromHookStderr } from "../session/traceparent-hook";
import type {
Session,
ToolUpdateMeta,
@@ -735,12 +736,28 @@ export async function handleSystemMessage(
contextSize: session.contextSize,
});
break;
- case "hook_response":
- logger.info("Hook response received", {
+ case "hook_response": {
+ // The traceparent hook reports the running turn's trace id on stderr —
+ // the same id the LLM gateway stamps on the turn's $ai_generation
+ // events. The session nonce keeps other UserPromptSubmit hooks (user or
+ // repo settings) from colliding with this channel. A mid-turn steer
+ // fires the hook again; the newer echo replaces the held id on purpose,
+ // so the turn's rating attaches to the segment that produced its final
+ // answer.
+ const traceId =
+ message.hook_event === "UserPromptSubmit" &&
+ message.outcome === "success"
+ ? traceIdFromHookStderr(message.stderr, session.traceparentHookNonce)
+ : null;
+ if (traceId) {
+ session.currentTurnTraceId = traceId;
+ }
+ logger.debug("Hook response received", {
hookName: message.hook_name,
hookEvent: message.hook_event,
});
break;
+ }
case "status":
if (message.status === "compacting") {
logger.info("Session compacting started", { sessionId });
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
index 51519fc0076e..e91eb0d6a697 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
@@ -45,6 +45,7 @@ function makeParams() {
isResume: false,
settingsManager: new SettingsManager(cwd),
taskState: new Map(),
+ traceparentHookNonce: "0123456789abcdef",
};
}
@@ -445,6 +446,16 @@ describe("buildSessionOptions", () => {
expect(headers).toBe(expected);
},
);
+
+ it("stamps the task id as the LLMA session id so generations group with feedback", () => {
+ const headers = buildSessionOptions({
+ ...makeParams(),
+ taskId: "task-123",
+ }).env?.ANTHROPIC_CUSTOM_HEADERS;
+
+ expect(headers).toContain("x-posthog-property-$ai_session_id: task-123");
+ expect(headers).not.toContain("test-session");
+ });
});
describe("machineAuth (own Claude subscription)", () => {
@@ -717,6 +728,58 @@ describe("buildSessionOptions", () => {
"00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
);
});
+
+ it("registers the traceparent hook and hook events for gateway sessions", () => {
+ const options = buildSessionOptions({ ...makeParams(), gatewayEnv });
+
+ const settings = JSON.parse(String(options.extraArgs?.settings));
+ const hook = settings.hooks.UserPromptSubmit[0].hooks[0];
+ expect(hook.command).toContain("$TRACEPARENT");
+ expect(options.includeHookEvents).toBe(true);
+ });
+
+ it("registers no traceparent hook for BYOK sessions", () => {
+ const options = buildSessionOptions(makeParams());
+
+ expect(options.extraArgs?.settings).toBeUndefined();
+ expect(options.includeHookEvents).toBe(false);
+ });
+
+ it("never clobbers a caller-supplied settings flag", () => {
+ const options = buildSessionOptions({
+ ...makeParams(),
+ gatewayEnv,
+ userProvidedOptions: { extraArgs: { settings: '{"model":"x"}' } },
+ });
+
+ expect(options.extraArgs?.settings).toBe('{"model":"x"}');
+ });
+
+ it("skips the hook when the caller uses the SDK settings option", () => {
+ // Both channels feed the same CLI flag; the SDK silently drops the
+ // extraArgs one, which would kill the caller's settings.
+ const options = buildSessionOptions({
+ ...makeParams(),
+ gatewayEnv,
+ userProvidedOptions: { settings: '{"model":"x"}' },
+ });
+
+ expect(options.extraArgs?.settings).toBeUndefined();
+ });
+
+ it("skips the POSIX hook on Windows hosts", () => {
+ const platform = Object.getOwnPropertyDescriptor(process, "platform");
+ Object.defineProperty(process, "platform", { value: "win32" });
+ try {
+ const options = buildSessionOptions({ ...makeParams(), gatewayEnv });
+ expect(options.extraArgs?.settings).toBeUndefined();
+ expect(options.includeHookEvents).toBe(false);
+ } finally {
+ if (platform) {
+ Object.defineProperty(process, "platform", platform);
+ }
+ }
+ });
});
});
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
index f5b9a5ebcbd0..7caeafd07c3a 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/options.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
@@ -51,6 +51,7 @@ import { loadUserClaudeJsonMcpServers } from "./mcp-config";
import { DEFAULT_MODEL, resolveFallbackModel } from "./models";
import { createRtkRewriteHook, resolveRtkPrefix } from "./rtk";
import type { SettingsManager } from "./settings";
+import { buildTraceparentHookSettingsJson } from "./traceparent-hook";
export interface ProcessSpawnedInfo {
pid: number;
@@ -91,6 +92,7 @@ export interface BuildOptionsParams {
systemPrompt?: Options["systemPrompt"];
userProvidedOptions?: Options;
sessionId: string;
+ taskId?: string;
isResume: boolean;
forkSession?: boolean;
additionalDirectories?: string[];
@@ -119,6 +121,9 @@ export interface BuildOptionsParams {
getCurrentModelId?: () => string | undefined;
/** Explicit gateway config — prevents global process.env mutation. */
gatewayEnv?: GatewayEnv;
+ /** Session's discriminator for the traceparent hook's stderr; the hook is
+ * skipped when absent (see session/traceparent-hook.ts). */
+ traceparentHookNonce?: string;
machineAuth?: MachineClaudeAuth;
/** Matched `bedrock-llm-gateway` variant; `test` serves this session from Bedrock. */
bedrockGatewayVariant?: BedrockGatewayVariant;
@@ -177,7 +182,7 @@ function buildMcpServers(
function buildEnvironment(
gateway?: GatewayEnv,
- sessionId?: string,
+ aiSessionId?: string,
bedrockGatewayVariant?: BedrockGatewayVariant,
contextWiki?: ContextWikiEnv,
machineAuth?: MachineClaudeAuth,
@@ -208,7 +213,7 @@ function buildEnvironment(
if (machineAuth) {
applyMachineClaudeAuth(env, machineAuth);
} else {
- applyGatewayAuth(env, gateway, sessionId, bedrockGatewayVariant);
+ applyGatewayAuth(env, gateway, aiSessionId, bedrockGatewayVariant);
}
applyContextWikiEnv(env, contextWiki);
return env;
@@ -217,7 +222,7 @@ function buildEnvironment(
function applyGatewayAuth(
env: Record<string, string>,
gateway: GatewayEnv | undefined,
- sessionId: string | undefined,
+ aiSessionId: string | undefined,
bedrockGatewayVariant: BedrockGatewayVariant | undefined,
): void {
// Custom HTTP headers reach the model only through the Claude CLI subprocess,
@@ -238,9 +243,9 @@ function applyGatewayAuth(
if (projectId) {
headerLines.push(buildPosthogProjectHeaderLines(Number(projectId)));
}
- if (sessionId) {
+ if (aiSessionId) {
headerLines.push(
- buildPosthogPropertyHeaderLines({ $ai_session_id: sessionId }),
+ buildPosthogPropertyHeaderLines({ $ai_session_id: aiSessionId }),
);
}
// The two Bedrock headers are mutually exclusive at the gateway: it dispatches
@@ -529,6 +534,22 @@ function isLegacyJavaScriptClaudeExecutable(executablePath: string): boolean {
export function buildSessionOptions(params: BuildOptionsParams): Options {
ensureLocalSettings(params.cwd);
+ // Gateway sessions get the traceparent hook (see session/traceparent-hook.ts)
+ // so each turn's gateway trace id reaches the session as a `hook_response`.
+ // `--settings` is the one hook channel that needs no settingSources; skipped
+ // when the caller supplies its own settings (either the SDK `settings`
+ // option or a raw `extraArgs` flag — both reach the same CLI flag, and the
+ // SDK silently drops the extraArgs one on collision) rather than clobbering
+ // it. The hook command is POSIX shell, so Windows Desktop hosts skip it.
+ const traceparentHookSettings =
+ params.gatewayEnv?.anthropicBaseUrl &&
+ params.traceparentHookNonce &&
+ process.platform !== "win32" &&
+ params.userProvidedOptions?.settings === undefined &&
+ params.userProvidedOptions?.extraArgs?.settings === undefined
+ ? buildTraceparentHookSettingsJson(params.traceparentHookNonce)
+ : undefined;
+
// Resolve which built-in tools to expose.
// Explicit tools array from userProvidedOptions takes precedence.
// disableBuiltInTools is a legacy shorthand for tools: [] — kept for
@@ -563,15 +584,23 @@ export function buildSessionOptions(params: BuildOptionsParams): Options {
extraArgs: {
...params.userProvidedOptions?.extraArgs,
"replay-user-messages": "",
+ ...(traceparentHookSettings && { settings: traceparentHookSettings }),
},
+ // Surfaces the traceparent hook's output as `hook_response` messages.
+ includeHookEvents:
+ params.userProvidedOptions?.includeHookEvents ??
+ traceparentHookSettings !== undefined,
mcpServers: buildMcpServers(
params.userProvidedOptions?.mcpServers,
params.mcpServers,
loadUserClaudeJsonMcpServers(params.cwd, params.logger),
),
+ // Feedback events stamp the task id as $ai_session_id, so generations
+ // carry the same id for LLMA to group a task's runs and ratings together.
+ // A session without a task keeps the agent session id.
env: buildEnvironment(
params.gatewayEnv,
- params.sessionId,
+ params.taskId ?? params.sessionId,
params.bedrockGatewayVariant,
params.contextWiki,
params.machineAuth,
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/traceparent-hook.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/traceparent-hook.test.ts
new file mode 100644
index 000000000000..befb59a891d8
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/session/traceparent-hook.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildTraceparentHookSettingsJson,
+ traceIdFromHookStderr,
+} from "./traceparent-hook";
+
+const NONCE = "0123456789abcdef";
+
+describe("traceparent hook", () => {
+ it.each([
+ [
+ "a valid traceparent",
+ `traceparent:${NONCE}=00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01`,
+ "0af76519-16cd-43dd-8448-eb211c80319c",
+ ],
+ [
+ "a future traceparent version",
+ `traceparent:${NONCE}=01-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01`,
+ "0af76519-16cd-43dd-8448-eb211c80319c",
+ ],
+ [
+ "a trailing newline",
+ `traceparent:${NONCE}=00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01\n`,
+ "0af76519-16cd-43dd-8448-eb211c80319c",
+ ],
+ [
+ "the all-zero trace id the W3C spec reserves for 'no trace'",
+ `traceparent:${NONCE}=00-00000000000000000000000000000000-b7ad6b7169203331-01`,
+ null,
+ ],
+ ["an empty TRACEPARENT env", `traceparent:${NONCE}=`, null],
+ ["a malformed value", `traceparent:${NONCE}=not-a-traceparent`, null],
+ [
+ "another hook echoing a valid traceparent without the session nonce",
+ "traceparent=00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
+ null,
+ ],
+ [
+ "another hook guessing a wrong nonce",
+ "traceparent:ffffffffffffffff=00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
+ null,
+ ],
+ [
+ "output that is not from this hook",
+ "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
+ null,
+ ],
+ ])("handles %s", (_case, stderr, expected) => {
+ expect(traceIdFromHookStderr(stderr, NONCE)).toBe(expected);
+ });
+
+ it("accepts nothing when the session has no nonce", () => {
+ expect(
+ traceIdFromHookStderr(
+ `traceparent:${NONCE}=00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01`,
+ undefined,
+ ),
+ ).toBeNull();
+ });
+
+ it("declares a command hook that writes to stderr, never to model context", () => {
+ const settings = JSON.parse(buildTraceparentHookSettingsJson(NONCE));
+ const hook = settings.hooks.UserPromptSubmit[0].hooks[0];
+ expect(hook.type).toBe("command");
+ expect(hook.command).toContain("$TRACEPARENT");
+ expect(hook.command).toContain(`traceparent:${NONCE}=`);
+ // stdout of a UserPromptSubmit hook is injected into the model's context;
+ // stderr is not. The command must redirect.
+ expect(hook.command).toContain(">&2");
+ });
+});
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/traceparent-hook.ts b/products/desktop/packages/agent/src/adapters/claude/session/traceparent-hook.ts
new file mode 100644
index 000000000000..67b0da9fdb02
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/session/traceparent-hook.ts
@@ -0,0 +1,72 @@
+/**
+ * Per-turn trace id recovery for gateway sessions.
+ *
+ * The LLM gateway derives each `$ai_generation`'s `$ai_trace_id` from the W3C
+ * `traceparent` header the Claude CLI sends, and the CLI mints one trace id
+ * per user turn. The CLI never reports that id on its stdout protocol, so the
+ * agent-server cannot correlate a turn with its generations. The CLI does
+ * export `TRACEPARENT` into every subprocess it spawns, hooks included, so a
+ * `UserPromptSubmit` command hook can echo it. With `includeHookEvents` on,
+ * the echo arrives as a `hook_response` SDK message before the turn's first
+ * gateway request.
+ *
+ * The hook writes to stderr: a `UserPromptSubmit` hook's stdout is injected
+ * into the model's context, stderr is not.
+ *
+ * `hook_response` carries no field identifying which settings source declared
+ * a hook (`hook_name` is just the event name), so a per-session random nonce
+ * in the stderr prefix keeps another `UserPromptSubmit` hook (user or repo
+ * settings) from colliding with this channel by accident. It is not a
+ * security boundary: the nonce rides the CLI's `--settings` argv, readable by
+ * any process on the machine, and a repo hook already runs with the session's
+ * full privileges.
+ */
+
+import { randomBytes } from "node:crypto";
+
+const TRACEPARENT_STDERR_PREFIX = "traceparent:";
+
+/** Per-session discriminator for the hook's stderr prefix. Hex only, so it is
+ * safe inside the single-quoted shell command and the settings JSON. */
+export function generateTraceparentHookNonce(): string {
+ return randomBytes(8).toString("hex");
+}
+
+/** Value for the CLI's `--settings <json>` flag declaring the hook. */
+export function buildTraceparentHookSettingsJson(nonce: string): string {
+ const command = `printf '${TRACEPARENT_STDERR_PREFIX}${nonce}=%s' "$TRACEPARENT" >&2`;
+ return JSON.stringify({
+ hooks: {
+ UserPromptSubmit: [{ hooks: [{ type: "command", command }] }],
+ },
+ });
+}
+
+/**
+ * Parses the hook's stderr into the gateway's `$ai_trace_id` form: the
+ * traceparent's 32-hex trace id rendered as a UUID, matching the gateway's
+ * `str(UUID(hex=...))`. Returns null for anything else, including a
+ * missing/mismatched nonce and the all-zero id the W3C spec reserves for
+ * "no trace".
+ */
+export function traceIdFromHookStderr(
+ stderr: string,
+ nonce: string | undefined,
+): string | null {
+ if (!nonce) {
+ return null;
+ }
+ const prefix = `${TRACEPARENT_STDERR_PREFIX}${nonce}=`;
+ if (!stderr.startsWith(prefix)) {
+ return null;
+ }
+ const traceparent = stderr.slice(prefix.length).trim();
+ const match = /^[0-9a-f]{2}-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(
+ traceparent,
+ );
+ if (!match || /^0{32}$/.test(match[1])) {
+ return null;
+ }
+ const hex = match[1];
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+}
diff --git a/products/desktop/packages/agent/src/adapters/claude/types.ts b/products/desktop/packages/agent/src/adapters/claude/types.ts
index f6ff491ec617..389ffdfd640a 100644
--- a/products/desktop/packages/agent/src/adapters/claude/types.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/types.ts
@@ -108,6 +108,16 @@ export type Session = BaseSession & {
fastModeEnabled: boolean;
/** Last title pushed via `session_info_update`, to dedupe turn-end polls. */
lastTitle?: string;
+ /** Gateway-form trace id of the SDK turn now executing, reported by the
+ * traceparent hook (see session/traceparent-hook.ts); cleared on settle
+ * and on turn failure. */
+ currentTurnTraceId?: string;
+ /** Discriminator the traceparent hook embeds in its stderr prefix; the
+ * parser only accepts echoes carrying it. */
+ traceparentHookNonce?: string;
+ /** True when this session's CLI was launched with the traceparent hook, so a
+ * model turn that settles without a trace id is a real gap worth logging. */
+ traceparentHookInstalled: boolean;
configOptions: SessionConfigOption[];
accumulatedUsage: AccumulatedUsage;
/** PostHog products used during this session, derived from MCP exec calls.
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index d66d58931f27..d59d21622400 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -1496,7 +1496,10 @@ export class AgentServer {
}
this.recordTurnUsage(result.usage);
- this.broadcastTurnComplete(result.stopReason);
+ this.broadcastTurnComplete(
+ result.stopReason,
+ this.promptResultTraceId(result),
+ );
if (result.stopReason === "end_turn") {
// Relay the response to Slack. For follow-ups this is the primary
@@ -2639,7 +2642,10 @@ export class AgentServer {
}
this.recordTurnUsage(result.usage);
- this.broadcastTurnComplete(result.stopReason);
+ this.broadcastTurnComplete(
+ result.stopReason,
+ this.promptResultTraceId(result),
+ );
if (result.stopReason === "end_turn") {
await this.relayAgentResponse(payload);
@@ -3021,7 +3027,10 @@ export class AgentServer {
}
this.recordTurnUsage(result.usage);
- this.broadcastTurnComplete(result.stopReason);
+ this.broadcastTurnComplete(
+ result.stopReason,
+ this.promptResultTraceId(result),
+ );
if (result.stopReason === "end_turn") {
await this.relayAgentResponse(payload);
@@ -5626,7 +5635,17 @@ ${commonInstructions}
this.broadcastEvent(event);
}
- private broadcastTurnComplete(stopReason: string): void {
+ /** The per-turn gateway trace id the Claude adapter reports via `PromptResponse._meta`. */
+ private promptResultTraceId(result: PromptResponse): string | null {
+ const traceId = (result._meta as { traceId?: unknown } | undefined)
+ ?.traceId;
+ return typeof traceId === "string" ? traceId : null;
+ }
+
+ private broadcastTurnComplete(
+ stopReason: string,
+ traceId: string | null = null,
+ ): void {
if (!this.session) return;
if (this.adapterEmittedTurnComplete) {
this.adapterEmittedTurnComplete = false;
@@ -5638,6 +5657,7 @@ ${commonInstructions}
params: {
sessionId: this.session.acpSessionId,
stopReason,
+ ...(traceId ? { traceId } : {}),
},
};
diff --git a/products/desktop/packages/core/src/analytics/aiFeedback.test.ts b/products/desktop/packages/core/src/analytics/aiFeedback.test.ts
index 6473686e9f2a..aee176d8e438 100644
--- a/products/desktop/packages/core/src/analytics/aiFeedback.test.ts
+++ b/products/desktop/packages/core/src/analytics/aiFeedback.test.ts
@@ -23,9 +23,15 @@ describe("aiFeedback", () => {
"maps a %s thumb to a quality=%s metric on the turn",
(sentiment, rating) => {
expect(
- buildTurnRatingMetric({ run, turnId: "turn-9", sentiment }),
+ buildTurnRatingMetric({
+ run,
+ turnId: "turn-9",
+ traceId: "trace-9",
+ sentiment,
+ }),
).toEqual({
...context,
+ $ai_trace_id: "trace-9",
turn_id: "turn-9",
$ai_metric_name: "quality",
$ai_metric_value: rating,
@@ -38,10 +44,12 @@ describe("aiFeedback", () => {
buildTurnRatingMetric({
run: { taskId: null },
turnId: "turn-1",
+ traceId: null,
sentiment: "positive",
}),
).toMatchObject({
$ai_session_id: null,
+ $ai_trace_id: null,
task_id: null,
task_run_id: undefined,
$ai_metric_value: "good",
diff --git a/products/desktop/packages/core/src/analytics/aiFeedback.ts b/products/desktop/packages/core/src/analytics/aiFeedback.ts
index 37b27cdcafb1..7c7b18c7c0d6 100644
--- a/products/desktop/packages/core/src/analytics/aiFeedback.ts
+++ b/products/desktop/packages/core/src/analytics/aiFeedback.ts
@@ -20,11 +20,12 @@ export interface AiFeedbackRunRef {
function buildContext(
run: AiFeedbackRunRef,
+ traceId: string | null,
extra: Partial<AiFeedbackContextProperties> = {},
): AiFeedbackContextProperties {
return {
$ai_session_id: run.taskId,
- $ai_trace_id: null,
+ $ai_trace_id: traceId,
ai_product: "posthog_code",
task_id: run.taskId,
task_run_id: run.taskRunId,
@@ -41,10 +42,11 @@ function sentimentToRating(
export function buildTurnRatingMetric(input: {
run: AiFeedbackRunRef;
turnId: string;
+ traceId: string | null;
sentiment: AgentTurnFeedbackSentiment;
}): AiMetricProperties {
return {
- ...buildContext(input.run, { turn_id: input.turnId }),
+ ...buildContext(input.run, input.traceId, { turn_id: input.turnId }),
$ai_metric_name: "quality",
$ai_metric_value: sentimentToRating(input.sentiment),
};
@@ -65,7 +67,8 @@ export interface SlashFeedbackEvents {
export function buildSlashFeedbackEvents(
input: SlashFeedbackInput,
): SlashFeedbackEvents {
- const context = buildContext(input.run, {
+ // Slash feedback rates the session, not one turn, so it carries no trace id.
+ const context = buildContext(input.run, null, {
feedback_type: input.feedbackType,
event_count: input.eventCount,
});
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 6cf61a27520b..5cc2b0c97f1f 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -499,7 +499,7 @@ export type AiQualityRating = "good" | "bad";
export interface AiFeedbackContextProperties {
$ai_session_id: string | null;
- $ai_trace_id: null;
+ $ai_trace_id: string | null;
ai_product: AiFeedbackProduct;
task_id: string | null;
task_run_id?: string;
diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
index b01cfc1068d1..3ba13f28d8cd 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
@@ -58,14 +58,21 @@ function userPromptMsg(
};
}
-function promptResponseMsg(ts: number, id: number): AcpMessage {
+function promptResponseMsg(
+ ts: number,
+ id: number,
+ traceId?: string,
+): AcpMessage {
return {
type: "acp_message",
ts,
message: {
jsonrpc: "2.0",
id,
- result: { stopReason: "end_turn" },
+ result: {
+ stopReason: "end_turn",
+ ...(traceId ? { _meta: { traceId } } : {}),
+ },
},
};
}
@@ -251,6 +258,23 @@ describe("buildConversationItems", () => {
);
});
+ it("keeps the prompt response's trace id on the turn for its rating", () => {
+ const result = buildConversationItems(
+ [
+ userPromptMsg(1, 1, "hi"),
+ agentMessageMsg(2, "hello"),
+ promptResponseMsg(3, 1, "trace-1"),
+ ],
+ null,
+ );
+
+ const update = result.items.find((item) => item.type === "session_update");
+ expect(update?.turnContext).toMatchObject({
+ turnComplete: true,
+ traceId: "trace-1",
+ });
+ });
+
it("keeps item ids stable when older history is prepended", () => {
const older: AcpMessage[] = [
userPromptMsg(1, 1, "first question"),
diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
index 95e246f3ee14..092b2f1683b8 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
@@ -40,6 +40,8 @@ export interface TurnContext {
childItems: Map<string, ConversationItem[]>;
turnCancelled: boolean;
turnComplete: boolean;
+ /** From the prompt response; null when the agent reported no gateway trace. */
+ traceId?: string | null;
}
export type ConversationItem =
@@ -685,11 +687,12 @@ function handlePromptResponse(
if (!turn) return;
const result = msg.result as {
stopReason?: string;
- _meta?: { interruptReason?: string };
+ _meta?: { interruptReason?: string; traceId?: string | null };
};
completePromptTurn(b, turn, ts, {
stopReason: result?.stopReason,
interruptReason: result?._meta?.interruptReason,
+ traceId: result?._meta?.traceId ?? null,
});
}
@@ -697,8 +700,15 @@ function completePromptTurn(
b: ItemBuilder,
turn: TurnState,
ts: number,
- result: { stopReason?: string; interruptReason?: string } = {},
+ result: {
+ stopReason?: string;
+ interruptReason?: string;
+ traceId?: string | null;
+ } = {},
) {
+ // The prompt response and `_posthog/turn_complete` race in cloud logs, so
+ // the trace id is taken from whichever carries it, even after completion.
+ if (result.traceId !== undefined) turn.context.traceId = result.traceId;
if (turn.isComplete) return;
turn.isComplete = true;
@@ -802,10 +812,13 @@ function handleNotification(
isNotification(msg.method, POSTHOG_NOTIFICATIONS.BACKGROUND_TURN_COMPLETE)
) {
b.isBackgroundTurnActive = false;
- const params = msg.params as { stopReason?: string } | undefined;
+ const params = msg.params as
+ | { stopReason?: string; traceId?: string | null }
+ | undefined;
if (!b.currentTurn) return;
completePromptTurn(b, b.currentTurn, ts, {
stopReason: params?.stopReason,
+ traceId: params?.traceId,
});
return;
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
index 6115901fbd66..6166c300c198 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
@@ -71,6 +71,7 @@ import {
type AgentTurn,
CHAT_THREAD_VIRTUALIZATION_THRESHOLD,
completedTurnTimestamp,
+ completedTurnTraceId,
countFlatRows,
type FlatThreadRow,
FOLLOWING_END,
@@ -365,10 +366,12 @@ const RawLogsToggleContext = createContext(false);
function TurnFooter({
turnId,
+ traceId,
timestamp,
copyText,
}: {
turnId: string;
+ traceId: string | null;
timestamp?: number;
copyText?: string;
}) {
@@ -389,7 +392,7 @@ function TurnFooter({
</span>
{copyText && <CopyButton value={copyText} label="Copy turn" />}
{(revealed || sentiment) && (
- <TurnFeedback turnId={turnId} sentiment={sentiment} />
+ <TurnFeedback turnId={turnId} traceId={traceId} sentiment={sentiment} />
)}
</ChatMessageFooter>
);
@@ -406,9 +409,11 @@ function TurnFooter({
*/
function TurnFeedback({
turnId,
+ traceId,
sentiment,
}: {
turnId: string;
+ traceId: string | null;
sentiment: AgentTurnFeedbackSentiment | null;
}) {
const taskId = useSessionTaskId();
@@ -426,6 +431,7 @@ function TurnFeedback({
buildTurnRatingMetric({
run: { taskId, taskRunId },
turnId,
+ traceId,
sentiment: next,
}),
);
@@ -944,6 +950,7 @@ const ThreadRow = memo(function ThreadRow({
</div>
<TurnFooter
turnId={item.id}
+ traceId={completedTurnTraceId(item)}
timestamp={completedTurnTimestamp(item)}
copyText={buildTurnCopyText(item.items) ?? undefined}
/>
@@ -1324,6 +1331,7 @@ const FlatRowView = memo(
{row.turnId != null && row.turnTimestamp != null && (
<TurnFooter
turnId={row.turnId}
+ traceId={row.turnTraceId ?? null}
timestamp={row.turnTimestamp}
copyText={row.turnCopyText}
/>
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts
index 535777dfcbe0..55b2019c3e51 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts
@@ -28,7 +28,13 @@ function sessionUpdate(
turnComplete = false,
timestamp,
text,
- }: { turnComplete?: boolean; timestamp?: number; text?: string } = {},
+ traceId,
+ }: {
+ turnComplete?: boolean;
+ timestamp?: number;
+ text?: string;
+ traceId?: string | null;
+ } = {},
): SessionUpdateItem {
return {
type: "session_update",
@@ -42,6 +48,7 @@ function sessionUpdate(
childItems: new Map(),
turnCancelled: false,
turnComplete,
+ traceId,
},
timestamp,
};
@@ -150,6 +157,19 @@ describe("flattenTurnRows", () => {
expect(flat.map((r) => r.turnTimestamp)).toEqual([undefined, 1234]);
});
+ it("carries the turn's trace id on the same row as its timestamp", () => {
+ const done = agentTurn("d", [
+ sessionUpdate("d1"),
+ sessionUpdate("d2", {
+ turnComplete: true,
+ timestamp: 1234,
+ traceId: "trace-d",
+ }),
+ ]);
+ const flat = flattenTurnRows([done]);
+ expect(flat.map((r) => r.turnTraceId)).toEqual([undefined, "trace-d"]);
+ });
+
it("carries the turn's copy text on the same row as its timestamp", () => {
const done = agentTurn("d", [
sessionUpdate("d1", { text: "first" }),
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts
index 7a579136c918..8f25624efd26 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts
@@ -88,6 +88,8 @@ export interface FlatThreadRow {
turnTimestamp?: number;
/** Set alongside {@link turnTimestamp}: identifies the turn its footer actions act on. */
turnId?: string;
+ /** Set alongside {@link turnId}: the gateway trace id the turn's rating joins on, null when unknown. */
+ turnTraceId?: string | null;
/** Set alongside {@link turnTimestamp}: the agent response as plain text, for its copy button. */
turnCopyText?: string;
}
@@ -97,16 +99,27 @@ export interface FlatThreadRow {
* by the last step in its run). Undefined while the turn is still streaming, since the timestamp
* only appears once the whole turn is done.
*/
-export function completedTurnTimestamp(turn: AgentTurn): number | undefined {
+function lastSessionUpdate(turn: AgentTurn) {
for (let i = turn.items.length - 1; i >= 0; i--) {
const item = turn.items[i];
const last = item.type === "tool_group" ? item.items.at(-1) : item;
- if (last?.type !== "session_update") continue;
- return last.turnContext.turnComplete ? last.timestamp : undefined;
+ if (last?.type === "session_update") return last;
}
return undefined;
}
+export function completedTurnTimestamp(turn: AgentTurn): number | undefined {
+ const last = lastSessionUpdate(turn);
+ return last?.turnContext.turnComplete ? last.timestamp : undefined;
+}
+
+export function completedTurnTraceId(turn: AgentTurn): string | null {
+ const last = lastSessionUpdate(turn);
+ return last?.turnContext.turnComplete
+ ? (last.turnContext.traceId ?? null)
+ : null;
+}
+
/** Viewport distance from the top of the loaded window that triggers an older-history page load. */
export const OLDER_HISTORY_LOAD_THRESHOLD_PX = 800;
@@ -165,6 +178,7 @@ export function flattenTurnRows(rows: TurnRow[]): FlatThreadRow[] {
timestamp == null
? undefined
: (buildTurnCopyText(row.items) ?? undefined);
+ const traceId = timestamp == null ? null : completedTurnTraceId(row);
for (let i = 0; i < row.items.length; i++) {
const item = row.items[i];
const isTrailing = i === row.items.length - 1;
@@ -175,6 +189,7 @@ export function flattenTurnRows(rows: TurnRow[]): FlatThreadRow[] {
isTrailingInTurn: isTrailing,
turnTimestamp: isTrailing ? timestamp : undefined,
turnId: isTrailing ? row.id : undefined,
+ turnTraceId: isTrailing ? traceId : undefined,
turnCopyText: isTrailing ? copyText : undefined,
});
}
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
index 238a2ee9f281..63a424098f49 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
@@ -738,6 +738,7 @@ describe("AgentService", () => {
expect(mockNewSession).toHaveBeenCalledTimes(1);
expect(mockNewSession.mock.calls[0][0]._meta).toMatchObject({
+ taskId: "task-1",
taskRunId: "run-1",
environment: "local",
});
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
index ddaba7a427b9..e3964292d414 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
@@ -1279,6 +1279,7 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
...(logUrl && {
persistence: { taskId, runId: taskRunId, logUrl },
}),
+ ...(!isPreview && { taskId }),
taskRunId,
environment: "local",
sessionId: existingSessionId,
@@ -1314,6 +1315,7 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
cwd: repoPath,
mcpServers,
_meta: {
+ ...(!isPreview && { taskId }),
taskRunId,
environment: "local",
systemPrompt,
diff --git a/products/posthog_ai/frontend/components/FeedbackPromptDetails.tsx b/products/posthog_ai/frontend/components/FeedbackPromptDetails.tsx
index 2e96c35d20bd..27be87bcfdad 100644
--- a/products/posthog_ai/frontend/components/FeedbackPromptDetails.tsx
+++ b/products/posthog_ai/frontend/components/FeedbackPromptDetails.tsx
@@ -24,7 +24,7 @@ export const FeedbackPromptDetails = memo(function FeedbackPromptDetails({
}: FeedbackPromptLogicProps & { sessionKind: FeedbackSessionKind }): JSX.Element {
const logicProps = { sessionId, streamKey }
const { submitDetailedFeedback, completeDetailedFeedback } = useActions(feedbackPromptLogic(logicProps))
- const { traceId } = useValues(runStreamLogic)
+ const { latestTurnTraceId: traceId } = useValues(runStreamLogic)
const [feedbackText, setFeedbackText] = useState('')
const [status, setStatus] = useState<'feedback' | 'ticket_preview' | 'done'>('feedback')
const [hasSubmittedTicket, setHasSubmittedTicket] = useState(false)
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
index 9f42754ce5ff..25094b78803f 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
@@ -211,7 +211,7 @@ function RunSurfaceThread({
sessionId={feedbackSessionId}
turnIndex={trailer.turnIndex}
run={feedbackRun}
- isLastTurn={trailer.isLastTurn}
+ traceId={trailer.traceId}
turnText={trailer.turnText}
/>
) : null,
diff --git a/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx
index 8a567b5f1d56..1af2bb2276e8 100644
--- a/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx
+++ b/products/posthog_ai/frontend/components/TurnFeedbackActions.tsx
@@ -8,7 +8,6 @@ import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { stripMarkdown } from 'lib/utils/markdown'
import { messageRatingsLogic } from '../logics/messageRatingsLogic'
-import { runStreamLogic } from '../logics/runStreamLogic'
import { MessageTemplate } from '../messages/MessageTemplate'
import { RunRef, captureTurnFeedbackText, captureTurnRating } from '../utils/feedbackEvents'
@@ -18,7 +17,8 @@ export interface TurnFeedbackActionsProps {
/** Ordinal of the completed turn — the rating's identity, stable across reloads. */
turnIndex: number
run: RunRef
- isLastTurn: boolean
+ /** The turn's gateway trace id, when the run reported one. Lands in `$ai_trace_id`. */
+ traceId?: string
turnText: string
}
@@ -31,28 +31,23 @@ export const TurnFeedbackActions = memo(function TurnFeedbackActions({
sessionId,
turnIndex,
run,
- isLastTurn,
+ traceId,
turnText,
}: TurnFeedbackActionsProps): JSX.Element {
const { ratingForKey } = useValues(messageRatingsLogic)
const { setRating } = useActions(messageRatingsLogic)
- const { traceId } = useValues(runStreamLogic)
const ratingKey = `${sessionId}:turn-${turnIndex}`
const rating = ratingForKey(ratingKey)
const [feedback, setFeedback] = useState<string>('')
const [feedbackInputStatus, setFeedbackInputStatus] = useState<'hidden' | 'pending' | 'submitted'>('hidden')
- // The sandbox runtime exposes no per-turn trace ids; the client-minted id of the latest send is
- // the only truthful value. Older turns send null rather than a synthetic id.
- const turnTraceId = isLastTurn ? traceId : null
-
function submitRating(newRating: 'good' | 'bad'): void {
if (rating) {
return // Already rated
}
setRating({ key: ratingKey, rating: newRating })
- captureTurnRating(sessionId, turnTraceId, newRating, turnIndex, run)
+ captureTurnRating(sessionId, traceId ?? null, newRating, turnIndex, run)
if (newRating === 'bad') {
setFeedbackInputStatus('pending')
}
@@ -62,7 +57,7 @@ export const TurnFeedbackActions = memo(function TurnFeedbackActions({
if (!feedback) {
return // Input is empty
}
- captureTurnFeedbackText(sessionId, turnTraceId, feedback, turnIndex, run)
+ captureTurnFeedbackText(sessionId, traceId ?? null, feedback, turnIndex, run)
setFeedbackInputStatus('submitted')
}
diff --git a/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts b/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts
index 0f264d6a1ab7..329c40ce42e1 100644
--- a/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts
+++ b/products/posthog_ai/frontend/logics/feedbackPromptLogic.ts
@@ -42,7 +42,8 @@ function readStream(streamKey: string): StreamSnapshot {
const trailers = computeTurnTrailers(items)
const lastTurn = [...trailers.values()].find((trailer) => trailer.isLastTurn)
return {
- traceId: stream.values.traceId,
+ // Same trailer as turnIndex, so the two can never describe different turns.
+ traceId: lastTurn?.traceId ?? null,
turnIndex: lastTurn?.turnIndex ?? null,
humanMessageCount: items.filter((item) => item.type === 'human_message').length,
run: stream.cache.activeRun as RunRef | undefined,
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index 89458e0d5838..f6623b549891 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -14,6 +14,7 @@ import { tasksRunsCommandCreate, tasksRunsStreamTokenRetrieve } from 'products/t
import type { AttachedContextItem } from '../types/contextTypes'
import type { PermissionRequestFrame, StoredLogEntry } from '../types/wireTypes'
import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContextBlock'
+import { computeTurnTrailers } from '../utils/turnTrailers'
import { attachedContextLogic } from './attachedContextLogic'
import { foregroundStreamLogic } from './foregroundStreamLogic'
import {
@@ -933,6 +934,43 @@ describe('runStreamLogic', () => {
})
})
+ describe('turn trace ids', () => {
+ const TRACE = '1d223305-d7ca-bfeb-3775-a4a15a6a31c6'
+
+ it('carries a replayed turn_complete traceId into the trailer and selector', async () => {
+ const frames: StoredLogEntry[] = [
+ notification('_posthog/user_message', { content: 'say baseline' }),
+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'baseline' } }),
+ notification('_posthog/turn_complete', { sessionId: 's1', stopReason: 'end_turn', traceId: TRACE }),
+ ]
+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)
+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)
+
+ await expectLogic(logic, () => {
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ }).toFinishAllListeners()
+
+ const trailers = computeTurnTrailers(logic.values.threadItems)
+ const lastTurn = [...trailers.values()].find((trailer) => trailer.isLastTurn)
+ expect(lastTurn?.traceId).toBe(TRACE)
+ expect(logic.values.latestTurnTraceId).toBe(TRACE)
+ })
+
+ it('keeps the last real turn id when a trailing traceless separator follows', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'q' }))
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'a' } })
+ )
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', { traceId: TRACE }))
+ // Synthetic idle-resume/error separators carry no trace id and are not turns.
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+ }).toFinishAllListeners()
+
+ expect(logic.values.latestTurnTraceId).toBe(TRACE)
+ })
+ })
+
describe('_posthog/user_message rendering', () => {
it('renders a seeded user turn into the thread on bootstrap replay', async () => {
const frames: StoredLogEntry[] = [
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index d59480002fbc..5672ee750530 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -70,6 +70,7 @@ import {
} from '../types/wireTypes'
import { extractContextBlockLines } from '../utils/posthogContextBlock'
import { getClaudeCodeMeta, resolveToolCall } from '../utils/toolResolver'
+import { computeTurnTrailers } from '../utils/turnTrailers'
import { attachedContextLogic } from './attachedContextLogic'
import { debugLogsLogic } from './debugLogsLogic'
import { registerHmrStreamAbort } from './devHmrStreamAbort'
@@ -1189,7 +1190,8 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
continue
}
if (method === '_posthog/turn_complete') {
- items.push({ id: `turn-${separatorSeq++}`, type: 'turn_separator' })
+ const traceId = typeof params.traceId === 'string' ? params.traceId : undefined
+ items.push({ id: `turn-${separatorSeq++}`, type: 'turn_separator', ...(traceId && { traceId }) })
continue
}
if (method === '_posthog/progress') {
@@ -1402,6 +1404,7 @@ export interface runStreamLogicValues {
hasGitArtifacts: boolean
isBootstrapResumeRun: boolean
isThinking: boolean
+ latestTurnTraceId: string | null
log: RunLog
logBootstrapLoading: boolean
pendingPermissionRequest: PermissionRequestRecord | null
@@ -1624,6 +1627,7 @@ export interface runStreamLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
foldedThread: (log: RunLog, isBootstrapResumeRun: boolean) => FoldedThread
+ latestTurnTraceId: (threadItems: ThreadItem[]) => string | null
threadItems: (foldedThread: FoldedThread, showDebugLogs: boolean) => ThreadItem[]
toolInvocations: (foldedThread: FoldedThread) => Map<string, ToolInvocation>
isThinking: (
@@ -2180,6 +2184,16 @@ export const runStreamLogic = kea<runStreamLogicType>([
(s) => [s.log, s.isBootstrapResumeRun],
(log: RunLog, isResumeRun: boolean): FoldedThread => foldLogToThread(log.entries, { isResumeRun }),
],
+ latestTurnTraceId: [
+ (s) => [s.threadItems],
+ (threadItems: ThreadItem[]): string | null => {
+ // Trailer-derived, not the raw last separator: synthetic trailing separators
+ // (idle-resume/error frames) carry no trace id and are not turns.
+ const trailers = computeTurnTrailers(threadItems)
+ const lastTurn = [...trailers.values()].find((trailer) => trailer.isLastTurn)
+ return lastTurn?.traceId ?? null
+ },
+ ],
threadItems: [
(s) => [s.foldedThread, s.showDebugLogs],
(foldedThread: FoldedThread, showDebugLogs: boolean): ThreadItem[] =>
diff --git a/products/posthog_ai/frontend/types/streamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.ts
index 0f59831a4c65..3ddf416824c8 100644
--- a/products/posthog_ai/frontend/types/streamTypes.ts
+++ b/products/posthog_ai/frontend/types/streamTypes.ts
@@ -160,6 +160,8 @@ export interface ThreadItem {
contextSize?: number
/** For `task_notification` items — the milestone summary. */
summary?: string
+ /** For `turn_separator` items — the turn's gateway trace id (`$ai_trace_id` on its generations). */
+ traceId?: string
/** For `progress` items — backend-supplied group id, scoped to the task run. */
progressGroup?: string
/** For `progress` items — ordered setup/runtime progress rows. */
diff --git a/products/posthog_ai/frontend/types/wireTypes.ts b/products/posthog_ai/frontend/types/wireTypes.ts
index 78fa712b569f..5b8e0140baca 100644
--- a/products/posthog_ai/frontend/types/wireTypes.ts
+++ b/products/posthog_ai/frontend/types/wireTypes.ts
@@ -397,6 +397,8 @@ export interface PosthogRunStartedParams {
export interface PosthogTurnCompleteParams {
sessionId?: string
stopReason?: string
+ /** The turn's gateway trace id, when the agent's traceparent hook reported one. */
+ traceId?: string
}
export interface PosthogNotificationParamsByMethod {
diff --git a/products/posthog_ai/frontend/utils/turnTrailers.test.ts b/products/posthog_ai/frontend/utils/turnTrailers.test.ts
index 770f3e6df370..0061ebcc3b1a 100644
--- a/products/posthog_ai/frontend/utils/turnTrailers.test.ts
+++ b/products/posthog_ai/frontend/utils/turnTrailers.test.ts
@@ -6,11 +6,11 @@ function item(type: ThreadItem['type'], id: string, text?: string): ThreadItem {
}
describe('computeTurnTrailers', () => {
- it('assigns stable ordinals and per-turn text across multiple turns', () => {
+ it('assigns stable ordinals, per-turn text, and per-turn trace ids across multiple turns', () => {
const trailers = computeTurnTrailers([
item('human_message', 'h0', 'q1'),
item('assistant_message', 'a0', 'first answer'),
- item('turn_separator', 'turn-0'),
+ { ...item('turn_separator', 'turn-0'), traceId: 'trace-a' },
item('human_message', 'h1', 'q2'),
item('assistant_thought', 't0', 'thinking'),
item('assistant_message', 'a1', 'second answer'),
@@ -18,11 +18,17 @@ describe('computeTurnTrailers', () => {
item('turn_separator', 'turn-1'),
])
- expect(trailers.get('turn-0')).toEqual({ turnIndex: 0, isLastTurn: false, turnText: 'first answer' })
+ expect(trailers.get('turn-0')).toEqual({
+ turnIndex: 0,
+ isLastTurn: false,
+ turnText: 'first answer',
+ traceId: 'trace-a',
+ })
expect(trailers.get('turn-1')).toEqual({
turnIndex: 1,
isLastTurn: true,
turnText: 'second answer\n\ncontinued',
+ traceId: undefined,
})
})
diff --git a/products/posthog_ai/frontend/utils/turnTrailers.ts b/products/posthog_ai/frontend/utils/turnTrailers.ts
index f875b8bc9c0b..283a6f63553b 100644
--- a/products/posthog_ai/frontend/utils/turnTrailers.ts
+++ b/products/posthog_ai/frontend/utils/turnTrailers.ts
@@ -9,6 +9,8 @@ export interface TurnTrailer {
isLastTurn: boolean
/** The turn's assistant text, concatenated across its message bubbles. */
turnText: string
+ /** The turn's gateway trace id — `$ai_trace_id` on its generations and its feedback. */
+ traceId?: string
}
/**
@@ -33,7 +35,12 @@ export function computeTurnTrailers(threadItems: ThreadItem[]): Map<string, Turn
if (textParts.length === 0) {
continue
}
- trailers.set(item.id, { turnIndex, isLastTurn: false, turnText: textParts.join('\n\n') })
+ trailers.set(item.id, {
+ turnIndex,
+ isLastTurn: false,
+ turnText: textParts.join('\n\n'),
+ traceId: item.traceId,
+ })
lastSeparatorId = item.id
turnIndex += 1
textParts = []