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(aio): correlate cloud runner generations with run spans (#104702)

Jon McCallum0ac71d8b7334
diff --git a/products/desktop/packages/agent/README.md b/products/desktop/packages/agent/README.md
index 8c97d374f237..83aa9b0f3fcf 100644
--- a/products/desktop/packages/agent/README.md
+++ b/products/desktop/packages/agent/README.md
@@ -179,6 +179,11 @@ When set, `AgentServer` ships an allowlisted metadata subset of the session log
The `task_run` root span is ended and exported at the run's in-process terminal point — a background run's prompt settling, a terminal failure, or session cleanup (`close`). It cannot wait for teardown: agent-server is an exec'd process inside the sandbox, so `docker stop` / Modal terminate kill it without SIGTERM ever arriving, and a span still open at that moment is lost. Interactive sessions that end via hard teardown (e.g. inactivity timeout) therefore lose the root span; turn/tool spans and logs still assemble under the same trace id.
+When run tracing records spans, cloud Claude and Codex gateway requests include `task_run_trace_id` and `task_run_span_id` on their AI events.
+These fields identify the enclosing `task_run` span, preserve the existing `$ai_*` identity, and are omitted when tracing is disabled or sampled out.
+Both gateways accept these custom names; `$`-prefixed custom properties are reserved by the Go gateway.
+Resolve the hexadecimal IDs within the telemetry project, after the root span exports; export failure or hard teardown can leave the span unavailable.
+
## Agent SDK
The `Agent` class (`src/agent.ts`) is the entrypoint for local/programmatic usage. It handles LLM gateway configuration, log writer setup, and model filtering — then delegates to `createAcpConnection()`.
diff --git a/products/desktop/packages/agent/src/otel-telemetry.test.ts b/products/desktop/packages/agent/src/otel-telemetry.test.ts
index 7ad8ef91d548..c6039a6d41a3 100644
--- a/products/desktop/packages/agent/src/otel-telemetry.test.ts
+++ b/products/desktop/packages/agent/src/otel-telemetry.test.ts
@@ -66,6 +66,7 @@ interface ExportedLog {
interface ExportedSpan {
name: string;
+ resource: { attributes: Record<string, unknown> };
kind: number;
status: { code: number; message?: string };
attributes: Record<string, unknown>;
@@ -429,6 +430,28 @@ describe("OtelRunTelemetry", () => {
// Without a traces URL, no spans are built and logs carry no trace ids.
expect(mockSpanExport).not.toHaveBeenCalled();
expect(record.spanContext).toBeUndefined();
+ expect(telemetry.getRunSpanContext()).toBeUndefined();
+ });
+
+ it("omits correlation context when the run span is sampled out", async () => {
+ vi.stubEnv("OTEL_TRACES_SAMPLER", "always_off");
+ const unsampled = new OtelRunTelemetry(
+ {
+ url: "https://us.i.posthog.com/i/v1/logs",
+ token: "phc_test_key",
+ tracesUrl: "https://us.i.posthog.com/i/v1/traces",
+ },
+ RESOURCE,
+ );
+ try {
+ expect(unsampled.getRunSpanContext()).toBeUndefined();
+ unsampled.append(RUN_ID, makeEntry("session/prompt", {}));
+ await unsampled.shutdown();
+ expect(mockSpanExport).not.toHaveBeenCalled();
+ } finally {
+ await unsampled.shutdown();
+ vi.unstubAllEnvs();
+ }
});
it("never exports tool arguments, titles, or output content", async () => {
@@ -487,6 +510,7 @@ describe("OtelRunTelemetry", () => {
let telemetry: OtelRunTelemetry;
beforeEach(() => {
+ vi.stubEnv("OTEL_TRACES_SAMPLER", "always_on");
telemetry = new OtelRunTelemetry(
{
url: "https://us.i.posthog.com/i/v1/logs",
@@ -498,6 +522,11 @@ describe("OtelRunTelemetry", () => {
);
});
+ afterEach(async () => {
+ await telemetry.shutdown();
+ vi.unstubAllEnvs();
+ });
+
function driveSuccessfulRun(): void {
telemetry.append(RUN_ID, makeEntry("_posthog/run_started", {}));
telemetry.append(
@@ -541,15 +570,19 @@ describe("OtelRunTelemetry", () => {
}
it("builds a run trace: root span, turn span, tool span", async () => {
+ const runContext = telemetry.getRunSpanContext();
driveSuccessfulRun();
+ expect(telemetry.getRunSpanContext()).toEqual(runContext);
await telemetry.shutdown();
+ expect(telemetry.getRunSpanContext()).toBeUndefined();
const root = spanByName("task_run");
const turn = spanByName("turn");
const tool = spanByName("tool_call:execute");
expect(root.kind).toBe(SpanKind.SERVER);
+ expect(runContext).toEqual(root.spanContext());
expect(root.parentSpanContext).toBeUndefined();
expect(turn.parentSpanContext?.spanId).toBe(root.spanContext().spanId);
expect(tool.parentSpanContext?.spanId).toBe(turn.spanContext().spanId);
@@ -583,6 +616,54 @@ describe("OtelRunTelemetry", () => {
expect(surface).not.toContain(".env");
});
+ it("keeps correlation context attached to its run during concurrent turns", async () => {
+ const otherRunId = "run-other";
+ const other = new OtelRunTelemetry(
+ {
+ url: "https://us.i.posthog.com/i/v1/logs",
+ token: "phc_test_key",
+ tracesUrl: "https://us.i.posthog.com/i/v1/traces",
+ },
+ { ...RESOURCE, runId: otherRunId },
+ );
+ try {
+ const runContext = telemetry.getRunSpanContext();
+ const otherContext = other.getRunSpanContext();
+ expect(runContext?.traceId).not.toBe(otherContext?.traceId);
+ telemetry.append(RUN_ID, makeEntry("session/prompt", {}));
+ other.append(otherRunId, makeEntry("session/prompt", {}));
+ telemetry.append(
+ RUN_ID,
+ makeEntry("_posthog/turn_complete", { stopReason: "end_turn" }),
+ );
+ telemetry.append(RUN_ID, makeEntry("session/prompt", {}));
+ expect(telemetry.getRunSpanContext()).toEqual(runContext);
+ expect(other.getRunSpanContext()).toEqual(otherContext);
+
+ await Promise.all([telemetry.shutdown(), other.shutdown()]);
+
+ for (const [runId, context] of [
+ [RUN_ID, runContext],
+ [otherRunId, otherContext],
+ ] as const) {
+ expect(context).toBeDefined();
+ const runSpans = exportedSpans().filter(
+ (span) => span.resource.attributes.run_id === runId,
+ );
+ expect(
+ runSpans.find((span) => span.name === "task_run")?.spanContext(),
+ ).toEqual(context);
+ expect(
+ runSpans.every(
+ (span) => span.spanContext().traceId === context?.traceId,
+ ),
+ ).toBe(true);
+ }
+ } finally {
+ await Promise.all([telemetry.shutdown(), other.shutdown()]);
+ }
+ });
+
it("does not leave root OK when a later turn ends non-clean", async () => {
driveSuccessfulRun();
// Second turn gets cancelled: the latest outcome wins, so the earlier
@@ -698,6 +779,23 @@ describe("OtelRunTelemetry", () => {
expect(surface).not.toContain("SECRET");
});
+ it("makes a concurrent shutdown wait for the same flush", async () => {
+ const order: string[] = [];
+ mockLogShutdown.mockImplementationOnce(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ order.push("flushed");
+ });
+
+ await Promise.all([
+ telemetry.shutdown().then(() => order.push("first")),
+ telemetry.shutdown().then(() => order.push("second")),
+ ]);
+
+ expect(mockLogShutdown).toHaveBeenCalledOnce();
+ expect(order[0]).toBe("flushed");
+ expect(order).toContain("second");
+ });
+
it("shuts down logs even when the traces endpoint fails", async () => {
mockSpanShutdown.mockRejectedValueOnce(new Error("traces endpoint down"));
telemetry.append(RUN_ID, makeEntry("_posthog/run_started", {}));
diff --git a/products/desktop/packages/agent/src/otel-telemetry.ts b/products/desktop/packages/agent/src/otel-telemetry.ts
index aa9bccc237be..c5cda4c9cdff 100644
--- a/products/desktop/packages/agent/src/otel-telemetry.ts
+++ b/products/desktop/packages/agent/src/otel-telemetry.ts
@@ -1,3 +1,4 @@
+import type { SpanContext } from "@opentelemetry/api";
import { SeverityNumber } from "@opentelemetry/api-logs";
import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
import { resourceFromAttributes } from "@opentelemetry/resources";
@@ -276,6 +277,7 @@ export class OtelRunTelemetry implements SessionLogSink {
private runId: string;
private debugLogger?: Logger;
private shutdownStarted = false;
+ private shutdownPromise?: Promise<void>;
constructor(
config: OtelTelemetryConfig,
@@ -329,6 +331,10 @@ export class OtelRunTelemetry implements SessionLogSink {
}
}
+ getRunSpanContext(): SpanContext | undefined {
+ return this.traceBuilder?.getRunSpanContext();
+ }
+
append(sessionId: string, entry: StoredNotification): void {
// Resource attributes pin this writer to one run; ignore entries for any
// other session so records are never mislabeled.
@@ -365,14 +371,16 @@ export class OtelRunTelemetry implements SessionLogSink {
/**
* Ends open spans, flushes batched records, then stops the providers.
* Idempotent and best-effort: the two providers shut down independently
- * and a failure in one never skips the other. Never rejects.
+ * and a failure in one never skips the other. Never rejects. A second
+ * caller waits for the first flush rather than returning early, because the
+ * process can exit as soon as the last caller resolves.
*/
async shutdown(): Promise<void> {
- if (this.shutdownStarted) return;
this.shutdownStarted = true;
- await Promise.allSettled([
+ this.shutdownPromise ??= Promise.allSettled([
this.traceBuilder?.shutdown(),
this.loggerProvider.shutdown(),
- ]);
+ ]).then(() => undefined);
+ await this.shutdownPromise;
}
}
diff --git a/products/desktop/packages/agent/src/otel-trace-builder.ts b/products/desktop/packages/agent/src/otel-trace-builder.ts
index 23094c41ddae..2714cf3d8312 100644
--- a/products/desktop/packages/agent/src/otel-trace-builder.ts
+++ b/products/desktop/packages/agent/src/otel-trace-builder.ts
@@ -2,6 +2,7 @@ import {
type Context,
ROOT_CONTEXT,
type Span,
+ type SpanContext,
SpanKind,
SpanStatusCode,
type Tracer,
@@ -91,6 +92,12 @@ export class RunTraceBuilder {
this.rootContext = trace.setSpan(ROOT_CONTEXT, this.rootSpan);
}
+ getRunSpanContext(): SpanContext | undefined {
+ return this.rootSpan.isRecording()
+ ? this.rootSpan.spanContext()
+ : undefined;
+ }
+
/**
* Advances the span state machine with one stored entry and returns the
* context the entry's log record (if any) should attach to.
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 015a86e67c11..d2da7a051541 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
@@ -1,3 +1,4 @@
+import { type SpanContext, TraceFlags } from "@opentelemetry/api";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { GatewayEnv } from "../adapters/claude/session/options";
import type { Task } from "../types";
@@ -5,6 +6,7 @@ import { AgentServer, codexAuthFromGatewayEnv } from "./agent-server";
interface TestableServer {
configureEnvironment(args?: {
+ runSpanContext?: SpanContext;
isInternal?: boolean;
originProduct?: Task["origin_product"] | null;
signalReportId?: string | null;
@@ -24,6 +26,12 @@ interface TestableServer {
}): GatewayEnv;
}
+const RUN_SPAN_CONTEXT: SpanContext = {
+ traceId: "1234567890abcdef1234567890abcdef",
+ spanId: "1234567890abcdef",
+ traceFlags: TraceFlags.SAMPLED,
+};
+
const ENV_KEYS_UNDER_TEST = [
"LLM_GATEWAY_URL",
"POSTHOG_PROJECT_ID",
@@ -209,6 +217,7 @@ describe("AgentServer.configureEnvironment", () => {
// record. It carries both the selected project scope and event attribution.
it("forwards task metadata and project scope as openaiCustomHeaders", () => {
const env = buildServer("background").configureEnvironment({
+ runSpanContext: RUN_SPAN_CONTEXT,
isInternal: true,
originProduct: "signal_report",
signalReportId: "report-123",
@@ -227,6 +236,8 @@ describe("AgentServer.configureEnvironment", () => {
});
expect(env.openaiCustomHeaders).toEqual({
+ "x-posthog-property-task_run_trace_id": RUN_SPAN_CONTEXT.traceId,
+ "x-posthog-property-task_run_span_id": RUN_SPAN_CONTEXT.spanId,
"x-posthog-property-task_origin_product": "signal_report",
"x-posthog-property-task_internal": "true",
"x-posthog-property-signal_report_id": "report-123",
@@ -252,6 +263,7 @@ describe("AgentServer.configureEnvironment", () => {
it("forwards task metadata as anthropicCustomHeaders", () => {
const env = buildServer("background").configureEnvironment({
+ runSpanContext: RUN_SPAN_CONTEXT,
isInternal: true,
originProduct: "signal_report",
signalReportId: "report-123",
@@ -271,6 +283,8 @@ describe("AgentServer.configureEnvironment", () => {
expect(env.anthropicCustomHeaders).toBe(
[
+ `x-posthog-property-task_run_trace_id: ${RUN_SPAN_CONTEXT.traceId}`,
+ `x-posthog-property-task_run_span_id: ${RUN_SPAN_CONTEXT.spanId}`,
"x-posthog-property-task_origin_product: signal_report",
"x-posthog-property-task_internal: true",
"x-posthog-property-signal_report_id: report-123",
@@ -301,6 +315,8 @@ describe("AgentServer.configureEnvironment", () => {
expect(env.anthropicCustomHeaders).not.toContain("ai_stage");
expect(env.anthropicCustomHeaders).not.toContain("ai_agent_name");
+ expect(env.anthropicCustomHeaders).not.toContain("task_run_trace_id");
+ expect(env.anthropicCustomHeaders).not.toContain("task_run_span_id");
});
// A signals_scout title is multi-line; it must not inject extra header lines.
@@ -536,6 +552,7 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {
it("carries stage and team attribution in the blob for both adapters", () => {
const env = buildServer().configureEnvironment({
+ runSpanContext: RUN_SPAN_CONTEXT,
originProduct: "signal_report",
aiStage: "scout",
taskId: "task-1",
@@ -543,6 +560,8 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {
});
const expected = {
+ task_run_trace_id: RUN_SPAN_CONTEXT.traceId,
+ task_run_span_id: RUN_SPAN_CONTEXT.spanId,
task_origin_product: "signal_report",
task_internal: false,
ai_stage: "scout",
@@ -573,6 +592,9 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {
expect(Object.keys(env.openaiCustomHeaders ?? {})).toEqual([
"X-PostHog-Properties",
]);
+ const properties = parseBlob(env.anthropicCustomHeaders ?? "");
+ expect(properties).not.toHaveProperty("task_run_trace_id");
+ expect(properties).not.toHaveProperty("task_run_span_id");
});
// The gateway writes the tier into the OpenAI body from this header, so a
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index 28cf943fe4d4..07b777218dff 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -11,6 +11,8 @@ import {
import { tmpdir } from "node:os";
import { join } from "node:path";
import { type ContentBlock, RequestError } from "@agentclientprotocol/sdk";
+import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
+import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION as STE100_INSTRUCTION } from "@posthog/harness/extensions/benjamin";
import { type Adapter, IDLE_RESUME_STOP_REASON } from "@posthog/shared";
import { zipSync } from "fflate";
@@ -415,6 +417,159 @@ async function startInitialTaskMessage(
await startup.sendInitialTaskMessage(payload, prepared);
}
+it("links gateway requests to the run span exported after session shutdown", async () => {
+ const spans: { name: string; traceId: string; spanId: string }[] = [];
+ const logExport = vi
+ .spyOn(OTLPLogExporter.prototype, "export")
+ .mockImplementation((_logs, done) => done({ code: 0 }));
+ const spanExport = vi
+ .spyOn(OTLPTraceExporter.prototype, "export")
+ .mockImplementation((batch, done) => {
+ spans.push(
+ ...batch.map((span) => ({ name: span.name, ...span.spanContext() })),
+ );
+ done({ code: 0 });
+ });
+ const mswServer = setupServer(
+ ...createPostHogHandlers({ baseUrl: "http://localhost:8000" }),
+ http.get("https://gateway.us.posthog.com/*", () =>
+ HttpResponse.json({ data: [] }),
+ ),
+ );
+ const directory = await mkdtemp(join(tmpdir(), "agent-telemetry-"));
+ const server = new AgentServer({
+ port: getNextTestPort(),
+ jwtPublicKey: TEST_PUBLIC_KEY,
+ repositoryPath: directory,
+ apiUrl: "http://localhost:8000",
+ apiKey: "test-api-key",
+ projectId: 1,
+ mode: "interactive",
+ taskId: "test-task-id",
+ runId: "test-run-id",
+ resolveRtkSavings: async () => null,
+ otelLogsUrl: "http://otel.example.com/v1/logs",
+ otelLogsToken: "phc_test_key",
+ otelTracesUrl: "http://otel.example.com/v1/traces",
+ });
+ mswServer.listen({ onUnhandledRequest: "error" });
+ try {
+ vi.stubEnv("OTEL_TRACES_SAMPLER", "always_on");
+ for (const key of [
+ "LLM_GATEWAY_URL",
+ "AI_GATEWAY_URL",
+ "POSTHOG_API_KEY",
+ "POSTHOG_API_URL",
+ "POSTHOG_API_HOST",
+ "POSTHOG_AUTH_HEADER",
+ "POSTHOG_PROJECT_ID",
+ ]) {
+ vi.stubEnv(key, undefined);
+ }
+ mockedClaudeSdk.query.mockClear();
+ await server.start();
+
+ const request = mockedClaudeSdk.query.mock.lastCall?.[0] as unknown as {
+ options: { env: Record<string, string> };
+ };
+ const headers = request.options.env.ANTHROPIC_CUSTOM_HEADERS;
+ const traceId = headers.match(
+ /^x-posthog-property-task_run_trace_id: ([0-9a-f]{32})$/m,
+ )?.[1];
+ const spanId = headers.match(
+ /^x-posthog-property-task_run_span_id: ([0-9a-f]{16})$/m,
+ )?.[1];
+ expect(traceId).toBeDefined();
+ expect(spanId).toBeDefined();
+
+ await server.stop();
+
+ expect(spans.filter((span) => span.name === "task_run")).toEqual([
+ expect.objectContaining({ traceId, spanId }),
+ ]);
+ } finally {
+ try {
+ await server.stop();
+ } finally {
+ mswServer.close();
+ logExport.mockRestore();
+ spanExport.mockRestore();
+ vi.unstubAllEnvs();
+ await rm(directory, { recursive: true, force: true });
+ }
+ }
+}, 30000);
+
+it.each([false, true])(
+ "shuts down initialization telemetry (aborted: %s)",
+ async (aborted) => {
+ const append = vi.fn();
+ const shutdown = vi.fn(async () => {});
+ const testServer = new AgentServer({
+ port: 0,
+ jwtPublicKey: TEST_PUBLIC_KEY,
+ apiUrl: "http://localhost:8000",
+ apiKey: "test-api-key",
+ projectId: 1,
+ mode: "interactive",
+ taskId: "test-task-id",
+ runId: "test-run-id",
+ runtimeAdapter: "codex",
+ model: "gpt-5.2-codex",
+ }) as unknown as {
+ shutdownController: AbortController;
+ initializingTelemetry: {
+ append: typeof append;
+ shutdown: typeof shutdown;
+ };
+ _doInitializeSession(
+ payload: JwtPayload,
+ controller: null,
+ ): Promise<void>;
+ initializeSession(payload: JwtPayload, controller: null): Promise<void>;
+ };
+ testServer._doInitializeSession = vi.fn(async () => {
+ testServer.initializingTelemetry = { append, shutdown };
+ if (aborted) testServer.shutdownController.abort();
+ throw new Error("SECRET provider response");
+ });
+ const payload = {
+ task_id: "test-task-id",
+ run_id: "test-run-id",
+ team_id: 1,
+ user_id: 1,
+ distinct_id: "test-distinct-id",
+ mode: "interactive" as const,
+ };
+
+ await expect(testServer.initializeSession(payload, null)).rejects.toThrow(
+ "SECRET provider response",
+ );
+
+ if (aborted) {
+ expect(append).not.toHaveBeenCalled();
+ } else {
+ expect(append).toHaveBeenCalledWith(
+ "test-run-id",
+ expect.objectContaining({
+ notification: expect.objectContaining({
+ method: POSTHOG_NOTIFICATIONS.INITIALIZATION_FAILED,
+ params: expect.objectContaining({
+ runtimeAdapter: "codex",
+ initializationPhase: "session_setup",
+ requestedModel: "gpt-5.2-codex",
+ errorType: "error",
+ }),
+ }),
+ }),
+ );
+ }
+ expect(JSON.stringify(append.mock.calls)).not.toContain("SECRET");
+ expect(shutdown).toHaveBeenCalledOnce();
+ expect(testServer.initializingTelemetry).toBeUndefined();
+ },
+);
+
describe("AgentServer HTTP Mode", () => {
let repo: TestRepo;
let server: AgentServer | undefined;
@@ -493,58 +648,6 @@ describe("AgentServer HTTP Mode", () => {
);
};
- it("exports safe telemetry when session initialization fails", async () => {
- const append = vi.fn();
- const shutdown = vi.fn(async () => {});
- const testServer = createServer({
- runtimeAdapter: "codex",
- model: "gpt-5.2-codex",
- }) as unknown as {
- initializingTelemetry: {
- append: typeof append;
- shutdown: typeof shutdown;
- };
- _doInitializeSession(
- payload: JwtPayload,
- controller: null,
- ): Promise<void>;
- initializeSession(payload: JwtPayload, controller: null): Promise<void>;
- };
- testServer._doInitializeSession = vi.fn(async () => {
- testServer.initializingTelemetry = { append, shutdown };
- throw new Error("SECRET provider response");
- });
- const payload = {
- task_id: "test-task-id",
- run_id: "test-run-id",
- team_id: 1,
- user_id: 1,
- distinct_id: "test-distinct-id",
- mode: "interactive" as const,
- };
-
- await expect(testServer.initializeSession(payload, null)).rejects.toThrow(
- "SECRET provider response",
- );
-
- expect(append).toHaveBeenCalledWith(
- "test-run-id",
- expect.objectContaining({
- notification: expect.objectContaining({
- method: POSTHOG_NOTIFICATIONS.INITIALIZATION_FAILED,
- params: expect.objectContaining({
- runtimeAdapter: "codex",
- initializationPhase: "session_setup",
- requestedModel: "gpt-5.2-codex",
- errorType: "error",
- }),
- }),
- }),
- );
- expect(JSON.stringify(append.mock.calls)).not.toContain("SECRET");
- expect(shutdown).toHaveBeenCalledOnce();
- });
-
it("replays ACP notifications emitted before cloud session assignment", () => {
const testServer = createServer() as unknown as {
session: { sseController: null } | null;
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 3f50583d6c86..7441e4c2ae44 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -15,6 +15,7 @@ import {
RequestError,
} from "@agentclientprotocol/sdk";
import { type ServerType, serve } from "@hono/node-server";
+import type { SpanContext } from "@opentelemetry/api";
import { execGh } from "@posthog/git/gh";
import { getCurrentBranch, getRemoteUrl } from "@posthog/git/queries";
import { ghTokenEnv } from "@posthog/git/signed-commit";
@@ -1129,6 +1130,12 @@ export class AgentServer {
Promise.resolve()),
5_000,
);
+ // An abort during initialization leaves the root span open with no session
+ // to carry it, and the caller exits the process as soon as this returns.
+ await withTimeout(
+ this.initializingTelemetry?.shutdown() ?? Promise.resolve(),
+ 5_000,
+ );
} finally {
this.server?.close();
this.server = null;
@@ -1865,9 +1872,9 @@ export class AgentServer {
},
},
});
- await telemetry?.shutdown();
throw error;
} finally {
+ await this.initializingTelemetry?.shutdown();
await this.cleanupInitializingConnection();
this.initializingConnection = null;
this.initializingTelemetry = undefined;
@@ -1986,7 +1993,15 @@ export class AgentServer {
const runtimeAdapter = this.getRuntimeAdapter();
+ const telemetry = this.createRunTelemetry(
+ payload,
+ deviceInfo,
+ runtimeAdapter,
+ );
+ this.initializingTelemetry = telemetry;
+
const gatewayEnv = this.configureEnvironment({
+ runSpanContext: telemetry?.getRunSpanContext(),
isInternal: preTask?.internal === true,
originProduct: preTask?.origin_product,
signalReportId: preTask?.signal_report,
@@ -2088,13 +2103,6 @@ export class AgentServer {
userAgent: `posthog/cloud.hog.dev; version: ${this.config.version ?? packageJson.version}`,
});
- const telemetry = this.createRunTelemetry(
- payload,
- deviceInfo,
- runtimeAdapter,
- );
- this.initializingTelemetry = telemetry;
-
const logWriter = new SessionLogWriter({
posthogAPI,
logger: new Logger({ debug: true, prefix: "[SessionLogWriter]" }),
@@ -4658,6 +4666,7 @@ export class AgentServer {
}
private configureEnvironment({
+ runSpanContext,
isInternal = false,
originProduct,
signalReportId,
@@ -4675,6 +4684,7 @@ export class AgentServer {
prewarmed,
executionEnvironment,
}: {
+ runSpanContext?: SpanContext;
isInternal?: boolean;
originProduct?: Task["origin_product"] | null;
signalReportId?: string | null;
@@ -4732,6 +4742,9 @@ export class AgentServer {
// path sets them as `model_providers.posthog.http_headers` instead, so we
// also expose the record form below.
const gatewayProperties = {
+ // Gateway headers live for the session, so correlate with its enclosing run.
+ task_run_trace_id: runSpanContext?.traceId,
+ task_run_span_id: runSpanContext?.spanId,
task_origin_product: originProduct,
task_internal: isInternal,
signal_report_id: signalReportId,