: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): validate cloud task run state (#89033)
Alessandro Pogliaghi2627001e9683
diff --git a/products/desktop/packages/agent/src/posthog-api.test.ts b/products/desktop/packages/agent/src/posthog-api.test.tsindex 3832cd1fccc4..187da21550eb 100644--- a/products/desktop/packages/agent/src/posthog-api.test.ts+++ b/products/desktop/packages/agent/src/posthog-api.test.ts@@ -10,6 +10,39 @@ describe("PostHogAPIClient", () => {vi.clearAllMocks();});+ it.each([+ [+ "keeps known and backend-only fields",+ { reasoning_effort: "xhigh", backend_only: "kept" },+ { reasoning_effort: "xhigh", backend_only: "kept" },+ ],+ [+ "drops an unreadable reasoning effort",+ { reasoning_effort: 123, initial_prompt_override: "run this" },+ { initial_prompt_override: "run this" },+ ],+ [+ "drops an unreadable permission mode",+ { initial_permission_mode: "invented", prewarmed: true },+ { prewarmed: true },+ ],+ ["falls back to an empty state", null, {}],+ ])("reads task-run state and %s", async (_label, state, expected) => {+ const client = new PostHogAPIClient({+ apiUrl: "https://app.posthog.com",+ getApiKey: vi.fn().mockResolvedValue("token"),+ projectId: 1,+ });+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: vi.fn().mockResolvedValue({ id: "run-1", state }),+ });++ const run = await client.getTaskRun("task-1", "run-1");++ expect(run.state).toEqual(expected);+ });+it("refreshes once when fetching task run logs gets an auth failure", async () => {const getApiKey = vi.fn().mockResolvedValue("stale-token");const refreshApiKey = vi.fn().mockResolvedValue("fresh-token");diff --git a/products/desktop/packages/agent/src/posthog-api.ts b/products/desktop/packages/agent/src/posthog-api.tsindex de903393bd9d..da3d914fa9e2 100644--- a/products/desktop/packages/agent/src/posthog-api.ts+++ b/products/desktop/packages/agent/src/posthog-api.ts@@ -1,8 +1,9 @@-import type {- McpServerConnection,- McpToolApprovalState,- McpToolPolicy,- StoredLogEntry,+import {+ type McpServerConnection,+ type McpToolApprovalState,+ type McpToolPolicy,+ type StoredLogEntry,+ taskRunStateSchema,} from "@posthog/shared";import packageJson from "../package.json" with { type: "json" };import type {@@ -339,10 +340,11 @@ export class PostHogAPIClient {signal?: AbortSignal,): Promise<TaskRun> {const teamId = this.getTeamId();- return this.apiRequest<TaskRun>(+ const taskRun = await this.apiRequest<TaskRun>(`/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/`,{ signal },);+ return { ...taskRun, state: taskRunStateSchema.parse(taskRun.state) };}/**diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex f20e2fe1dfdf..9613da9967cb 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -102,6 +102,8 @@ import type {Task,TaskRun,TaskRunArtifact,+ TaskRunState,+ TaskRunStateField,} from "../types";import { resourceLink } from "../utils/acp-content";import { AsyncMutex } from "../utils/async-mutex";@@ -383,15 +385,9 @@ interface LocalSkillPromptContext {function getTaskRunStateString(taskRun: TaskRun | null,- key: string,+ key: TaskRunStateField,): string | null {- const state = taskRun?.state;-- if (!state || typeof state !== "object") {- return null;- }-- const value = (state as Record<string, unknown>)[key];+ const value = taskRun?.state[key];return typeof value === "string" ? value : null;}@@ -423,13 +419,7 @@ function readSlackArtifactDelivery(* that predates charts, which is the same as off.*/function readSlackChartDelivery(taskRun: TaskRun | null): boolean {- const state = taskRun?.state;-- if (!state || typeof state !== "object") {- return false;- }-- return (state as Record<string, unknown>).slack_chart_delivery === true;+ return taskRun?.state.slack_chart_delivery === true;}// Prompt block we hand the agent when the user attached files but we could not@@ -1828,9 +1818,7 @@ export class AgentServer {preTask?.repositories ??(preTask?.repository ? [preTask.repository] : []);- this.prewarmedRun =- (preTaskRun?.state as Record<string, unknown> | undefined)?.prewarmed ===- true;+ this.prewarmedRun = preTaskRun?.state.prewarmed === true;this.prewarmedStartupTurnPending = this.prewarmedRun;const runtimeAdapter = this.getRuntimeAdapter();@@ -2000,7 +1988,7 @@ export class AgentServer {const conversationClear =extractConversationClearCapability(initializeResult);- const runState = preTaskRun?.state as Record<string, unknown> | undefined;+ const runState = preTaskRun?.state;// Preserve native Codex modes for cloud runs so they behave the same as// local sessions. Claude keeps the historical auto-approved default when// PostHog Desktop has not explicitly selected a mode.@@ -3082,14 +3070,8 @@ export class AgentServer {}private getInitialPromptOverride(taskRun: TaskRun): string | null {- const state = taskRun.state as Record<string, unknown> | undefined;- const override = state?.initial_prompt_override;- if (typeof override !== "string") {- return null;- }-- const trimmed = override.trim();- return trimmed.length > 0 ? trimmed : null;+ const override = taskRun.state.initial_prompt_override;+ return typeof override === "string" ? override.trim() || null : null;}private markMessageDelivered(messageId: string): void {@@ -3107,14 +3089,14 @@ export class AgentServer {taskRun: TaskRun | null,): Promise<BuiltPrompt | null> {if (!taskRun) return null;- const state = taskRun.state as Record<string, unknown> | undefined;- const message = state?.pending_user_message;+ const state = taskRun.state;+ const message = state.pending_user_message;const pendingMessageId =- typeof state?.pending_user_message_id === "string" &&+ typeof state.pending_user_message_id === "string" &&state.pending_user_message_id? state.pending_user_message_id: undefined;- const artifactIds = Array.isArray(state?.pending_user_artifact_ids)+ const artifactIds = Array.isArray(state.pending_user_artifact_ids)? state.pending_user_artifact_ids.filter((artifactId): artifactId is string =>typeof artifactId === "string" && artifactId.trim().length > 0,@@ -3259,10 +3241,7 @@ export class AgentServer {}private getClearedPendingUserState(taskRun: TaskRun | null): string[] | null {- const state =- taskRun?.state && typeof taskRun.state === "object"- ? (taskRun.state as Record<string, unknown>)- : null;+ const state = taskRun?.state;if (!state) {return null;}@@ -3919,11 +3898,8 @@ export class AgentServer {// Fallback: read from TaskRun state (set by API when creating the run)if (!taskRun) return null;- const state = taskRun.state as Record<string, unknown> | undefined;- const stateRunId = state?.resume_from_run_id;- return typeof stateRunId === "string" && stateRunId.trim().length > 0- ? stateRunId.trim()- : null;+ const stateRunId = taskRun.state.resume_from_run_id;+ return typeof stateRunId === "string" ? stateRunId.trim() || null : null;}private buildSessionSystemPrompt(@@ -4025,13 +4001,13 @@ export class AgentServer {return null;}- let state: Record<string, unknown> | undefined;+ let state: TaskRunState | undefined;try {const run = await this.posthogAPI.getTaskRun(this.session.payload.task_id,this.session.payload.run_id,);- state = run?.state as Record<string, unknown> | undefined;+ state = run?.state;} catch (error) {// Keep the settings unresolved so a later message retries. A transient// control-plane failure must not prevent the first prompt from running.@@ -4046,7 +4022,7 @@ export class AgentServer {}private async resolveWarmReasoningEffort(- state: Record<string, unknown> | undefined,+ state: TaskRunState | undefined,): Promise<void> {if (this.warmReasoningEffortResolved || !this.session) {return;@@ -4083,7 +4059,7 @@ export class AgentServer {* incomplete launch path omits the CLI flag, before the agent sees its first prompt.*/private resolveAutoPublishFromState(- state: Record<string, unknown> | undefined,+ state: TaskRunState | undefined,): string | null {if (this.autoPublishStateResolved) {return null;diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.ts b/products/desktop/packages/agent/src/server/pi-agent-server.tsindex 4fff3d568bad..752b8e1b8698 100644--- a/products/desktop/packages/agent/src/server/pi-agent-server.ts+++ b/products/desktop/packages/agent/src/server/pi-agent-server.ts@@ -544,7 +544,7 @@ export class PiAgentServer {return null;}),]);- const runState = taskRun?.state as Record<string, unknown> | undefined;+ const runState = taskRun?.state;const taskSnapshotKind = taskRun? typeof runState?.snapshot_kind === "string"? runState.snapshot_kinddiff --git a/products/desktop/packages/agent/src/types.ts b/products/desktop/packages/agent/src/types.tsindex 47ac8bfaf162..2dd3a60a75e2 100644--- a/products/desktop/packages/agent/src/types.ts+++ b/products/desktop/packages/agent/src/types.ts@@ -14,6 +14,8 @@ export type {TaskRun,TaskRunArtifact,TaskRunEnvironment,+ TaskRunState,+ TaskRunStateField,TaskRunStatus,} from "@posthog/shared";diff --git a/products/desktop/packages/api-client/src/task-normalization.ts b/products/desktop/packages/api-client/src/task-normalization.tsindex 4dd0e605745a..80c45c6cbfff 100644--- a/products/desktop/packages/api-client/src/task-normalization.ts+++ b/products/desktop/packages/api-client/src/task-normalization.ts@@ -1,10 +1,11 @@-import type {- ArtifactType,- Task,- TaskRun,- TaskRunArtifact,- TaskRunArtifactMetadata,- TaskRunStatus,+import {+ type ArtifactType,+ type Task,+ type TaskRun,+ type TaskRunArtifact,+ type TaskRunArtifactMetadata,+ type TaskRunStatus,+ taskRunStateSchema,} from "@posthog/shared/domain-types";import type { Schemas } from "./generated";@@ -187,7 +188,7 @@ export function normalizeTaskRunResponse(log_url: dto.log_url ?? "",error_message: dto.error_message ?? null,output: isRecord(dto.output) ? dto.output : null,- state: isRecord(dto.state) ? dto.state : {},+ state: taskRunStateSchema.parse(dto.state),...(dto.artifacts == null? {}: { artifacts: dto.artifacts.map(normalizeTaskRunArtifact) }),diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex a0c82f38f1e8..2aef13623269 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -286,6 +286,39 @@ export type TaskRunStatus =export type TaskRunEnvironment = "local" | "cloud";+const optionalField = <T extends z.ZodType>(+ field: T,+): z.ZodCatch<z.ZodOptional<T>> => field.optional().catch(undefined);++const taskRunStateFields = {+ ai_stage: optionalField(z.string()),+ auto_publish: optionalField(z.boolean()),+ initial_permission_mode: optionalField(executionModeSchema),+ initial_prompt_override: optionalField(z.string()),+ pending_user_artifact_ids: optionalField(z.array(z.string())),+ pending_user_message: optionalField(z.string()),+ pending_user_message_id: optionalField(z.string()),+ prewarmed: optionalField(z.boolean()),+ reasoning_effort: optionalField(+ z.union([effortLevelSchema, z.enum(["off", "minimal"])]),+ ),+ resume_from_run_id: optionalField(z.string()),+ sandbox_environment_id: optionalField(z.string()),+ slack_artifact_delivery: optionalField(+ z.enum(["none", "message", "canvas_file"]),+ ),+ slack_chart_delivery: optionalField(z.boolean()),+ slack_notified_pr_url: optionalField(z.string()),+ slack_thread_url: optionalField(z.string()),+ snapshot_kind: optionalField(z.string()),+ token_usage: optionalField(z.record(z.string(), z.unknown())),+} satisfies z.ZodRawShape;++export const taskRunStateSchema = z.looseObject(taskRunStateFields).catch({});++export type TaskRunState = z.infer<typeof taskRunStateSchema>;+export type TaskRunStateField = keyof typeof taskRunStateFields;+export type ArtifactType =| "plan"| "context"@@ -375,7 +408,7 @@ export interface TaskRun {log_url: string;error_message: string | null;output: Record<string, unknown> | null; // Structured output (PR URL, commit SHA, etc.)- state: Record<string, unknown>; // Intermediate run state (defaults to {}, never null)+ state: TaskRunState;artifacts?: TaskRunArtifact[];created_at: string;updated_at: string;diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.tsindex 65d8962cb56f..389182dd2110 100644--- a/products/desktop/packages/shared/src/index.ts+++ b/products/desktop/packages/shared/src/index.ts@@ -157,8 +157,11 @@ export {type TaskRunArtifact,type TaskRunArtifactMetadata,type TaskRunEnvironment,+ type TaskRunState,+ type TaskRunStateField,type TaskRunStatus,TERMINAL_STATUSES,+ taskRunStateSchema,} from "./domain-types";export * from "./enrichment";export {