: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(tasks): end analysis runs promptly and enrich insight events (#87777)
Shy Alter2fb3bfafe3b7
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.tsindex 39269885552d..97fdab3cbabd 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts@@ -121,6 +121,7 @@ type AppServerSessionMeta = {taskId?: string;persistence?: { taskId?: string };environment?: "local" | "cloud";+ mode?: string;channelMode?: boolean;spokenNarration?: boolean;baseBranch?: string;@@ -678,6 +679,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {if (!meta) return undefined;return {environment: meta.environment,+ background: meta.mode === "background",channelMode: meta.channelMode,spokenNarration: resolveSpokenNarration(meta),taskId: meta.taskId,diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.test.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.test.tsindex cd6a9c5f424a..7b4b1d32c763 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.test.ts+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.test.ts@@ -1,4 +1,14 @@import { describe, expect, it, vi } from "vitest";++const updateTaskRun = vi.fn();++vi.mock("../../../signed-commit-artefacts", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("../../../signed-commit-artefacts")+ >()),+ createSandboxPosthogClient: () => ({ updateTaskRun }),+}));+import { enabledLocalTools } from "../index";import type { LocalToolCtx, LocalToolGateMeta } from "../registry";import { FINISH_TOOL_NAME, finishSchema, finishTool } from "./finish";@@ -14,11 +24,17 @@ describe("finish tool", () => {expected: true,},{- name: "background cloud run without requestFinish",+ name: "background cloud run without requestFinish or run ids",ctx: { cwd: "/repo" },meta: { environment: "cloud", background: true },expected: false,},+ {+ name: "background cloud run with run ids only (out-of-process adapter)",+ ctx: { cwd: "/repo", taskId: "task-1", taskRunId: "run-1" },+ meta: { environment: "cloud", background: true },+ expected: true,+ },{name: "interactive cloud run (background unset)",ctx: { cwd: "/repo", requestFinish },@@ -75,6 +91,21 @@ describe("finish tool", () => {expect(result.isError).toBeUndefined();});+ it("marks the run terminal via the API when no requestFinish callback exists", async () => {+ updateTaskRun.mockResolvedValue({});+ const result = await finishTool.handler(+ { cwd: "/repo", taskId: "task-1", taskRunId: "run-1" },+ { status: "failed", reason: "blocked" },+ );+ expect(updateTaskRun).toHaveBeenCalledWith(+ "task-1",+ "run-1",+ { status: "failed", error_message: "blocked" },+ expect.any(AbortSignal),+ );+ expect(result.isError).toBeUndefined();+ });+it("errors when requestFinish is unavailable", async () => {const result = await finishTool.handler({ cwd: "/repo" },diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.tsindex 224af671e87f..115911e0cf8d 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.ts+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/finish.ts@@ -1,5 +1,13 @@import { z } from "zod";-import { defineLocalTool, type LocalToolResult } from "../registry";+import {+ createSandboxPosthogClient,+ withReportDeadline,+} from "../../../signed-commit-artefacts";+import {+ defineLocalTool,+ type LocalToolCtx,+ type LocalToolResult,+} from "../registry";export const FINISH_TOOL_NAME = "finish";@@ -39,6 +47,42 @@ export const FINISH_TOOL_DESCRIPTION =* down. Gated to cloud runs that actually own a sandbox — local sessions have* no `requestFinish` and no sandbox to reclaim, so the tool stays hidden there.*/+// Adapters that run local tools in a separate process (codex) cannot pass the+// in-process `requestFinish` callback through the serialized tool context, so+// the tool falls back to the same PostHog API PATCH that callback performs.+function resolveRequestFinish(+ ctx: LocalToolCtx,+): LocalToolCtx["requestFinish"] {+ if (ctx.requestFinish) {+ return ctx.requestFinish;+ }+ const { taskId, taskRunId } = ctx;+ if (!taskId || !taskRunId) {+ return undefined;+ }+ const client = createSandboxPosthogClient();+ if (!client) {+ return undefined;+ }+ return async (status, message) => {+ await withReportDeadline(+ (signal) =>+ client.updateTaskRun(+ taskId,+ taskRunId,+ {+ status,+ ...(status === "failed" && message+ ? { error_message: message }+ : {}),+ },+ signal,+ ),+ "run finish",+ );+ };+}+export const finishTool = defineLocalTool({name: FINISH_TOOL_NAME,description: FINISH_TOOL_DESCRIPTION,@@ -47,9 +91,10 @@ export const finishTool = defineLocalTool({isEnabled: (ctx, meta) =>meta?.environment === "cloud" &&meta?.background === true &&- ctx.requestFinish !== undefined,+ resolveRequestFinish(ctx) !== undefined,handler: async (ctx, args): Promise<LocalToolResult> => {- if (!ctx.requestFinish) {+ const requestFinish = resolveRequestFinish(ctx);+ if (!requestFinish) {return {content: [{ type: "text", text: "finish is not available in this session." },@@ -57,7 +102,7 @@ export const finishTool = defineLocalTool({isError: true,};}- await ctx.requestFinish(args.status, args.reason);+ await requestFinish(args.status, args.reason);return {content: [{diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/report-insight.test.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/report-insight.test.tsindex df324ec99fc4..66407a03cb33 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/report-insight.test.ts+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/report-insight.test.ts@@ -3,11 +3,10 @@ import os from "node:os";import path from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-const getTaskRun = vi.fn();const reportAnalysisInsight = vi.fn();vi.mock("../../../signed-commit-artefacts", () => ({- createSandboxPosthogClient: () => ({ getTaskRun, reportAnalysisInsight }),+ createSandboxPosthogClient: () => ({ reportAnalysisInsight }),withReportDeadline: <T>(work: (signal: AbortSignal) => Promise<T>) =>work(new AbortController().signal),}));@@ -94,8 +93,7 @@ describe("reportInsightTool", () => {const logPath = path.join(cwd, LOG_RELATIVE_PATH);await mkdir(path.dirname(logPath), { recursive: true });await writeFile(logPath, RUN_LOG);- getTaskRun.mockResolvedValue({ state: {} });- reportAnalysisInsight.mockResolvedValue({});+ reportAnalysisInsight.mockResolvedValue({ insight_index: 0 });});afterEach(async () => {@@ -225,32 +223,31 @@ describe("reportInsightTool", () => {expect(reportAnalysisInsight).not.toHaveBeenCalled();});- it("enforces the per-run cap and the no-findings contradiction", async () => {- getTaskRun.mockResolvedValue({- state: {- [INSIGHTS_STATE_KEY]: Array(5).fill({ category: "missing_tool" }),- },- });- const capped = await reportInsightTool.handler(ctx(cwd), validFinding());- expect(capped.isError).toBe(true);- expect(capped.content[0].text).toMatch(/cap/);+ it("numbers the recorded finding from the server's index", async () => {+ reportAnalysisInsight.mockResolvedValue({ insight_index: 2 });+ const result = await reportInsightTool.handler(ctx(cwd), validFinding());+ expect(result.isError).toBeUndefined();+ expect(result.content[0].text).toMatch(+ /Recorded finding 3 .+ 2 more allowed/,+ );+ });- getTaskRun.mockResolvedValue({- state: {- [INSIGHTS_STATE_KEY]: [{ no_findings_reason: "run_was_efficient" }],- },- });- const contradictory = await reportInsightTool.handler(- ctx(cwd),- validFinding(),+ it("returns a coaching error when the server rejects the report", async () => {+ reportAnalysisInsight.mockRejectedValueOnce(+ new Error(+ 'Failed request: [400] {"evidence":[{"quote":["Ensure this value has at least 20 characters."]}]}',+ ),+ );+ const result = await reportInsightTool.handler(ctx(cwd), validFinding());+ expect(result.isError).toBe(true);+ expect(result.content[0].text).toMatch(/was rejected by the server/);+ expect(result.content[0].text).toContain(+ "Ensure this value has at least 20 characters",);- expect(contradictory.isError).toBe(true);- expect(contradictory.content[0].text).toMatch(/contradictory/);});it("accumulates findings filed as parallel tool calls", async () => {const state: Record<string, unknown> = {};- getTaskRun.mockImplementation(() => Promise.resolve({ state }));reportAnalysisInsight.mockImplementation(appendingUpdateMock(state));const second = validFinding({diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/report-insight.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/report-insight.tsindex 12b03b730b78..effc98e79c32 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/report-insight.ts+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/report-insight.ts@@ -94,6 +94,18 @@ function errorResult(message: string): LocalToolResult {return { content: [{ type: "text", text: message }], isError: true };}+// Desktop ships on its own schedule with no orchestration against backend deploys, so a+// report can hit an older server contract (a 10-19 char quote, an output_bytes-only+// finding). The API throws a raw `Failed request: [400] {...}` blob that loses the finding+// silently. Turn a rejection into an actionable error so the model can correct the input+// and retry, matching the coaching style of every other rejection path in this tool.+function reportRejectionResult(error: unknown, what: string): LocalToolResult {+ const message = error instanceof Error ? error.message : String(error);+ return errorResult(+ `The ${what} was rejected by the server and was not recorded. Correct the flagged field and call report_insight again. Server response: ${message}`,+ );+}+// biome-ignore lint/suspicious/noControlCharactersInRegex: matching the ESC byte is the pointconst ANSI_PATTERN = /(?:\u001b|\\u001b)\[[0-9;]*m/g;@@ -251,6 +263,14 @@ export const reportInsightTool = defineLocalTool({.describe("Tokens consumed across the wasted span, measured from the run log.",),+ output_bytes: z+ .number()+ .int()+ .min(1)+ .optional()+ .describe(+ "Sum of tool-output sizes across the wasted span, measured from the log. Works in both log formats even when token counters are absent.",+ ),}).optional().describe(@@ -282,20 +302,6 @@ export const reportInsightTool = defineLocalTool({);}- const run = await withReportDeadline(- (signal) =>- client.getTaskRun(- ctx.taskId as string,- ctx.taskRunId as string,- signal,- ),- "analysis run lookup",- );- const state = (run.state ?? {}) as Record<string, unknown>;- const existing = Array.isArray(state[INSIGHTS_STATE_KEY])- ? (state[INSIGHTS_STATE_KEY] as StoredInsight[])- : [];-if (args.no_findings_reason) {const findingFields = [args.observation,@@ -308,21 +314,20 @@ export const reportInsightTool = defineLocalTool({"no_findings_reason cannot be combined with a finding. Either report the finding (drop no_findings_reason) or report no findings (drop every other field).",);}- if (existing.length > 0) {- return errorResult(- "Findings were already reported for this run, so a no-findings report is contradictory. Stop reporting.",+ try {+ await withReportDeadline(+ (signal) =>+ client.reportAnalysisInsight(+ ctx.taskId as string,+ ctx.taskRunId as string,+ { no_findings_reason: args.no_findings_reason },+ signal,+ ),+ "no-findings report",);+ } catch (error) {+ return reportRejectionResult(error, "no-findings report");}- await withReportDeadline(- (signal) =>- client.reportAnalysisInsight(- ctx.taskId as string,- ctx.taskRunId as string,- { no_findings_reason: args.no_findings_reason },- signal,- ),- "no-findings report",- );return {content: [{@@ -338,16 +343,6 @@ export const reportInsightTool = defineLocalTool({"A finding requires observation, evidence, and category (or use only no_findings_reason for a clean run).",);}- if (existing.some((entry) => "no_findings_reason" in entry)) {- return errorResult(- "This run was already reported as having no findings; a finding now is contradictory. Stop reporting.",- );- }- if (existing.length >= MAX_INSIGHTS_PER_RUN) {- return errorResult(- `The ${MAX_INSIGHTS_PER_RUN}-finding cap for this run is reached. Stop reporting; summarize what you filed.`,- );- }if (args.category === "other" && !args.other_justification) {return errorResult("category 'other' requires other_justification (50-200 chars).",@@ -361,7 +356,7 @@ export const reportInsightTool = defineLocalTool({wastedDimensions.length === 0) {return errorResult(- `category '${args.category}' requires wasted_effort with at least one measured dimension (tool_calls, seconds, or tokens) — count or subtract it from the log.`,+ `category '${args.category}' requires wasted_effort with at least one measured dimension (tool_calls, seconds, tokens, or output_bytes) — count or subtract it from the log.`,);}if (!args.recurrence || !args.confidence_basis || !args.suggested_fix) {@@ -420,25 +415,29 @@ export const reportInsightTool = defineLocalTool({confidence_basis: args.confidence_basis,suggested_fix: args.suggested_fix,};- await withReportDeadline(- (signal) =>- client.reportAnalysisInsight(- ctx.taskId as string,- ctx.taskRunId as string,- insight,- signal,- ),- "insight report",- );+ try {+ const { insight_index } = await withReportDeadline(+ (signal) =>+ client.reportAnalysisInsight(+ ctx.taskId as string,+ ctx.taskRunId as string,+ insight,+ signal,+ ),+ "insight report",+ );- const remaining = MAX_INSIGHTS_PER_RUN - existing.length - 1;- return {- content: [- {- type: "text",- text: `Recorded finding ${existing.length + 1} (${args.category}). ${remaining} more allowed; only report findings that clear the evidence bar.`,- },- ],- };+ const remaining = MAX_INSIGHTS_PER_RUN - insight_index - 1;+ return {+ content: [+ {+ type: "text",+ text: `Recorded finding ${insight_index + 1} (${args.category}). ${remaining} more allowed; only report findings that clear the evidence bar.`,+ },+ ],+ };+ } catch (error) {+ return reportRejectionResult(error, "finding");+ }}),});