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(desktop): enable rich output prompts across runtimes (#86171)

Shy Alterb95962aa6b40
diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts
index 4d8c772cca92..d600a81f9020 100644
--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts
+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts
@@ -93,7 +93,6 @@ describe("DesktopPiRpcClientFactory", () => {
enrichment: {
apiUrl: "http://127.0.0.1:5678",
publicApiUrl: "https://eu.posthog.com",
- enableObjectReferences: true,
projectId: 1,
apiKey: "posthog-code-auth-proxy",
},
diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts
index 68d65ba44b91..acef96807a54 100644
--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts
+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts
@@ -61,7 +61,6 @@ export class DesktopPiRpcClientFactory implements PiRpcClientFactory {
enrichment: {
apiUrl: enrichmentApiUrl,
publicApiUrl: access.apiHost,
- enableObjectReferences: true,
projectId,
apiKey: PROXY_API_KEY,
},
diff --git a/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts b/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts
index b69042e2fcd5..41d256ece05e 100644
--- a/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts
+++ b/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts
@@ -229,7 +229,6 @@ test.describe("Pi enrichment", () => {
enrichment: {
apiUrl: baseUrl,
publicApiUrl: "https://us.posthog.com",
- enableObjectReferences: true,
projectId: 1,
apiKey: "posthog-test-key",
},
diff --git a/products/desktop/packages/agent/src/pi/enrichment-extension.test.ts b/products/desktop/packages/agent/src/pi/enrichment-extension.test.ts
index 8b08e55166c2..5f670594edeb 100644
--- a/products/desktop/packages/agent/src/pi/enrichment-extension.test.ts
+++ b/products/desktop/packages/agent/src/pi/enrichment-extension.test.ts
@@ -21,7 +21,7 @@ describe("createPiEnrichmentExtension", () => {
vi.unstubAllGlobals();
});
- it("adds live PostHog metadata to Pi read results", async () => {
+ it("adds rich-output instructions and live metadata to Pi", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (input: string | URL | Request) => {
@@ -52,7 +52,6 @@ describe("createPiEnrichmentExtension", () => {
let beforeAgentStartHandler: BeforeAgentStartHandler | undefined;
const extension = createPiEnrichmentExtension({
apiUrl: "https://us.posthog.com",
- enableObjectReferences: true,
projectId: 1,
apiKey: "token",
});
@@ -98,26 +97,4 @@ describe("createPiEnrichmentExtension", () => {
},
]);
});
-
- it("does not add object-tag guidance unless enabled", async () => {
- let beforeAgentStartHandler: BeforeAgentStartHandler | undefined;
- const extension = createPiEnrichmentExtension({
- apiUrl: "https://us.posthog.com",
- projectId: 1,
- apiKey: "token",
- });
- await extension.factory({
- on: (
- event: string,
- registeredHandler: ToolResultHandler | BeforeAgentStartHandler,
- ) => {
- if (event === "before_agent_start") {
- beforeAgentStartHandler =
- registeredHandler as BeforeAgentStartHandler;
- }
- },
- } as unknown as ExtensionAPI);
-
- expect(beforeAgentStartHandler).toBeUndefined();
- });
});
diff --git a/products/desktop/packages/agent/src/pi/enrichment-extension.ts b/products/desktop/packages/agent/src/pi/enrichment-extension.ts
index ff3dc2afbe71..58c32b5d9155 100644
--- a/products/desktop/packages/agent/src/pi/enrichment-extension.ts
+++ b/products/desktop/packages/agent/src/pi/enrichment-extension.ts
@@ -4,7 +4,7 @@ import {
type ExtensionFactory,
isReadToolResult,
} from "@earendil-works/pi-coding-agent";
-import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/shared/rich-output-prompt";
+import { appendRichOutputPrompt } from "@posthog/shared/rich-output-prompt";
import {
createEnrichment,
enrichFileForAgent,
@@ -13,7 +13,6 @@ import {
export interface PiEnrichmentConfig {
apiUrl: string;
publicApiUrl?: string;
- enableObjectReferences?: boolean;
projectId: number;
apiKey: string;
}
@@ -25,11 +24,9 @@ export function createPiEnrichmentExtension(config: PiEnrichmentConfig): {
return {
name: "posthog-enricher",
factory: (pi: ExtensionAPI) => {
- if (config.enableObjectReferences) {
- pi.on("before_agent_start", (event) => ({
- systemPrompt: `${event.systemPrompt}\n\n## Rich output in replies\n${RICH_OUTPUT_TAGS_PROMPT}`,
- }));
- }
+ pi.on("before_agent_start", (event) => ({
+ systemPrompt: appendRichOutputPrompt(event.systemPrompt),
+ }));
const enrichment = createEnrichment({
apiUrl: config.apiUrl,
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 57705bd0ad02..1e132cf5a377 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -34,6 +34,7 @@ import {
buildPosthogScopedPropertyHeaderLines,
buildPosthogScopedPropertyHeaderRecord,
} from "@posthog/shared/posthog-property-headers";
+import { appendRichOutputPrompt } from "@posthog/shared/rich-output-prompt";
import { unzipSync } from "fflate";
import { Hono } from "hono";
import { z } from "zod";
@@ -122,7 +123,7 @@ import {
jsonRpcRequestSchema,
validateCommandParams,
} from "./schemas";
-import type { AgentServerConfig } from "./types";
+import type { AgentServerConfig, ClaudeCodeConfig } from "./types";
const agentErrorClassificationSchema = z.enum([
"upstream_stream_terminated",
@@ -161,6 +162,18 @@ const UPSTREAM_TURN_RETRY_DELAY_MS = 5_000;
const PENDING_ARTIFACT_MAX_ATTEMPTS = 4;
const PENDING_ARTIFACT_RETRY_DELAY_MS = 500;
+export function buildCloudSessionSystemPrompt(
+ cloudAppend: string,
+ userPrompt: ClaudeCodeConfig["systemPrompt"],
+): string | { append: string } {
+ if (typeof userPrompt === "string") {
+ return appendRichOutputPrompt([userPrompt, cloudAppend].join("\n\n"));
+ }
+
+ const prompt = [userPrompt?.append, cloudAppend].filter(Boolean).join("\n\n");
+ return { append: appendRichOutputPrompt(prompt) };
+}
+
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -3472,20 +3485,7 @@ export class AgentServer {
);
const userPrompt = this.config.claudeCode?.systemPrompt;
- // String override: combine user prompt with cloud instructions
- if (typeof userPrompt === "string") {
- return [userPrompt, cloudAppend].join("\n\n");
- }
-
- // Preset with append: merge user append with cloud instructions
- if (typeof userPrompt === "object") {
- return {
- append: [userPrompt.append, cloudAppend].filter(Boolean).join("\n\n"),
- };
- }
-
- // Default: just cloud instructions
- return { append: cloudAppend };
+ return buildCloudSessionSystemPrompt(cloudAppend, userPrompt);
}
private buildCodexInstructions(
diff --git a/products/desktop/packages/agent/src/server/cloud-session-prompt.test.ts b/products/desktop/packages/agent/src/server/cloud-session-prompt.test.ts
new file mode 100644
index 000000000000..59b762c76e2c
--- /dev/null
+++ b/products/desktop/packages/agent/src/server/cloud-session-prompt.test.ts
@@ -0,0 +1,26 @@
+import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/shared/rich-output-prompt";
+import { describe, expect, it } from "vitest";
+import { buildCloudSessionSystemPrompt } from "./agent-server";
+
+describe("buildCloudSessionSystemPrompt", () => {
+ it.each([
+ ["the default prompt", undefined],
+ ["a string override", "Answer in JSON."],
+ [
+ "a preset override",
+ {
+ type: "preset" as const,
+ preset: "claude_code" as const,
+ append: "Use the canvas tools.",
+ },
+ ],
+ ])("includes rich-output instructions for %s", (_name, userPrompt) => {
+ const prompt = buildCloudSessionSystemPrompt(
+ "Cloud task instructions.",
+ userPrompt,
+ );
+ const text = typeof prompt === "string" ? prompt : prompt.append;
+
+ expect(text).toContain(RICH_OUTPUT_TAGS_PROMPT);
+ });
+});
diff --git a/products/desktop/packages/shared/src/rich-output-prompt.ts b/products/desktop/packages/shared/src/rich-output-prompt.ts
index 8635a3376f18..693f734289bb 100644
--- a/products/desktop/packages/shared/src/rich-output-prompt.ts
+++ b/products/desktop/packages/shared/src/rich-output-prompt.ts
@@ -1,11 +1,18 @@
/**
* Prompt block teaching an agent the object-tag vocabulary the desktop
- * renders as live references (chips, hover previews, chart cards). Embedded
- * by the local agent's system prompt and the quick-ask steering, so the
- * taught syntax stays in sync with what `remarkObjectTags` parses.
+ * renders as live references (chips, hover previews, chart cards). Shared by
+ * every agent runtime so its syntax stays in sync with what `remarkObjectTags`
+ * parses.
*/
export const RICH_OUTPUT_TAGS_PROMPT = `Embed the PostHog objects behind your conclusions as XML tags, the same convention as \`<file path="..."/>\` attachments. Every tag is a live reference the app resolves when shown - never restate the object's data in your text, and never put tags inside code fences.
- Inline reference: \`<kind id="...">short human label</kind>\` inside a sentence, e.g. \`The <insight id="9pQx3">checkout funnel</insight> dropped after <flag id="42">new-checkout-flow</flag> rolled out.\` Kinds: insight, dashboard, error, replay, flag, experiment, survey, ticket, trace, eval, event, cohort, action, person. Use the object's id (insights: the short id; feature flags: the numeric id, falling back to the key; persons: the uuid). It renders as a chip with a live hover preview that opens the object in PostHog.
- Inline SQL: \`<hogql label="signups today">SELECT count() FROM events WHERE ...</hogql>\` - the SQL is the tag body, the label is what the sentence shows. Hovering runs the query live; clicking opens the SQL editor.
- Full-size chart, for any numeric or time-series answer (always prefer this over a markdown table): a saved insight \`<insight id="9pQx3" display="block"/>\` or a query \`<hogql display="block" title="Daily active users, last 7 days" caption="optional context">SELECT ...</hogql>\`. The chart executes live on every view. Include the time range in the title, and keep blank lines out of the SQL body.
- Recording card: \`<replay id="<session_id>" display="block"/>\` renders the recording's details with a link into PostHog's player. Use it when a specific session is the evidence.`;
+
+export function appendRichOutputPrompt(prompt: string): string {
+ if (prompt.includes(RICH_OUTPUT_TAGS_PROMPT)) {
+ return prompt;
+ }
+ return `${prompt}\n\n## Rich output in replies\n${RICH_OUTPUT_TAGS_PROMPT}`;
+}
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 8f9b4a860026..7cb81a311961 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
@@ -1014,7 +1014,7 @@ describe("AgentService", () => {
describe("channel system prompt repository isolation", () => {
const credentials = { apiHost: "https://app.posthog.com", projectId: 1 };
- function buildChannelPrompt(): string {
+ function buildChannelPrompt(systemPromptOverride?: string): string {
return (
service as unknown as {
buildSystemPrompt: (
@@ -1031,14 +1031,22 @@ describe("AgentService", () => {
"task-1",
undefined,
undefined,
- undefined,
+ systemPromptOverride,
true,
).append;
}
- it("uses the shared object-reference prompt", () => {
- expect(buildChannelPrompt()).toContain(RICH_OUTPUT_TAGS_PROMPT);
- });
+ it.each([
+ ["default", undefined],
+ ["overridden", "Generate a canvas."],
+ ])(
+ "uses the shared object-reference prompt for a %s session",
+ (_name, systemPromptOverride) => {
+ expect(buildChannelPrompt(systemPromptOverride)).toContain(
+ RICH_OUTPUT_TAGS_PROMPT,
+ );
+ },
+ );
it("requires a task-specific clone instead of an existing checkout", () => {
const prompt = buildChannelPrompt();
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 c6f7bfdf2f57..8c29492cbd2e 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
@@ -75,7 +75,7 @@ import {
serializeError,
TypedEventEmitter,
} from "@posthog/shared";
-import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/shared/rich-output-prompt";
+import { appendRichOutputPrompt } from "@posthog/shared/rich-output-prompt";
import { inject, injectable, preDestroy } from "inversify";
import { WORKSPACE_REPOSITORY } from "../../db/identifiers";
import type { IWorkspaceRepository } from "../../db/repositories/workspace-repository";
@@ -626,10 +626,9 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
): {
append: string;
} {
- // A constrained surface (e.g. the canvas generator) supplies its own prompt
- // and does NOT want the default coding/attribution guidance.
+ // Overrides replace coding guidance, but rich tags must stay available in every agent response.
if (systemPromptOverride) {
- return { append: systemPromptOverride };
+ return { append: appendRichOutputPrompt(systemPromptOverride) };
}
let prompt = `PostHog context: use project ${credentials.projectId} on ${credentials.apiHost}. When using PostHog MCP tools, operate only on this project.`;
@@ -674,8 +673,7 @@ Optimize for the fewest shell round trips.
- Read multiple files at once.
- Never rerun a command solely to reproduce output you already have.
-## Rich output in replies
-${RICH_OUTPUT_TAGS_PROMPT}`;
+`;
if (channelMode) {
prompt += `
@@ -703,7 +701,7 @@ If a repository is required, call \`list_repos\` to find it, then use \`clone_re
prompt += `\n\nThe user has granted you access to additional directories outside the working directory. You may read and edit files in these paths just like the working directory:\n<additional_directories>\n${dirs}\n</additional_directories>`;
}
- return { append: prompt };
+ return { append: appendRichOutputPrompt(prompt) };
}
async startSession(params: StartSessionInput): Promise<SessionResponse> {