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(desktop): send span name and session id as headers on the go gateway (#116544)

Brandon8218ef6acfbe
diff --git a/packages/agent/packages/agent-contracts/src/posthog-property-headers.test.ts b/packages/agent/packages/agent-contracts/src/posthog-property-headers.test.ts
index 0e13a16d013d..4c75b725b2ce 100644
--- a/packages/agent/packages/agent-contracts/src/posthog-property-headers.test.ts
+++ b/packages/agent/packages/agent-contracts/src/posthog-property-headers.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import {
+ buildAiGatewayReservedHeaders,
buildPosthogProjectHeaderLines,
buildPosthogProjectHeaderRecord,
buildPosthogPropertiesBlob,
@@ -449,6 +450,32 @@ describe("collapsePropertyHeadersForAiGateway", () => {
);
});
+ it("lifts $ai_span_name into the span name header", () => {
+ const out = collapsePropertyHeadersForAiGateway(
+ { "x-posthog-property-$ai_span_name": "commit_message" },
+ { ai_product: "posthog_code", team_id: 7 },
+ );
+ expect(out["X-PostHog-Span-Name"]).toBe("commit_message");
+ expect(JSON.parse(out["X-PostHog-Properties"])).not.toHaveProperty(
+ "$ai_span_name",
+ );
+ });
+
+ it("prefers a dedicated header over the same key sent as a property", () => {
+ const out = collapsePropertyHeadersForAiGateway(
+ {
+ "x-posthog-span-name": "from_header",
+ "x-posthog-property-$ai_span_name": "from_property",
+ "x-posthog-session-id": "s-header",
+ "x-posthog-property-$ai_session_id": "s-property",
+ },
+ { ai_product: "posthog_code", team_id: 7 },
+ );
+ expect(out["X-PostHog-Span-Name"]).toBe("from_header");
+ expect(out["X-PostHog-Session-Id"]).toBe("s-header");
+ expect(out).not.toHaveProperty("x-posthog-span-name");
+ });
+
it("keeps the trusted keys when the client's values overflow the cap", () => {
const out = collapsePropertyHeadersForAiGateway(
{
@@ -507,3 +534,35 @@ describe("collapsePropertyHeadersForAiGateway", () => {
});
});
});
+
+describe("buildAiGatewayReservedHeaders", () => {
+ it("maps the reserved keys to the Go gateway's dedicated headers", () => {
+ expect(
+ buildAiGatewayReservedHeaders({
+ $ai_session_id: "task-1",
+ $ai_span_name: "pr_description",
+ task_id: "ignored",
+ }),
+ ).toEqual({
+ "X-PostHog-Session-Id": "task-1",
+ "X-PostHog-Span-Name": "pr_description",
+ });
+ });
+
+ it("omits empty or missing values", () => {
+ expect(
+ buildAiGatewayReservedHeaders({
+ $ai_session_id: "",
+ $ai_span_name: null,
+ }),
+ ).toEqual({});
+ });
+
+ it("sanitizes values so they cannot inject headers", () => {
+ expect(
+ buildAiGatewayReservedHeaders({ $ai_span_name: "a\r\nX-Evil: 1" })[
+ "X-PostHog-Span-Name"
+ ],
+ ).not.toMatch(/[\r\n]/);
+ });
+});
diff --git a/packages/agent/packages/agent-contracts/src/posthog-property-headers.ts b/packages/agent/packages/agent-contracts/src/posthog-property-headers.ts
index e6d84802a6e7..a142275d9ae1 100644
--- a/packages/agent/packages/agent-contracts/src/posthog-property-headers.ts
+++ b/packages/agent/packages/agent-contracts/src/posthog-property-headers.ts
@@ -244,6 +244,28 @@ export function buildPosthogSessionHeaderLines(
.join("\n");
}
+/** Span name header the Go gateway reads, for the same reason. */
+export const POSTHOG_SPAN_NAME_HEADER = "X-PostHog-Span-Name";
+
+const RESERVED_PROPERTY_HEADERS: ReadonlyArray<[string, string]> = [
+ ["$ai_session_id", POSTHOG_SESSION_ID_HEADER],
+ ["$ai_span_name", POSTHOG_SPAN_NAME_HEADER],
+];
+
+/** Go gateway headers for the reserved `$ai_*` keys the blob drops. */
+export function buildAiGatewayReservedHeaders(
+ properties: PosthogProperties,
+): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [key, header] of RESERVED_PROPERTY_HEADERS) {
+ const raw = properties[key];
+ if (raw === null || raw === undefined || raw === "") continue;
+ const value = sanitizeHeaderValue(String(raw));
+ if (value) out[header] = value;
+ }
+ return out;
+}
+
const PROPERTY_HEADER_PREFIX = "x-posthog-property-";
function parsePropertiesBlob(raw: string): PosthogProperties {
@@ -275,15 +297,18 @@ export function collapsePropertyHeadersForAiGateway(
const out: Record<string, string> = {};
const fromHeaders: PosthogProperties = {};
let fromBlob: PosthogProperties = {};
- let sessionId: string | undefined;
+ const reserved: PosthogProperties = {};
for (const [key, value] of Object.entries(headers)) {
const lower = key.toLowerCase();
+ const reservedKey = RESERVED_PROPERTY_HEADERS.find(
+ ([, header]) => header.toLowerCase() === lower,
+ )?.[0];
if (lower.startsWith(PROPERTY_HEADER_PREFIX)) {
fromHeaders[lower.slice(PROPERTY_HEADER_PREFIX.length)] = value;
} else if (lower === POSTHOG_PROPERTIES_HEADER.toLowerCase()) {
fromBlob = parsePropertiesBlob(value);
- } else if (lower === POSTHOG_SESSION_ID_HEADER.toLowerCase()) {
- sessionId = value;
+ } else if (reservedKey) {
+ reserved[reservedKey] = value;
} else {
out[key] = value;
}
@@ -310,10 +335,15 @@ export function collapsePropertyHeadersForAiGateway(
if (lostTrusted) blob = buildPosthogPropertiesBlob(trusted);
if (blob) out[POSTHOG_PROPERTIES_HEADER] = blob;
- const session = sessionId ?? merged.$ai_session_id;
- if (session !== null && session !== undefined && session !== "") {
- const value = sanitizeHeaderValue(String(session));
- if (value) out[POSTHOG_SESSION_ID_HEADER] = value;
- }
- return out;
+ // A dedicated header wins over the same key sent as a property.
+ return {
+ ...out,
+ ...buildAiGatewayReservedHeaders({
+ $ai_session_id: merged.$ai_session_id,
+ $ai_span_name: merged.$ai_span_name,
+ ...Object.fromEntries(
+ Object.entries(reserved).filter(([, v]) => v !== ""),
+ ),
+ }),
+ };
}
diff --git a/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts b/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts
index 89847414961a..4784521c70e7 100644
--- a/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts
+++ b/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts
@@ -214,6 +214,7 @@ describe("LlmGatewayService.prompt", () => {
"x-posthog-property-rich": "line one line two done ",
});
expect(init.headers).not.toHaveProperty("x-posthog-property-unused");
+ expect(init.headers).not.toHaveProperty("X-PostHog-Span-Name");
expect(init.headers).not.toHaveProperty("x-posthog-property-skipped");
});
@@ -579,9 +580,28 @@ describe("LlmGatewayService.prompt on the Go gateway", () => {
ai_product: "posthog_code",
team_id: 7,
});
+ expect(init.headers["X-PostHog-Span-Name"]).toBe("title");
+ expect(init.headers).not.toHaveProperty("X-PostHog-Session-Id");
expect(JSON.parse(init.body).model).toBe("claude-haiku-4-5");
});
+ it("sends a caller's session id in the session header", async () => {
+ const goFetch = vi.fn().mockResolvedValue(createJsonResponse(SUCCESS_BODY));
+ const { service } = createService(vi.fn(), {
+ route: GO_ROUTE,
+ fetch: goFetch,
+ });
+
+ await service.prompt([{ role: "user", content: "hi" }], {
+ model: "claude-haiku-4-5",
+ posthogProperties: { $ai_session_id: "task-9" },
+ });
+
+ expect(goFetch.mock.calls[0][1].headers["X-PostHog-Session-Id"]).toBe(
+ "task-9",
+ );
+ });
+
it("sends a default max_tokens when the caller passes none", async () => {
const goFetch = vi.fn().mockResolvedValue(createJsonResponse(SUCCESS_BODY));
const { service } = createService(vi.fn(), {
diff --git a/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts b/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts
index 5d14f7dd4300..2909200619f8 100644
--- a/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts
+++ b/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts
@@ -6,6 +6,7 @@ import {
isAnthropicModelId,
} from "@posthog/shared";
import {
+ buildAiGatewayReservedHeaders,
buildPosthogProjectHeaderRecord,
buildPosthogPropertiesHeaderRecord,
buildPosthogPropertyHeaderRecord,
@@ -222,11 +223,14 @@ export class LlmGatewayService {
Authorization: `Bearer ${current.token}`,
},
}),
- buildPosthogPropertiesHeaderRecord({
- ...options.posthogProperties,
- ai_product: "posthog_code",
- team_id: current.teamId,
- }),
+ {
+ ...buildPosthogPropertiesHeaderRecord({
+ ...options.posthogProperties,
+ ai_product: "posthog_code",
+ team_id: current.teamId,
+ }),
+ ...buildAiGatewayReservedHeaders(options.posthogProperties ?? {}),
+ },
shape,
);
try {