: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): auto-publish Pi cloud runs (#81074)
Alessandro Pogliaghi61e3cb0c421b
diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.test.ts b/products/desktop/packages/agent/src/server/pi-agent-server.test.tsindex 61d809ed2099..adf63d8cd67a 100644--- a/products/desktop/packages/agent/src/server/pi-agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/pi-agent-server.test.ts@@ -304,6 +304,100 @@ describe("PiAgentServer", () => {});});+ it("injects auto-publish instructions into the first native Pi prompt", async () => {+ const sendCommand = vi.fn(+ async (_command: Record<string, unknown>) => ({}),+ );+ const server = new PiAgentServer(+ config({ autoPublish: true, createPr: true }),+ ) as unknown as {+ session: unknown;+ executeCommand(+ method: string,+ params: Record<string, unknown>,+ ): Promise<unknown>;+ };+ server.session = {+ runtime: {+ client: { getState: vi.fn(async () => ({ isStreaming: false })) },+ sendCommand,+ },+ };++ await server.executeCommand("user_message", { content: "fix it" });+ await server.executeCommand("user_message", { content: "one more thing" });++ expect(sendCommand.mock.calls[0]?.[0].message).toContain(+ "auto-publish enabled",+ );+ expect(sendCommand.mock.calls[0]?.[0].message).toContain(+ "gh pr create --draft",+ );+ expect(sendCommand.mock.calls[1]?.[0].message).toBe("one more thing");+ });++ it("retries Pi auto-publish instructions when the first send fails", async () => {+ const sendCommand = vi+ .fn(async (_command: Record<string, unknown>) => ({}))+ .mockRejectedValueOnce(new Error("send failed"));+ const server = new PiAgentServer(+ config({ autoPublish: true, createPr: true }),+ ) as unknown as {+ session: unknown;+ executeCommand(+ method: string,+ params: Record<string, unknown>,+ ): Promise<unknown>;+ };+ server.session = {+ runtime: {+ client: { getState: vi.fn(async () => ({ isStreaming: false })) },+ sendCommand,+ },+ };++ await expect(+ server.executeCommand("user_message", { content: "fix it" }),+ ).rejects.toThrow("send failed");+ await server.executeCommand("user_message", { content: "fix it" });++ expect(sendCommand.mock.calls[0]?.[0].message).toContain(+ "auto-publish enabled",+ );+ expect(sendCommand.mock.calls[1]?.[0].message).toContain(+ "auto-publish enabled",+ );+ });++ it.each([+ [{ autoPublish: false }, "auto-publish disabled"],+ [{ autoPublish: true, createPr: false }, "PR creation disabled"],+ ])(+ "does not inject Pi auto-publish instructions when %s",+ async (overrides, _label) => {+ const sendCommand = vi.fn(+ async (_command: Record<string, unknown>) => ({}),+ );+ const server = new PiAgentServer(config(overrides)) as unknown as {+ session: unknown;+ executeCommand(+ method: string,+ params: Record<string, unknown>,+ ): Promise<unknown>;+ };+ server.session = {+ runtime: {+ client: { getState: vi.fn(async () => ({ isStreaming: false })) },+ sendCommand,+ },+ };++ await server.executeCommand("user_message", { content: "fix it" });++ expect(sendCommand.mock.calls[0]?.[0].message).toBe("fix it");+ },+ );+it("hydrates cloud artifacts into native Pi prompt inputs", async () => {const repositoryPath = await mkdtemp(join(tmpdir(), "pi-attachments-"));const sendCommand = vi.fn(diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.ts b/products/desktop/packages/agent/src/server/pi-agent-server.tsindex 465fc8570f89..5b1e30824842 100644--- a/products/desktop/packages/agent/src/server/pi-agent-server.ts+++ b/products/desktop/packages/agent/src/server/pi-agent-server.ts@@ -127,6 +127,7 @@ export class PiAgentServer {private logFlushQueue: Promise<void> = Promise.resolve();private logFlushActive = false;private logFlushRequested = false;+ private autoPublishInstructionDelivered = false;private readonly canceledSseControllers = new WeakSet<SseController>();private readonly pendingMcpPermissions = new Map<string,@@ -704,13 +705,17 @@ export class PiAgentServer {typeof params.content === "string" ? params.content : "",artifacts,);- return this.dispatchUserMessage(+ const result = await this.dispatchUserMessage(runtime,message.content,message.images,typeof params.messageId === "string" ? params.messageId : randomUUID(),params.steer === true,);+ if (message.includesAutoPublishInstruction) {+ this.autoPublishInstructionDelivered = true;+ }+ return result;}private async prepareUserMessage(@@ -719,6 +724,7 @@ export class PiAgentServer {): Promise<{content: string;images: Parameters<PiRpcClient["prompt"]>[1];+ includesAutoPublishInstruction: boolean;}> {const images: NonNullable<Parameters<PiRpcClient["prompt"]>[1]> = [];const filePaths: string[] = [];@@ -762,12 +768,38 @@ export class PiAgentServer {const attachmentText = filePaths.length? `Attached files:\n${filePaths.map((filePath) => `- ${filePath}`).join("\n")}`: "";+ const autoPublishInstruction = this.buildAutoPublishInstruction();return {- content: [content, attachmentText].filter(Boolean).join("\n\n"),+ content: [autoPublishInstruction, content, attachmentText]+ .filter(Boolean)+ .join("\n\n"),images,+ includesAutoPublishInstruction: autoPublishInstruction !== null,};}+ /**+ * Pi does not consume AgentServer's ACP session system prompt. Carry the+ * user's cloud auto-publish choice into its first prompt explicitly, just as+ * prewarmed ACP sessions inject a first-message override after reading run+ * state. Without this, Pi sees the task but never sees the instruction to+ * publish the completed change.+ */+ private buildAutoPublishInstruction(): string | null {+ if (+ this.autoPublishInstructionDelivered ||+ this.config.autoPublish !== true ||+ this.config.createPr === false+ ) {+ return null;+ }+ return [+ "IMPORTANT — the user has auto-publish enabled for this cloud run.",+ "After completing and verifying code changes, create a `posthog/` branch, stage the changes, use the `git_signed_commit` tool to create a signed commit, and open a draft pull request with `gh pr create --draft`. Do not stop with local changes waiting for review.",+ "Do not use `git commit` or `git push`. If this task already has an open pull request for the same work, continue on that PR instead of opening another one.",+ ].join("\n");+ }+private async dispatchUserMessage(runtime: PiRuntime,content: string,