: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): keep delegated reports out of triage (#100522)
Dylan Martinacb94d6a7ffc
diff --git a/products/desktop/apps/code/.storybook/preview.tsx b/products/desktop/apps/code/.storybook/preview.tsxindex aca1d6470b82..78972ec8c5c3 100644--- a/products/desktop/apps/code/.storybook/preview.tsx+++ b/products/desktop/apps/code/.storybook/preview.tsx@@ -1,9 +1,11 @@import "./mocks/electron-trpc";import "./mocks/renderer-storage";+import { useThemeStore } from "@posthog/ui/shell/themeStore";import { Theme } from "@radix-ui/themes";import "@radix-ui/themes/styles.css";import type { Preview } from "@storybook/react-vite";import MockDate from "mockdate";+import { useEffect } from "react";import "../../../packages/ui/src/styles/globals.css";import { withAppProviders } from "./withAppProviders";@@ -40,6 +42,9 @@ const preview: Preview = {withAppProviders,(Story, context) => {const isDark = context.globals.theme !== "light";+ useEffect(() => {+ useThemeStore.getState().setTheme(isDark ? "dark" : "light");+ }, [isDark]);// The app's themeStore puts this on the document, and quill's tokens hang// off it. Anything portaled out of the story root (a popover, a dropdown)// reads the document rather than the Theme below it, so without this adiff --git a/products/desktop/apps/code/.storybook/withAppProviders.tsx b/products/desktop/apps/code/.storybook/withAppProviders.tsxindex 74f8879f853a..f9d12c9e7cc5 100644--- a/products/desktop/apps/code/.storybook/withAppProviders.tsx+++ b/products/desktop/apps/code/.storybook/withAppProviders.tsx@@ -1,3 +1,4 @@+import WorkerUrl from "@pierre/diffs/worker/worker.js?worker&url";import { type ServiceContainer, setRootContainer } from "@posthog/di/container";import { ServiceProvider } from "@posthog/di/react";import { ipcLink } from "@posthog/electron-trpc/renderer";@@ -66,21 +67,6 @@ const noopHostClient = {},} as unknown as HostTrpcClient;-// Diffs are computed in a web worker. Storybook has no worker backend, so hand-// out an inert stub: components render, diffs just never resolve.-const stubWorker = {- postMessage() {},- terminate() {},- addEventListener() {},- removeEventListener() {},- dispatchEvent() {- return false;- },- onmessage: null,- onmessageerror: null,- onerror: null,-} as unknown as Worker;-// An inert, infinitely-chainable stand-in for any core service a deep component// tree resolves that we haven't (and don't need to) wire up for visuals — e.g.// the external-apps service behind a "open in editor" button. Property access@@ -149,7 +135,9 @@ function createProviderStack(): ProviderStack {.bind<HostTrpcClient>(HOST_TRPC_CLIENT).toConstantValue(noopHostClient);bindings.bind(IMPERATIVE_QUERY_CLIENT).toConstantValue(queryClient);- bindings.bind(DIFF_WORKER_FACTORY).toConstantValue(() => stubWorker);+ bindings+ .bind(DIFF_WORKER_FACTORY)+ .toConstantValue(() => new Worker(WorkerUrl, { type: "module" }));// Real (not inert-proxy) flags: isEnabled must return an actual boolean, or// every flag reads as enabled and useFeatureFlag's state never settles.bindings.bind<FeatureFlags>(FEATURE_FLAGS).toConstantValue({diff --git a/products/desktop/apps/code/src/main/utils/otel-log-transport.test.ts b/products/desktop/apps/code/src/main/utils/otel-log-transport.test.tsindex cbb5a1b94449..3e8c9187b83c 100644--- a/products/desktop/apps/code/src/main/utils/otel-log-transport.test.ts+++ b/products/desktop/apps/code/src/main/utils/otel-log-transport.test.ts@@ -1,5 +1,9 @@import { beforeEach, describe, expect, it, vi } from "vitest";+vi.mock("./env", () => ({+ getAppVersion: () => process.env.POSTHOG_CODE_VERSION,+}));+const mockEmit = vi.fn();const mockForceFlush = vi.fn(() => Promise.resolve());const mockShutdown = vi.fn(() => Promise.resolve());diff --git a/products/desktop/apps/code/test-runner-jest.config.js b/products/desktop/apps/code/test-runner-jest.config.jsindex e34e6516fb11..c9640dd9fbc4 100644--- a/products/desktop/apps/code/test-runner-jest.config.js+++ b/products/desktop/apps/code/test-runner-jest.config.js@@ -5,6 +5,7 @@ const baseConfig = getJestConfig();module.exports = {...baseConfig,+ roots: [path.resolve(__dirname, "../..")],forceExit: true,// test-runner-globals.js must come first: Storybook 10 loads test-runner.ts// outside Jest's module scope, so `jest` has to be reachable via globalThisdiff --git a/products/desktop/apps/web/src/web-container.ts b/products/desktop/apps/web/src/web-container.tsindex 6e67562d6a68..cda0148dc29f 100644--- a/products/desktop/apps/web/src/web-container.ts+++ b/products/desktop/apps/web/src/web-container.ts@@ -75,6 +75,7 @@ import {REPORT_MODEL_RESOLVER,type ReportModelResolver,} from "@posthog/core/inbox/identifiers";+import { inboxCoreModule } from "@posthog/core/inbox/inbox.module";import { selectModelFromOptions } from "@posthog/core/inbox/reportTaskCreation";import { githubConnectModule } from "@posthog/core/integrations/githubConnect.module";import {@@ -856,6 +857,13 @@ container.bind(REPORT_MODEL_RESOLVER).toConstantValue({},} satisfies ReportModelResolver);+// ── Inbox: the report services the shared Inbox hooks resolve ──+// Self-driving lives in the shared route tree, so the web host loads the same+// core module the desktop renderer does. Bindings resolve lazily, and the one+// token the shared hooks reach for (the report implementation service) has no+// injected dependencies, so nothing here needs a local-only capability.+container.load(inboxCoreModule);+// Fail loudly at composition time if a capability the shared app resolves via// service location is unbound, instead of limping to the first navigation that// needs it (how the missing reportModelResolver first surfaced). This runs atdiff --git a/products/desktop/docs/SELF-DRIVING-REPORTS.md b/products/desktop/docs/SELF-DRIVING-REPORTS.mdindex 2c5dfdac0ca3..fd6d996184e1 100644--- a/products/desktop/docs/SELF-DRIVING-REPORTS.md+++ b/products/desktop/docs/SELF-DRIVING-REPORTS.md@@ -22,6 +22,18 @@ Unread reports show a small blue dot in the list. Open a report to mark it as reSelect the dot or use the right-click menu to mark a report as read or unread. Read reports stay in the list.Read state is saved on this device for the current user and project. It does not sync across devices or recover earlier report visits.Select Triage mode to review reports in sequence.+Create PR starts the task in the background. Triage advances only after the task starts successfully.+The confirmation offers View task. It does not open a chat panel or navigate away.+Reports with an active implementation task stay in the list with a Creating PR label, but leave the triage queue.+This uses the saved task assignment and survives reopening the app. It does not dismiss, resolve, or change the report read state.+A failed or stopped task, a task that finishes without a PR, or a report waiting for input returns to triage with a status message.+If task status cannot be loaded, the report stays in triage. An attached PR remains available for review.+Task status refreshes in batches while the list is open. Rows use the same status results as triage.+The batch response supplies the latest run's PR URL and state, including changes after task completion.+Completed tasks need no separate detail requests when these fields are present. Null fields mean that the run has no PR.+Older servers that omit either field use cached task details instead. The cache expires after five minutes.+The triage count includes only loaded reports that need a decision. Load more reports to check the next page.+A callback error after task startup does not change a successful start into a failed start. Older servers without task assignments keep their existing queue behavior.Triage hides the sidebar. Exiting triage or opening a report restores it without changing its saved width or open setting.Press T from the report list or an open report to start triage when triage is enabled. The shortcut does not run while you type in a field.@@ -29,3 +41,12 @@ To filter reports for a user, open Filter reports, then hover over Scope.Hover opens the user list without moving keyboard focus. Click the search field to type, or use the keyboard to open Scope and focus the search field.The search starts empty and shows up to 20 options, including For you and Entire project.Search by name or email across all users. The search field stays visible above the results.++## Storybook previews++The `Inbox/Reports` stories cover the sidebar, report list, report detail, and triage mode.+They use local report and task fixtures, including active work, failed tasks, and requests for input.+PR stories include draft and failed-check states and a rendered code diff.+Interactive stories cover user search, read state, summary navigation, and sidebar restoration.+The `inbox` story tag selects these previews for visual checks in both themes.+Cloud task startup, refunds, and GitHub writes are not connected to live services in these previews.diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.tsindex 2c7a05784313..ed1df5bb6344 100644--- a/products/desktop/packages/api-client/src/posthog-client.test.ts+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts@@ -2281,6 +2281,25 @@ describe("PostHogAPIClient", () => {});});+ it.each([+ {},+ { pr_url: null, pr_state: null },+ {+ pr_url: "https://github.com/example/project/pull/1",+ pr_state: "merged",+ },+ ])("preserves optional PR fields in task summaries: %j", async (fields) => {+ const summary = {+ id: "task-1",+ latest_run: { id: "run-1", status: "completed", ...fields },+ };+ const fetch = buildFetchForPages(page([summary]));+ const summaries = await buildClient(fetch).getTaskSummaries([summary.id]);+ expect(summaries).toEqual([summary]);+ expect(summaries[0].latest_run?.pr_url).toBe(fields.pr_url);+ expect(summaries[0].latest_run?.pr_state).toBe(fields.pr_state);+ });+it("fetches remaining pages by offset from count, not by walking next", async () => {const fetch = buildFetchForPages(page([{ id: "a" }], 250),diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 4024db527333..577bcb2ae97a 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -148,6 +148,8 @@ import {normalizeTaskRunArtifact,normalizeTaskRunResponse,type TaskRunArtifactDTO,+ type TaskSummariesResponse,+ type TaskSummaryDTO,} from "./task-normalization";interface HogQLGrid {@@ -3070,7 +3072,7 @@ export class PostHogAPIClient {const fetchPage = async (offset: number,- ): Promise<Schemas.PaginatedTaskSummaryDTOList> => {+ ): Promise<TaskSummariesResponse> => {const urlPath = `${basePath}?limit=${PAGE_LIMIT}&offset=${offset}`;const response = await this.api.fetcher.fetch({method: "post",@@ -3085,11 +3087,11 @@ export class PostHogAPIClient {`Failed to fetch task summaries: ${response.statusText}`,);}- return (await response.json()) as Schemas.PaginatedTaskSummaryDTOList;+ return (await response.json()) as TaskSummariesResponse;};const first = await fetchPage(0);- const all: Schemas.TaskSummaryDTO[] = [...first.results];+ const all: TaskSummaryDTO[] = [...first.results];const capped = Math.min(first.count, PAGE_LIMIT * MAX_PAGES);if (first.count > PAGE_LIMIT * MAX_PAGES) {log.warn(diff --git a/products/desktop/packages/api-client/src/task-normalization.ts b/products/desktop/packages/api-client/src/task-normalization.tsindex 34c25de11ff3..8d40a1ae43f1 100644--- a/products/desktop/packages/api-client/src/task-normalization.ts+++ b/products/desktop/packages/api-client/src/task-normalization.ts@@ -11,6 +11,22 @@ import {} from "@posthog/shared/domain-types";import type { Schemas } from "./generated";+export type TaskSummaryDTO = Omit<Schemas.TaskSummaryDTO, "latest_run"> & {+ latest_run?:+ | (Omit<Schemas.TaskRunSummary, "pr_url" | "pr_state"> & {+ pr_url?: string | null;+ pr_state?: "open" | "draft" | "merged" | "closed" | "unknown" | null;+ })+ | null;+};++export type TaskSummariesResponse = Omit<+ Schemas.PaginatedTaskSummaryDTOList,+ "results"+> & {+ results: TaskSummaryDTO[];+};+export type TaskRunArtifactDTO = Omit<Schemas.TaskRunArtifactResponse,"metadata" | "storage_path"diff --git a/products/desktop/packages/core/src/inbox/inbox.module.ts b/products/desktop/packages/core/src/inbox/inbox.module.tsindex ddcd38a0e460..66b666701f46 100644--- a/products/desktop/packages/core/src/inbox/inbox.module.ts+++ b/products/desktop/packages/core/src/inbox/inbox.module.ts@@ -7,10 +7,16 @@ import {SIGNAL_REPORT_TASK_SERVICE,SIGNAL_SOURCE_SERVICE,} from "./identifiers";+import {+ REPORT_IMPLEMENTATION_SERVICE,+ ReportImplementationService,+} from "./reportImplementationService";import { SignalReportTaskService } from "./signalReportTaskService";import { SignalSourceService } from "./signalSourceService";export const inboxCoreModule = new ContainerModule(({ bind }) => {+ bind(ReportImplementationService).toSelf().inSingletonScope();+ bind(REPORT_IMPLEMENTATION_SERVICE).toService(ReportImplementationService);bind(InboxBulkActionService).toSelf().inSingletonScope();bind(INBOX_BULK_ACTION_SERVICE).toService(InboxBulkActionService);diff --git a/products/desktop/packages/core/src/inbox/reportImplementation.ts b/products/desktop/packages/core/src/inbox/reportImplementation.tsnew file mode 100644index 000000000000..fee1b072accf--- /dev/null+++ b/products/desktop/packages/core/src/inbox/reportImplementation.ts@@ -0,0 +1,84 @@+import type { SignalReport, Task } from "@posthog/shared/types";++export type ReportImplementationState =+ | "checking"+ | "working"+ | "needs_input"+ | "failed"+ | "cancelled"+ | "no_pr"+ | "in_review"+ | "unknown";++export const REPORT_IMPLEMENTATION_LABELS: Record<+ ReportImplementationState,+ string+> = {+ checking: "Checking task status",+ working: "Creating PR",+ needs_input: "Waiting on you",+ failed: "PR task failed",+ cancelled: "PR task stopped",+ no_pr: "No PR created",+ in_review: "PR created",+ unknown: "Task status unavailable",+};++export function reportImplementationTaskId(+ report: SignalReport,+): string | null {+ if (report.implementation_pr_url && !report.implementation_pr_merged)+ return null;+ if (+ report.status === "resolved" ||+ report.status === "suppressed" ||+ report.status === "deleted"+ )+ return null;+ return report.assignee?.kind === "task" ? report.assignee.task_id : null;+}++export function deriveReportImplementationState(+ report: SignalReport,+ task:+ | {+ latest_run?: {+ status: string | null;+ output?: NonNullable<Task["latest_run"]>["output"];+ } | null;+ }+ | undefined,+ lookupFailed = false,+): ReportImplementationState | null {+ if (!reportImplementationTaskId(report)) return null;+ if (report.status === "pending_input") return "needs_input";+ if (lookupFailed) return "unknown";+ if (!task) return "checking";+ const run = task.latest_run;+ if (run?.status === "failed") return "failed";+ if (run?.status === "cancelled") return "cancelled";+ const prClosed =+ report.implementation_pr_merged ||+ run?.output?.pr_merged === true ||+ run?.output?.pr_state === "merged" ||+ run?.output?.pr_state === "closed";+ if (+ !prClosed &&+ (report.implementation_pr_url ||+ (typeof run?.output?.pr_url === "string" && run.output.pr_url.trim()))+ )+ return "in_review";+ if (!run) return "unknown";+ if (run.status === "completed") return "no_pr";+ return run.status === "not_started" ||+ run.status === "queued" ||+ run.status === "in_progress"+ ? "working"+ : "unknown";+}++export function needsImplementationDecision(+ state: ReportImplementationState | null,+): boolean {+ return state !== "working" && state !== "in_review" && state !== "checking";+}diff --git a/products/desktop/packages/core/src/inbox/reportImplementationService.ts b/products/desktop/packages/core/src/inbox/reportImplementationService.tsnew file mode 100644index 000000000000..3835402b894c--- /dev/null+++ b/products/desktop/packages/core/src/inbox/reportImplementationService.ts@@ -0,0 +1,143 @@+import type { Schemas } from "@posthog/api-client";+import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";+import type { SignalReport, Task } from "@posthog/shared/types";+import { injectable } from "inversify";+import {+ deriveReportImplementationState,+ type ReportImplementationState,+ reportImplementationTaskId,+} from "./reportImplementation";++export const REPORT_IMPLEMENTATION_SERVICE = Symbol.for(+ "posthog.core.inbox.reportImplementationService",+);++@injectable()+export class ReportImplementationService {+ private readonly completedTasks = new WeakMap<+ PostHogAPIClient,+ Map<string, { version: string; expiresAt: number; task: Promise<Task> }>+ >();++ initialStates(+ reports: SignalReport[],+ lookupFailed = false,+ ): Map<string, ReportImplementationState | null> {+ return new Map(+ reports.map((report) => [+ report.id,+ deriveReportImplementationState(report, undefined, lookupFailed),+ ]),+ );+ }++ /**+ * The states to show while a fetch is in flight. A report that gains or+ * finishes a task changes the query key, so the next fetch starts with+ * nothing. `known` carries what the last fetch resolved, so only a report+ * that was never checked falls back to "checking".+ */+ pendingStates(+ reports: SignalReport[],+ known: ReadonlyMap<string, ReportImplementationState | null>,+ lookupFailed = false,+ ): Map<string, ReportImplementationState | null> {+ const states = this.initialStates(reports, lookupFailed);+ for (const [id, state] of states) {+ if (state !== "checking") continue;+ const previous = known.get(id);+ if (previous !== undefined) states.set(id, previous);+ }+ return states;+ }++ private async completedTask(+ client: PostHogAPIClient,+ summary: Schemas.TaskSummaryDTO,+ ): Promise<Task> {+ let cache = this.completedTasks.get(client);+ if (!cache) {+ cache = new Map();+ this.completedTasks.set(client, cache);+ }+ const version = `${summary.updated_at}:${summary.latest_run?.id}`;+ const cached = cache.get(summary.id);+ if (cached?.version === version && cached.expiresAt > Date.now())+ return cached.task;+ const task = client.getTask(summary.id);+ cache.set(summary.id, {+ version,+ expiresAt: Date.now() + 5 * 60_000,+ task,+ });+ if (cache.size > 400) {+ const oldest = cache.keys().next().value;+ if (oldest) cache.delete(oldest);+ }+ try {+ return await task;+ } catch (error) {+ cache.delete(summary.id);+ throw error;+ }+ }++ async loadStates(+ client: PostHogAPIClient,+ reports: SignalReport[],+ ): Promise<Map<string, ReportImplementationState | null>> {+ const ids = [+ ...new Set(+ reports+ .map(reportImplementationTaskId)+ .filter((id): id is string => id !== null),+ ),+ ];+ if (!ids.length) return this.initialStates(reports);+ const summaries = await client.getTaskSummaries(ids);+ const tasks = new Map<+ string,+ Parameters<typeof deriveReportImplementationState>[1]+ >(+ summaries.map((summary) => [+ summary.id,+ {+ latest_run: summary.latest_run && {+ status: summary.latest_run.status,+ output: {+ pr_url: summary.latest_run.pr_url,+ pr_state: summary.latest_run.pr_state,+ },+ },+ },+ ]),+ );+ const completed = summaries.filter(+ (summary) =>+ summary.latest_run?.status === "completed" &&+ (summary.latest_run.pr_url === undefined ||+ summary.latest_run.pr_state === undefined),+ );+ for (let offset = 0; offset < completed.length; offset += 10) {+ await Promise.all(+ completed.slice(offset, offset + 10).map(async (summary) => {+ try {+ tasks.set(summary.id, await this.completedTask(client, summary));+ } catch {+ tasks.delete(summary.id);+ }+ }),+ );+ }+ return new Map(+ reports.map((report) => {+ const taskId = reportImplementationTaskId(report);+ const task = taskId ? tasks.get(taskId) : undefined;+ return [+ report.id,+ deriveReportImplementationState(report, task, !!taskId && !task),+ ];+ }),+ );+ }+}diff --git a/products/desktop/packages/core/src/inbox/reportInboxSections.test.ts b/products/desktop/packages/core/src/inbox/reportInboxSections.test.tsindex 33864d1290ed..18c53262aa56 100644--- a/products/desktop/packages/core/src/inbox/reportInboxSections.test.ts+++ b/products/desktop/packages/core/src/inbox/reportInboxSections.test.ts@@ -1,6 +1,11 @@-import type { SignalReport } from "@posthog/shared/types";-import { describe, expect, it } from "vitest";-+import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";+import type { SignalReport, Task, TaskRunStatus } from "@posthog/shared/types";+import { describe, expect, it, vi } from "vitest";+import {+ deriveReportImplementationState,+ needsImplementationDecision,+} from "./reportImplementation";+import { ReportImplementationService } from "./reportImplementationService";import { partitionInboxReports } from "./reportInboxSections";function report(overrides: Partial<SignalReport>): SignalReport {@@ -19,7 +24,344 @@ function report(overrides: Partial<SignalReport>): SignalReport {} as SignalReport;}+function implementationTask(+ status: TaskRunStatus,+ output: Record<string, unknown> | null = null,+): Task {+ return {+ id: "implementation-1",+ task_number: 1,+ slug: "implementation-1",+ title: "Fix the example report",+ description: "Create a PR for the report.",+ origin_product: "signal_report",+ created_at: "2026-09-01T00:00:00Z",+ updated_at: "2026-09-01T00:00:00Z",+ latest_run: {+ id: "run-1",+ task: "implementation-1",+ team: 1,+ branch: null,+ status,+ log_url: "",+ error_message: null,+ output,+ state: {},+ created_at: "2026-09-01T00:00:00Z",+ updated_at: "2026-09-01T00:00:00Z",+ completed_at: null,+ },+ };+}+describe("reportInboxSections", () => {+ it("batches and deduplicates task lookups for a full report page", async () => {+ const reports = Array.from({ length: 400 }, (_, index) =>+ report({+ id: `report-${index}`,+ assignee: { kind: "task", task_id: `task-${index % 200}` },+ }),+ );+ const summaries = Array.from({ length: 200 }, (_, index) => ({+ id: `task-${index}`,+ latest_run: { status: "in_progress" },+ }));+ const client = {+ getTaskSummaries: vi.fn().mockResolvedValue(summaries),+ getTask: vi.fn(),+ };+ const service = new ReportImplementationService();+ const states = await service.loadStates(+ client as unknown as PostHogAPIClient,+ reports,+ );+ expect(client.getTaskSummaries).toHaveBeenCalledExactlyOnceWith(+ summaries.map((summary) => summary.id),+ );+ expect(client.getTask).not.toHaveBeenCalled();+ expect(states.size).toBe(400);+ expect([...states.values()].every((state) => state === "working")).toBe(+ true,+ );+ });++ it("keeps missing tasks visible and pending input actionable", async () => {+ const client = { getTaskSummaries: vi.fn().mockResolvedValue([]) };+ const states = await new ReportImplementationService().loadStates(+ client as unknown as PostHogAPIClient,+ [+ report({+ id: "missing",+ assignee: { kind: "task", task_id: "missing" },+ }),+ report({+ id: "input",+ status: "pending_input",+ assignee: { kind: "task", task_id: "input" },+ }),+ ],+ );+ expect(states.get("missing")).toBe("unknown");+ expect(states.get("input")).toBe("needs_input");+ });++ it.each([+ [null, null, "no_pr"],+ ["https://github.com/example/project/pull/1", "open", "in_review"],+ ["https://github.com/example/project/pull/1", "draft", "in_review"],+ ["https://github.com/example/project/pull/1", "unknown", "in_review"],+ ["https://github.com/example/project/pull/1", "merged", "no_pr"],+ ["https://github.com/example/project/pull/1", "closed", "no_pr"],+ ])(+ "loads completed tasks with PR state %s / %s without detail requests",+ async (prUrl, prState, expected) => {+ const summaries = Array.from({ length: 25 }, (_, index) => ({+ id: `task-${index}`,+ latest_run: {+ id: `run-${index}`,+ status: "completed",+ pr_url: prUrl,+ pr_state: prState,+ },+ }));+ const reports = summaries.map((summary) =>+ report({+ id: summary.id,+ assignee: { kind: "task", task_id: summary.id },+ }),+ );+ const client = {+ getTaskSummaries: vi.fn().mockResolvedValue(summaries),+ getTask: vi.fn(),+ };+ const states = await new ReportImplementationService().loadStates(+ client as unknown as PostHogAPIClient,+ reports,+ );+ expect(client.getTaskSummaries).toHaveBeenCalledExactlyOnceWith(+ summaries.map((summary) => summary.id),+ );+ expect(client.getTask).not.toHaveBeenCalled();+ expect([...states.values()]).toEqual(reports.map(() => expected));+ },+ );++ it("uses fresh summaries instead of cached details after a server upgrade", async () => {+ const task = implementationTask("completed");+ const summary = {+ ...task,+ latest_run: { id: "run-1", status: "completed" },+ };+ const client = {+ getTaskSummaries: vi.fn().mockResolvedValue([summary]),+ getTask: vi.fn().mockResolvedValue(task),+ };+ const reports = [report({ assignee: { kind: "task", task_id: task.id } })];+ const service = new ReportImplementationService();+ const load = () =>+ service.loadStates(client as unknown as PostHogAPIClient, reports);+ expect((await load()).get("r")).toBe("no_pr");+ for (const [prState, expected] of [+ ["open", "in_review"],+ ["merged", "no_pr"],+ ["open", "in_review"],+ ["closed", "no_pr"],+ ]) {+ client.getTaskSummaries.mockResolvedValue([+ {+ ...summary,+ latest_run: {+ ...summary.latest_run,+ pr_url: "https://github.com/example/project/pull/1",+ pr_state: prState,+ },+ },+ ]);+ expect((await load()).get("r")).toBe(expected);+ }+ expect(client.getTaskSummaries).toHaveBeenCalledTimes(5);+ expect(client.getTask).toHaveBeenCalledOnce();+ });++ it.each([{}, { pr_url: null }, { pr_state: null }])(+ "loads details only for summaries with missing PR fields: %j",+ async (fields) => {+ const task = implementationTask("completed", {+ pr_url: "https://github.com/example/project/pull/1",+ });+ const client = {+ getTaskSummaries: vi.fn().mockResolvedValue([+ {+ id: task.id,+ latest_run: { id: "run-1", status: "completed", ...fields },+ },+ {+ id: "no-pr",+ latest_run: {+ id: "run-2",+ status: "completed",+ pr_url: null,+ pr_state: null,+ },+ },+ ]),+ getTask: vi.fn().mockResolvedValue(task),+ };+ const states = await new ReportImplementationService().loadStates(+ client as unknown as PostHogAPIClient,+ [task.id, "no-pr"].map((id) =>+ report({ id, assignee: { kind: "task", task_id: id } }),+ ),+ );+ expect(states.get(task.id)).toBe("in_review");+ expect(states.get("no-pr")).toBe("no_pr");+ expect(client.getTask).toHaveBeenCalledExactlyOnceWith(task.id);+ },+ );++ it("checks legacy completed PR output once per task version and client", async () => {+ const task = implementationTask("completed", {+ pr_url: "https://github.com/example/project/pull/1",+ });+ const summary = {+ ...task,+ latest_run: { id: "run-1", status: "completed" },+ };+ const client = {+ getTaskSummaries: vi.fn().mockResolvedValue([summary]),+ getTask: vi.fn().mockResolvedValue(task),+ };+ const reports = [report({ assignee: { kind: "task", task_id: task.id } })];+ const service = new ReportImplementationService();+ const load = () =>+ service.loadStates(client as unknown as PostHogAPIClient, reports);+ expect((await load()).get("r")).toBe("in_review");+ await load();+ expect(client.getTask).toHaveBeenCalledOnce();+ client.getTaskSummaries.mockResolvedValue([+ { ...summary, updated_at: "2026-09-02T00:00:00Z" },+ ]);+ client.getTask.mockResolvedValue(+ implementationTask("completed", { pr_state: "closed" }),+ );+ expect((await load()).get("r")).toBe("no_pr");+ expect(client.getTask).toHaveBeenCalledTimes(2);+ const otherClient = {+ ...client,+ getTask: vi.fn().mockResolvedValue(implementationTask("completed")),+ };+ await service.loadStates(+ otherClient as unknown as PostHogAPIClient,+ reports,+ );+ expect(otherClient.getTask).toHaveBeenCalledOnce();+ });++ it("refreshes completed PR output even if the task timestamp does not change", async () => {+ const now = vi.spyOn(Date, "now").mockReturnValue(0);+ try {+ const task = implementationTask("completed", {+ pr_url: "https://github.com/example/project/pull/1",+ });+ const client = {+ getTaskSummaries: vi+ .fn()+ .mockResolvedValue([+ { ...task, latest_run: { id: "run-1", status: "completed" } },+ ]),+ getTask: vi+ .fn()+ .mockResolvedValueOnce(task)+ .mockResolvedValue(+ implementationTask("completed", { pr_state: "closed" }),+ ),+ };+ const service = new ReportImplementationService();+ const reports = [+ report({ assignee: { kind: "task", task_id: task.id } }),+ ];+ expect(+ (+ await service.loadStates(+ client as unknown as PostHogAPIClient,+ reports,+ )+ ).get("r"),+ ).toBe("in_review");+ now.mockReturnValue(5 * 60_000);+ expect(+ (+ await service.loadStates(+ client as unknown as PostHogAPIClient,+ reports,+ )+ ).get("r"),+ ).toBe("no_pr");+ } finally {+ now.mockRestore();+ }+ });++ it("limits completed-task detail requests to ten at a time", async () => {+ const task = implementationTask("completed");+ const summaries = Array.from({ length: 25 }, (_, index) => ({+ ...task,+ id: `task-${index}`,+ }));+ const reports = summaries.map((summary) =>+ report({+ id: summary.id,+ assignee: { kind: "task", task_id: summary.id },+ }),+ );+ let active = 0;+ let maximum = 0;+ const client = {+ getTaskSummaries: vi.fn().mockResolvedValue(summaries),+ getTask: vi.fn().mockImplementation(async () => {+ active++;+ maximum = Math.max(maximum, active);+ await Promise.resolve();+ active--;+ return task;+ }),+ };+ const states = await new ReportImplementationService().loadStates(+ client as unknown as PostHogAPIClient,+ reports,+ );+ expect(client.getTask).toHaveBeenCalledTimes(25);+ expect(maximum).toBe(10);+ expect([...states.values()].every((state) => state === "no_pr")).toBe(true);+ });++ it("recovers a failed completed-task lookup on the next refresh", async () => {+ const task = implementationTask("completed");+ const client = {+ getTaskSummaries: vi+ .fn()+ .mockResolvedValue([+ { ...task, latest_run: { id: "run-1", status: "completed" } },+ ]),+ getTask: vi+ .fn()+ .mockRejectedValueOnce(new Error("Unavailable"))+ .mockResolvedValue(task),+ };+ const service = new ReportImplementationService();+ const reports = [report({ assignee: { kind: "task", task_id: task.id } })];+ expect(+ (+ await service.loadStates(client as unknown as PostHogAPIClient, reports)+ ).get("r"),+ ).toBe("unknown");+ expect(+ (+ await service.loadStates(client as unknown as PostHogAPIClient, reports)+ ).get("r"),+ ).toBe("no_pr");+ });+it.each([[{ status: "ready" }, "needsPr"],[@@ -61,4 +403,83 @@ describe("reportInboxSections", () => {expect(sections.reviewAndMerge.map((r) => r.id)).toEqual(["r1", "r2"]);expect(sections.needsPr.map((r) => r.id)).toEqual(["n1", "n2"]);});+ it.each([+ ["queued", "working", false],+ ["not_started", "working", false],+ ["in_progress", "working", false],+ ["failed", "failed", true],+ ["cancelled", "cancelled", true],+ ["completed", "no_pr", true],+ ] as const)(+ "keeps a %s implementation in the correct queue",+ (status, expected, needsDecision) => {+ const assignedReport = report({+ assignee: { kind: "task", task_id: "implementation-1" },+ work_state: "working",+ });+ const task = implementationTask(status);+ const state = deriveReportImplementationState(assignedReport, task);+ expect(state).toBe(expected);+ expect(needsImplementationDecision(state)).toBe(needsDecision);+ expect(assignedReport.status).toBe("ready");+ expect(partitionInboxReports([assignedReport]).needsPr).toEqual([+ assignedReport,+ ]);+ },+ );++ it.each([+ ["ready", undefined, false, "checking", false],+ ["ready", undefined, true, "unknown", true],+ ["pending_input", undefined, false, "needs_input", true],+ ["resolved", undefined, false, null, true],+ ["suppressed", undefined, false, null, true],+ ] as const)(+ "handles %s reports with unavailable task state",+ (status, task, failed, expected, needsDecision) => {+ const state = deriveReportImplementationState(+ report({+ status,+ assignee: { kind: "task", task_id: "implementation-1" },+ }),+ task,+ failed,+ );+ expect(state).toBe(expected);+ expect(needsImplementationDecision(state)).toBe(needsDecision);+ },+ );++ it("keeps a finished PR out of triage before report metadata refreshes", () => {+ const state = deriveReportImplementationState(+ report({ assignee: { kind: "task", task_id: "implementation-1" } }),+ implementationTask("completed", {+ pr_url: "https://github.com/example/project/pull/1",+ }),+ );+ expect(state).toBe("in_review");+ expect(needsImplementationDecision(state)).toBe(false);+ });++ it("does not hide reports on servers without task assignments", () => {+ expect(+ needsImplementationDecision(+ deriveReportImplementationState(report({}), undefined),+ ),+ ).toBe(true);+ });+ it.each(["merged", "closed"])(+ "returns reports with a %s earlier fix to triage",+ (prState) => {+ const state = deriveReportImplementationState(+ report({ assignee: { kind: "task", task_id: "implementation-1" } }),+ implementationTask("completed", {+ pr_url: "https://github.com/example/project/pull/1",+ pr_state: prState,+ }),+ );+ expect(state).toBe("no_pr");+ expect(needsImplementationDecision(state)).toBe(true);+ },+ );});diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex 46cf3e13e824..8f38854836eb 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -769,6 +769,11 @@ export interface SignalReport {source_products?: string[];/** PR URL from the latest implementation task run, if available. */implementation_pr_url?: string | null;+ work_state?: "unclaimed" | "working" | "in_review" | "done";+ assignee?: {+ kind: "user" | "task" | "agent" | "system";+ task_id: string | null;+ } | null;/*** Whether that PR merged (GitHub webhook). A merged PR is history, not work* in flight: a report can outlive its fix when evidence keeps arriving, anddiff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxDetailFrameView.stories.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxDetailFrameView.stories.tsxindex 8392c7fcecfc..1d94b0e82d59 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxDetailFrameView.stories.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxDetailFrameView.stories.tsx@@ -4,7 +4,6 @@ import {ClockCounterClockwiseIcon,EyeSlashIcon,FileTextIcon,- GitPullRequestIcon,MagnifyingGlassIcon,PlusIcon,ReceiptIcon,@@ -12,18 +11,25 @@ import {UsersThreeIcon,XIcon,} from "@phosphor-icons/react";-import { deriveReportVerdict } from "@posthog/core/inbox/reportVerdict";+import { useHostTRPC } from "@posthog/host-router/react";import { Button } from "@posthog/quill";import { DetailSection } from "@posthog/ui/features/inbox/components/DetailSection";import { InboxDetailFrameView } from "@posthog/ui/features/inbox/components/InboxDetailFrameView";import {+ inboxStoryImplementations,inboxStoryReport,inboxStorySignal,} from "@posthog/ui/features/inbox/components/inboxStoryFixtures";-import { ReportVerdictCallout } from "@posthog/ui/features/inbox/components/ReportVerdictCallout";+import { ReportVerdictBanner } from "@posthog/ui/features/inbox/components/ReportVerdictBanner";import { SignalsList } from "@posthog/ui/features/inbox/components/SignalsList";+import { PrDecisionBlock } from "@posthog/ui/features/pr-review/PrDecisionBlock";+import { PrFilesChangedSection } from "@posthog/ui/features/pr-review/PrFilesChangedSection";import type { Meta, StoryObj } from "@storybook/react-vite";+import { useQueryClient } from "@tanstack/react-query";import type { ReactNode } from "react";+import { expect, waitFor } from "storybook/test";+import { ReportFeedbackFooter } from "./detail/ReportFeedbackFooter";+import { InboxStoryData } from "./InboxStoryData";const report = inboxStoryReport();const signals = [@@ -45,8 +51,31 @@ const pageAt = (width: number) => (Story: () => ReactNode) => (const meta: Meta<typeof InboxDetailFrameView> = {title: "Inbox/Reports/Single report",component: InboxDetailFrameView,+ tags: ["inbox"],parameters: { layout: "fullscreen" },- decorators: [pageAt(1360)],+ decorators: [+ pageAt(1360),+ (Story, context) => (+ <InboxStoryData report={context.args.report}>+ <Story />+ </InboxStoryData>+ ),+ ],+ render: (args) => (+ <InboxDetailFrameView+ {...args}+ belowSummary={+ args.belowSummary === undefined ? (+ <ReportVerdictBanner report={args.report} />+ ) : (+ args.belowSummary+ )+ }+ footer={+ <ReportFeedbackFooter key={args.report.id} report={args.report} />+ }+ />+ ),args: {report,fallbackTitle: "Untitled report",@@ -71,36 +100,6 @@ const meta: Meta<typeof InboxDetailFrameView> = {evidenceSection: { Icon: MagnifyingGlassIcon, title: "Evidence" },evidenceCount: signals.length,evidenceContent: <SignalsList signals={signals} />,- belowSummary: (- <div className="flex select-none flex-col gap-3 rounded-lg border border-(--amber-6) bg-(--amber-2) p-4">- <div className="flex flex-col gap-1">- <span className="font-semibold text-[15px] text-gray-12">- Needs your decision- </span>- <span className="text-[14px] text-gray-11">- The agent can fix this with code and open a pull request. The report- reopens if the problem comes back.- </span>- </div>- <div className="flex flex-wrap items-center gap-2.5">- <Button type="button" variant="primary">- <GitPullRequestIcon />- Implement- </Button>- <Button type="button" variant="outline">- <ChatCircleIcon />- Ask about it- </Button>- <Button type="button" variant="outline">- <EyeSlashIcon />- Dismiss…- </Button>- </div>- </div>- ),- footer: (- <p className="m-0 text-[13px] text-gray-11">Was this report useful?</p>- ),children: (<><DetailSection@@ -159,63 +158,31 @@ type Story = StoryObj<typeof InboxDetailFrameView>;export const EvidenceFirst: Story = {};export const LikelyAlreadyFixed: Story = {- args: {- report: inboxStoryReport({ already_addressed: true }),- belowSummary: (- <ReportVerdictCallout- verdict={deriveReportVerdict(- inboxStoryReport({ already_addressed: true }),- { hasExistingPr: false },- )}- >- <div className="flex flex-wrap items-center gap-2.5">- <Button variant="outline">- <ChatCircleIcon />- Ask about it- </Button>- <Button variant="outline">- <EyeSlashIcon />- Dismiss…- </Button>- </div>- </ReportVerdictCallout>- ),- },+ args: { report: inboxStoryReport({ already_addressed: true }) },};export const WaitingForInput: Story = {- args: {- report: inboxStoryReport({- status: "pending_input",- actionability: "requires_human_input",- }),- belowSummary: (- <div className="flex select-none flex-col gap-3 rounded-lg border border-(--amber-6) bg-(--amber-2) p-4">- <div className="flex flex-col gap-1">- <span className="font-semibold text-[15px] text-gray-12">- Waiting on you- </span>- <span className="text-[14px] text-gray-11">- Review the recommendation. Start an implementation task to add- direction and choose a model, or ask for more context.- </span>- </div>- <div className="flex flex-wrap items-center gap-2.5">- <Button type="button" variant="primary">- <GitPullRequestIcon />- Implement- </Button>- <Button type="button" variant="outline">- <ChatCircleIcon />- Ask about it- </Button>- <Button type="button" variant="outline">- <EyeSlashIcon />- Dismiss…- </Button>- </div>- </div>- ),+ args: { report: inboxStoryImplementations[2].report },+};++export const CreatingPr: Story = {+ args: { report: inboxStoryImplementations[0].report },+};++export const FailedTask: Story = {+ args: { report: inboxStoryImplementations[1].report },+};++export const Feedback: Story = {+ play: async ({ canvas, userEvent }): Promise<void> => {+ await userEvent.click(+ await canvas.findByRole("button", { name: "This report was useful" }),+ );+ await expect(canvas.getByText("Thanks for the feedback")).toBeVisible();+ await userEvent.click(canvas.getByRole("button", { name: "Add a note" }));+ await expect(+ canvas.getByRole("textbox", { name: "Add a note about this report" }),+ ).toBeVisible();},};@@ -240,11 +207,53 @@ export const Narrow: Story = {decorators: [pageAt(520)],};+const prUrl = "https://github.com/example/project/pull/42";+export const WithPullRequest: Story = {+ decorators: [+ (Story, context) => {+ const trpc = useHostTRPC();+ const queryClient = useQueryClient();+ queryClient.setQueryData(trpc.git.getPrInfoByUrl.queryKey({ prUrl }), {+ number: 42,+ title: "Coalesce pending cohort calculations",+ body: "Keep only the newest queued calculation.",+ author: null,+ state: "open",+ merged: false,+ draft: context.parameters.draft ?? false,+ mergeable: true,+ mergeStateStatus: "clean",+ baseRefName: "main",+ headRefName: "fix-cohort-queue",+ additions: 1,+ deletions: 1,+ changedFiles: 1,+ });+ queryClient.setQueryData(trpc.git.getPrChecks.queryKey({ prUrl }), [+ {+ name: "Unit tests",+ bucket: context.parameters.failing ? "fail" : "pass",+ link: null,+ workflow: "Tests",+ description: null,+ },+ ]);+ queryClient.setQueryData(trpc.git.getPrChangedFiles.queryKey({ prUrl }), [+ {+ path: "src/cohortQueue.ts",+ status: "modified",+ linesAdded: 1,+ linesRemoved: 1,+ patch:+ "diff --git a/src/cohortQueue.ts b/src/cohortQueue.ts\n--- a/src/cohortQueue.ts\n+++ b/src/cohortQueue.ts\n@@ -1,3 +1,3 @@\n export function enqueue(cohortId: string) {\n- return queue.add(cohortId);\n+ return queue.replacePending(cohortId);\n }\n",+ },+ ]);+ return <Story />;+ },+ ],args: {- report: inboxStoryReport({- implementation_pr_url: "https://github.com/example/project/pull/42",- }),+ report: inboxStoryReport({ implementation_pr_url: prUrl }),primaryAction: (<><Button variant="outline" size="sm">@@ -264,11 +273,51 @@ export const WithPullRequest: Story = {</Button></>),- summarySection: { Icon: FileTextIcon, title: "Summary" },secondaryTab: {label: "Changed code",- content: <p>Changed files appear here.</p>,+ content: <PrFilesChangedSection prUrl={prUrl} bare />,},- belowSummary: null,+ belowSummary: <PrDecisionBlock prUrl={prUrl} />,+ children: (+ <DetailSection Icon={UsersThreeIcon} title="Reviewers" collapsible>+ <p className="text-[13px] text-gray-11">Example reviewer</p>+ </DetailSection>+ ),},};++export const DraftPullRequest: Story = {+ ...WithPullRequest,+ parameters: { draft: true },+};++export const FailingPullRequest: Story = {+ ...WithPullRequest,+ parameters: { failing: true },+};++export const ChangedCode: Story = {+ ...WithPullRequest,+ play: async ({ canvas, canvasElement, userEvent }): Promise<void> => {+ await userEvent.click(+ await canvas.findByRole("tab", { name: "Changed code" }),+ );+ await expect(await canvas.findByText("1 file changed")).toBeVisible();+ await waitFor(() => {+ const diffText = Array.from(canvasElement.querySelectorAll("*"))+ .map((element) => element.shadowRoot?.textContent ?? "")+ .join(" ");+ expect(diffText).toContain("queue.replacePending");+ });+ },+};++export const NarrowPullRequest: Story = {+ ...WithPullRequest,+ decorators: [...(WithPullRequest.decorators ?? []), pageAt(520)],+};++export const NarrowChangedCode: Story = {+ ...ChangedCode,+ decorators: [...(WithPullRequest.decorators ?? []), pageAt(520)],+};diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxPane.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxPane.tsxindex 08ab89737ca3..9ee37499dc16 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxPane.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxPane.tsx@@ -65,6 +65,7 @@ export function InboxPane({ className }: { className?: string }): ReactElement {<InboxPaneRowkey={report.id}report={report}+ implementationState={inbox.implementationStates.get(report.id)}optionValue={report.id}isSelected={report.id === selectedReportId}/>diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxPanePresentation.stories.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxPanePresentation.stories.tsxindex 82c753d7a85c..31219956d53d 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxPanePresentation.stories.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxPanePresentation.stories.tsx@@ -1,3 +1,5 @@+import { inboxReportKeys } from "@posthog/core/inbox/inboxQuery";+import { deriveReportImplementationState } from "@posthog/core/inbox/reportImplementation";import { Button } from "@posthog/quill";import type { SignalReport } from "@posthog/shared/types";import {@@ -8,12 +10,20 @@ import { authKeys } from "@posthog/ui/features/auth/useCurrentUser";import { InboxFilterMenu } from "@posthog/ui/features/inbox/components/InboxFilterMenu";import { InboxPanePresentation } from "@posthog/ui/features/inbox/components/InboxPanePresentation";import { InboxPaneRow } from "@posthog/ui/features/inbox/components/InboxPaneRow";-import { inboxStoryReport } from "@posthog/ui/features/inbox/components/inboxStoryFixtures";+import {+ inboxStoryImplementations,+ inboxStoryReport,+} from "@posthog/ui/features/inbox/components/inboxStoryFixtures";import { useInboxReportReadStore } from "@posthog/ui/features/inbox/stores/inboxReportReadStore";import { CHANNELS_SIDEBAR_MIN_WIDTH } from "@posthog/ui/features/sidebar/constants";import type { Meta, StoryObj } from "@storybook/react-vite";import { useQueryClient } from "@tanstack/react-query";-import { type ReactNode, useEffect } from "react";+import { type ReactNode, useEffect, useState } from "react";+import { expect, waitFor, within } from "storybook/test";+import { useInboxAvailableSuggestedReviewersStore } from "../inboxAvailableSuggestedReviewersStore";+import { useInboxReviewerScopeStore } from "../stores/inboxReviewerScopeStore";+import { useInboxSignalsFilterStore } from "../stores/inboxSignalsFilterStore";+import { InboxStoryData } from "./InboxStoryData";function WithReadState({children,@@ -23,6 +33,28 @@ function WithReadState({const queryClient = useQueryClient();useEffect(() => {const previousAuth = useAuthStore.getState().authState;+ const previousRead = useInboxReportReadStore.getState();+ const previousScope = useInboxReviewerScopeStore.getState();+ const previousFilters = useInboxSignalsFilterStore.getState();+ const previousReviewers =+ useInboxAvailableSuggestedReviewersStore.getState();+ const previousUser = queryClient.getQueryData(authKeys.currentUser("us:1"));+ useInboxReviewerScopeStore.setState({ scope: "for-you" });+ useInboxSignalsFilterStore.getState().resetFilters();+ const reviewers = Array.from({ length: 25 }, (_, index) => ({+ uuid: `reviewer-${index + 1}`,+ name: `Example reviewer ${String(index + 1).padStart(2, "0")}`,+ email: `reviewer${index + 1}@example.com`,+ github_login: `example-reviewer-${index + 1}`,+ }));+ const reviewersKey = inboxReportKeys.availableSuggestedReviewers("us:1:");+ queryClient.setQueryData(reviewersKey, {+ results: reviewers,+ count: reviewers.length,+ });+ useInboxAvailableSuggestedReviewersStore+ .getState()+ .setReviewersForAuthIdentity("us:1", reviewers);queryClient.setQueryData(authKeys.currentUser("us:1"), {uuid: "storybook-reader",});@@ -42,6 +74,18 @@ function WithReadState({});return () => {useAuthStore.setState({ authState: previousAuth });+ useInboxReportReadStore.setState(previousRead);+ useInboxReviewerScopeStore.setState(previousScope);+ useInboxSignalsFilterStore.setState(previousFilters);+ useInboxAvailableSuggestedReviewersStore.setState(previousReviewers);+ queryClient.removeQueries({ queryKey: reviewersKey, exact: true });+ if (previousUser)+ queryClient.setQueryData(authKeys.currentUser("us:1"), previousUser);+ else+ queryClient.removeQueries({+ queryKey: authKeys.currentUser("us:1"),+ exact: true,+ });};}, [queryClient]);return <>{children}</>;@@ -83,6 +127,11 @@ function paneRow(report: SignalReport): React.JSX.Element {<InboxPaneRowkey={report.id}report={report}+ implementationState={deriveReportImplementationState(+ report,+ inboxStoryImplementations.find((entry) => entry.report.id === report.id)+ ?.task,+ )}optionValue={report.id}isSelected={report.id === "needs-1"}/>@@ -92,6 +141,7 @@ function paneRow(report: SignalReport): React.JSX.Element {const meta: Meta<typeof InboxPanePresentation> = {title: "Inbox/Reports/Sidebar pane",component: InboxPanePresentation,+ tags: ["inbox"],parameters: { layout: "fullscreen" },decorators: [(Story) => (@@ -100,11 +150,28 @@ const meta: Meta<typeof InboxPanePresentation> = {style={{ width: CHANNELS_SIDEBAR_MIN_WIDTH }}><WithReadState>- <Story />+ <InboxStoryData>+ <Story />+ </InboxStoryData></WithReadState></div>),],+ render: function SearchablePane(args) {+ const [query, setQuery] = useState(args.query);+ return (+ <InboxPanePresentation+ {...args}+ query={query}+ onQueryChange={setQuery}+ reports={args.reports.filter((report) =>+ `${report.title} ${report.summary}`+ .toLowerCase()+ .includes(query.toLowerCase()),+ )}+ />+ );+ },args: {reports,query: "",@@ -148,3 +215,73 @@ export const FiltersActive: Story = {filterControl: <InboxFilterMenu active onClearFilters={() => {}} />,},};++export const ImplementationProgress: Story = {+ args: {+ reports: [+ reports[0],+ ...inboxStoryImplementations.map((entry) => entry.report),+ ],+ },+};++export const SearchReports: Story = {+ play: async ({ canvas, userEvent }): Promise<void> => {+ await userEvent.type(+ await canvas.findByRole("combobox", { name: "Search reports" }),+ "buffer",+ );+ await expect(+ canvas.getByText("Expose buffer health in the player controls"),+ ).toBeVisible();+ await expect(+ canvas.queryByText("Avoid duplicate evaluations after a reconnect"),+ ).not.toBeInTheDocument();+ },+};++export const ReadAndUnread: Story = {+ play: async ({ canvas, canvasElement, userEvent }): Promise<void> => {+ const unreadButtons = await canvas.findAllByRole("button", {+ name: "Mark report as read",+ });+ const unreadCount = unreadButtons.length;+ await userEvent.click(unreadButtons[0]);+ await expect(+ canvas.getAllByRole("button", { name: "Mark report as read" }),+ ).toHaveLength(unreadCount - 1);+ await userEvent.pointer({+ target: canvas.getByRole("option", {+ name: /keep recurring calculations/i,+ }),+ keys: "[MouseRight]",+ });+ const body = within(canvasElement.ownerDocument.body);+ await userEvent.click(+ await body.findByRole("menuitem", { name: "Mark as unread" }),+ );+ await expect(+ canvas.getAllByRole("button", { name: "Mark report as read" }),+ ).toHaveLength(unreadCount);+ },+};++export const ScopeSearch: Story = {+ play: async ({ canvas, canvasElement, userEvent }): Promise<void> => {+ await userEvent.click(+ await canvas.findByRole("button", { name: "Filter reports" }),+ );+ const body = within(canvasElement.ownerDocument.body);+ await userEvent.hover(await body.findByRole("menuitem", { name: /Scope/ }));+ const search = await body.findByPlaceholderText("Search users…");+ await expect(search).toHaveValue("");+ await expect(await body.findByText("Example reviewer 01")).toBeVisible();+ await expect(+ body.queryByText("Example reviewer 25"),+ ).not.toBeInTheDocument();+ await waitFor(() => expect(search).toBeVisible());+ search.focus();+ await userEvent.type(search, "[email protected]", { skipClick: true });+ await expect(await body.findByText("Example reviewer 25")).toBeVisible();+ },+};diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxPaneRow.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxPaneRow.tsxindex af7d6c2090ab..d27665bb5712 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxPaneRow.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxPaneRow.tsx@@ -1,3 +1,5 @@+import type { ReportImplementationState } from "@posthog/core/inbox/reportImplementation";+import { REPORT_IMPLEMENTATION_LABELS } from "@posthog/core/inbox/reportImplementation";import {deriveHeadline,humanizeReportTitle,@@ -16,10 +18,12 @@ import type { ReactElement } from "react";/** One report in the rail's Self-driving list. */export function InboxPaneRow({report,+ implementationState,isSelected,optionValue,}: {report: SignalReport;+ implementationState?: ReportImplementationState | null;isSelected: boolean;optionValue: string;}): ReactElement {@@ -36,6 +40,17 @@ export function InboxPaneRow({const pr = report.implementation_pr_url? parsePrUrl(report.implementation_pr_url): null;+ // An explicit aria-label replaces the row's descendant text in the+ // accessible name, so the implementation status the badge below shows has to+ // be named here too. Without it a screen reader cannot tell a report whose+ // task is working from one whose task failed.+ const label = [+ title,+ report.priority ? `priority ${report.priority}` : "priority unknown",+ implementationState && REPORT_IMPLEMENTATION_LABELS[implementationState],+ ]+ .filter(Boolean)+ .join(", ");return (<InboxReportContextMenu report={report}>@@ -43,11 +58,7 @@ export function InboxPaneRow({<AutocompleteItemvalue={optionValue}nativeButton- aria-label={- report.priority- ? `${title}, priority ${report.priority}`- : `${title}, priority unknown`- }+ aria-label={label}className={cn("h-auto w-full items-start py-1.5 pr-8 text-left ring-offset-0 data-highlighted:border-transparent data-highlighted:bg-fill-hover data-highlighted:ring-0 [&>span]:w-full [&>span]:items-start [&>span]:gap-2",isSelected && "bg-fill-selected",@@ -72,6 +83,17 @@ export function InboxPaneRow({{headline}</span>)}+ {implementationState && (+ <span+ className={`mt-1 flex items-center gap-1.5 text-[12px] ${implementationState === "working" ? "text-blue-11" : "text-amber-11"}`}+ >+ <span+ aria-hidden="true"+ className="size-1.5 rounded-full bg-current"+ />+ {REPORT_IMPLEMENTATION_LABELS[implementationState]}+ </span>+ )}<span className="mt-1 block truncate text-muted-foreground/70 text-xxs">{formatRelativeAge(report.created_at)}{pr ? ` · ${pr.repoSlug}` : ""}diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxReportRow.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxReportRow.tsxindex 7c1225611483..345b11fa4559 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxReportRow.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxReportRow.tsx@@ -1,3 +1,4 @@+import type { ReportImplementationState } from "@posthog/core/inbox/reportImplementation";import type { SignalReport } from "@posthog/shared/types";import { InboxReportContextMenu } from "@posthog/ui/features/inbox/components/InboxReportContextMenu";import { InboxReportRowView } from "@posthog/ui/features/inbox/components/InboxReportRowView";@@ -9,8 +10,10 @@ import { openExternalUrl } from "@posthog/ui/shell/openExternal";export function InboxReportRow({report,+ implementationState,}: {report: SignalReport;+ implementationState?: ReportImplementationState | null;}): React.JSX.Element {const { pointerHandlers } = useInboxReportDetailPrefetch({to: "/reports/$reportId",@@ -21,6 +24,7 @@ export function InboxReportRow({<InboxReportContextMenu report={report}><InboxReportRowViewreport={report}+ implementationState={implementationState}prefetchHandlers={pointerHandlers}reviewers={<SuggestedReviewerAvatarStack report={report} />}restoreAction={<ReportRestoreButton report={report} />}diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxReportRowView.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxReportRowView.tsxindex 5ced7b3ae5d6..50d4c5c54b0a 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxReportRowView.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxReportRowView.tsx@@ -3,6 +3,10 @@ import {GitMergeIcon,GitPullRequestIcon,} from "@phosphor-icons/react";+import {+ REPORT_IMPLEMENTATION_LABELS,+ type ReportImplementationState,+} from "@posthog/core/inbox/reportImplementation";import {deriveHeadline,humanizeReportTitle,@@ -19,6 +23,7 @@ import type { HTMLAttributes, ReactNode } from "react";export interface InboxReportRowViewProps {report: SignalReport;+ implementationState?: ReportImplementationState | null;reviewers?: ReactNode;restoreAction?: ReactNode;prefetchHandlers?: Pick<@@ -31,6 +36,7 @@ export interface InboxReportRowViewProps {export function InboxReportRowView({report,+ implementationState,reviewers,restoreAction,prefetchHandlers,@@ -89,6 +95,17 @@ export function InboxReportRowView({{headline}</span>)}+ {implementationState && (+ <span+ className={`flex items-center gap-1.5 text-[12px] ${implementationState === "working" ? "text-blue-11" : "text-amber-11"}`}+ >+ <span+ aria-hidden="true"+ className="size-1.5 rounded-full bg-current"+ />+ {REPORT_IMPLEMENTATION_LABELS[implementationState]}+ </span>+ )}<span className="flex min-w-0 items-center gap-1.5 overflow-hidden text-[12.5px] text-gray-10">{pr && (<span title={pr.repoSlug} className="max-w-48 truncate font-medium">diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxStoryData.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxStoryData.tsxnew file mode 100644index 000000000000..e51ea6d82580--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxStoryData.tsx@@ -0,0 +1,65 @@+import { inboxReportKeys } from "@posthog/core/inbox/inboxQuery";+import type { SignalReport } from "@posthog/shared/types";+import { inboxStoryImplementations } from "@posthog/ui/features/inbox/components/inboxStoryFixtures";+import type { ReportTaskData } from "@posthog/ui/features/inbox/hooks/useReportTasks";+import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";+import { useQueryClient } from "@tanstack/react-query";+import { type ReactNode, useEffect, useState } from "react";++export function InboxStoryData({+ report,+ children,+}: {+ report?: SignalReport;+ children: ReactNode;+}): ReactNode {+ const queryClient = useQueryClient();+ const [seeded, setSeeded] = useState<{+ report?: SignalReport;+ queryClient: typeof queryClient;+ } | null>(null);+ useEffect(() => {+ const storyReports = [+ ...inboxStoryImplementations.map((entry) => entry.report),+ ...(report ? [report] : []),+ ];+ const previous = new Map<readonly unknown[], unknown>();+ const seed = (queryKey: readonly unknown[], data: unknown): void => {+ previous.set(queryKey, queryClient.getQueryData(queryKey));+ queryClient.setQueryData(queryKey, data);+ };+ for (const item of Array.from(+ new Map(storyReports.map((item) => [item.id, item])).values(),+ )) {+ const task = inboxStoryImplementations.find(+ (entry) => entry.report.id === item.id,+ )?.task;+ const tasks: ReportTaskData[] = task+ ? [+ {+ task,+ purpose: "implementation",+ purposeLabel: "Implementation",+ startedAt: task.created_at,+ },+ ]+ : [];+ const tasksKey = ["inbox", "report-tasks", item.id];+ const artefactsKey = inboxReportKeys.artefacts(item.id);+ seed(tasksKey, tasks);+ seed(artefactsKey, { results: [], count: 0 });+ if (task) seed(taskDetailQuery(task.id).queryKey, task);+ }+ setSeeded({ report, queryClient });+ return () => {+ for (const [queryKey, data] of previous) {+ if (data === undefined)+ queryClient.removeQueries({ queryKey, exact: true });+ else queryClient.setQueryData(queryKey, data);+ }+ };+ }, [queryClient, report]);+ return seeded?.queryClient === queryClient && seeded.report === report+ ? children+ : null;+}diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxTriagePane.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxTriagePane.tsxindex dc6f4860eec3..ec2237537530 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxTriagePane.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxTriagePane.tsx@@ -1,4 +1,3 @@-import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import { ReportTriageFocus } from "@posthog/ui/features/inbox/components/ReportTriageFocus";import { useInboxTriageOrigin } from "@posthog/ui/features/inbox/hooks/useInboxBackTarget";import { useInboxSectionedReports } from "@posthog/ui/features/inbox/hooks/useInboxSectionedReports";@@ -11,17 +10,23 @@ import { useNavigate } from "@tanstack/react-router";import type { ReactElement } from "react";export function InboxTriagePane(): ReactElement {- // Beside the rail the sidebar list owns paging; without it, nothing else is- // reading this list, so triage walks the pages itself.- const spacesLayout = useChannelsLayout();- const inbox = useInboxSectionedReports({ autoPage: !spacesLayout });+ const inbox = useInboxSectionedReports({ autoPage: true });const triageOrigin = useInboxTriageOrigin();const hasActiveFilters = useInboxSignalsFilterStore(hasActiveReportsListFilters,);const navigate = useNavigate();- if (inbox.isLoading) {+ // The queue is filtered by task state, so a loaded page can hold no decision+ // while a later page still does. Handing that page to triage would end the+ // session and record a triage that was never done. Task state is waited on+ // the same way, because Create PR reloads it: blanking a queue that is on+ // screen unmounts triage and loses the place the reader had in it.+ if (+ inbox.isLoading ||+ (inbox.triageReports.length === 0 &&+ (inbox.triageLoading || inbox.triagePagePending))+ ) {return <LoadingState className="h-full" />;}diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.dismiss.test.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.dismiss.test.tsxindex e12ccc74c209..ec1871c255b2 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.dismiss.test.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.dismiss.test.tsx@@ -139,4 +139,24 @@ describe("ReportTriageFocus dismiss", () => {settle({ ...reports[0], status: "suppressed" });});});+ it("keeps the selected report when work returns and advances when it leaves", async () => {+ const first = reports[0];+ const second = { ...first, id: "report-2", title: "Second report" };+ const third = { ...first, id: "report-3", title: "Third report" };+ const props = {+ allReports: [first, second, third],+ scope: INBOX_SCOPE_ENTIRE_PROJECT,+ hasActiveFilters: false,+ onExit: vi.fn(),+ };+ const { rerender } = render(+ <ReportTriageFocus {...props} reports={[second, third]} />,+ { wrapper: createWrapper() },+ );+ expect(screen.getByText("Second report")).toBeInTheDocument();+ rerender(<ReportTriageFocus {...props} reports={[first, second, third]} />);+ expect(screen.getByText("Second report")).toBeInTheDocument();+ rerender(<ReportTriageFocus {...props} reports={[first, third]} />);+ expect(screen.getByText("Third report")).toBeInTheDocument();+ });});diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.tsxindex 3698e793adad..c7c9931472de 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.tsx@@ -76,6 +76,7 @@ export function ReportTriageFocus({: -1;return Math.max(0, initialIndex);});+ const [selectedReportId, setSelectedReportId] = useState(reports[index]?.id);const [expanded, setExpanded] = useState(false);const chatOpen = useReportChatPanelStore((state) => state.open);const setChatOpen = useReportChatPanelStore((state) => state.setOpen);@@ -108,7 +109,13 @@ export function ReportTriageFocus({// The queue shrinks under us when a report is archived; clamping (rather// than resetting) is what makes archive-and-advance work.- const clamped = Math.min(index, Math.max(0, reports.length - 1));+ const selectedIndex = reports.findIndex(+ (item) => item.id === selectedReportId,+ );+ const clamped =+ selectedIndex >= 0+ ? selectedIndex+ : Math.min(index, Math.max(0, reports.length - 1));const report = reports[clamped];const reportId = report?.id;const {@@ -156,6 +163,11 @@ export function ReportTriageFocus({setChatOpen(false);}, [finishSession, reportId, setChatOpen]);+ useEffect(() => {+ setSelectedReportId(reportId);+ setIndex(clamped);+ }, [reportId, clamped]);+// Triage is intentionally sequential, so the next destination is known as// soon as the card renders. Warm it before navigation so the detail route// does not begin its work only after the user opens it.@@ -186,12 +198,12 @@ export function ReportTriageFocus({// refetch lands. Moving the index before that would skip the next report.const goNext = useCallback(() => {if (removingReviewer) return;- setIndex((i) => Math.min(i + 1, reports.length - 1));- }, [reports.length, removingReviewer]);+ setSelectedReportId(reports[Math.min(clamped + 1, reports.length - 1)]?.id);+ }, [clamped, reports, removingReviewer]);const goPrev = useCallback(() => {if (removingReviewer) return;- setIndex((i) => Math.max(i - 1, 0));- }, [removingReviewer]);+ setSelectedReportId(reports[Math.max(clamped - 1, 0)]?.id);+ }, [clamped, reports, removingReviewer]);const handleExit = useCallback(() => {finishSession("exited");onExit();diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocusView.stories.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocusView.stories.tsxindex b9726b77707c..a6fb9591381c 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocusView.stories.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocusView.stories.tsx@@ -1,16 +1,13 @@-import {- ArrowSquareOutIcon,- CheckCircleIcon,- EyeSlashIcon,- FileTextIcon,- GitPullRequestIcon,-} from "@phosphor-icons/react";+import { FileTextIcon } from "@phosphor-icons/react";import { Button } from "@posthog/quill";import { useRailSurface } from "@posthog/ui/features/canvas/hooks/useRailSurface";import { InboxDetailFrameView } from "@posthog/ui/features/inbox/components/InboxDetailFrameView";import { InboxPanePresentation } from "@posthog/ui/features/inbox/components/InboxPanePresentation";import { InboxPaneRow } from "@posthog/ui/features/inbox/components/InboxPaneRow";-import { inboxStoryReport } from "@posthog/ui/features/inbox/components/inboxStoryFixtures";+import {+ inboxStoryImplementations,+ inboxStoryReport,+} from "@posthog/ui/features/inbox/components/inboxStoryFixtures";import {ReportTriageFocusView,type ReportTriageFocusViewProps,@@ -18,7 +15,10 @@ import {import { isInboxTriagePath } from "@posthog/ui/features/inbox/triageRoute";import type { Meta, StoryObj } from "@storybook/react-vite";import { useNavigate, useRouterState } from "@tanstack/react-router";-import { type ReactNode, useEffect } from "react";+import { type ReactNode, useEffect, useState } from "react";+import { expect, waitFor, within } from "storybook/test";+import { InboxStoryData } from "./InboxStoryData";+import { ReportVerdictBanner } from "./ReportVerdictBanner";const report = inboxStoryReport();const previousReport = inboxStoryReport({@@ -33,78 +33,55 @@ const nextReport = inboxStoryReport({});const viewportAt = (width: number) => (Story: () => ReactNode) => (- <div className="h-[760px] bg-gray-1" style={{ width }}>+ <div className="h-[760px] w-full bg-gray-1" style={{ maxWidth: width }}><Story /></div>);-function createPrActions(): React.JSX.Element {- return (- <div className="flex flex-wrap items-center gap-2.5">- <Button- type="button"- variant="outline"- className="h-9 gap-2 px-4 text-[14px]"- >- <CheckCircleIcon />- Resolve- </Button>- <Button- type="button"- variant="outline"- className="h-9 gap-2 px-4 text-[14px]"- >- <EyeSlashIcon />- Dismiss- </Button>- <Button- type="button"- variant="primary"- className="h-9 gap-2 px-4 text-[14px]"- >- <GitPullRequestIcon />- Create PR- </Button>- </div>- );-}--function openPrActions(): React.JSX.Element {+function TriagePreview(props: ReportTriageFocusViewProps): React.JSX.Element {+ const reports = [props.report, nextReport];+ const [index, setIndex] = useState(0);+ const [expanded, setExpanded] = useState(props.expanded);+ const current = reports[index];return (- <div className="flex flex-wrap items-center gap-2.5">- <Button- type="button"- variant="outline"- className="h-9 gap-2 px-4 text-[14px]"- >- <CheckCircleIcon />- Resolve- </Button>- <Button- type="button"- variant="outline"- className="h-9 gap-2 px-4 text-[14px]"- >- <EyeSlashIcon />- Dismiss- </Button>- <Button- type="button"- variant="primary"- className="h-9 gap-2 px-4 text-[14px]"- >- <ArrowSquareOutIcon />- View PR on GitHub- </Button>- </div>+ <InboxStoryData key={current.id} report={current}>+ <ReportTriageFocusView+ {...props}+ report={current}+ position={index + 1}+ total={reports.length}+ previousReport={reports[index - 1] ?? null}+ nextReport={reports[index + 1] ?? null}+ expanded={expanded}+ actions={+ <ReportVerdictBanner+ key={current.id}+ report={current}+ variant="triage-actions"+ surface="triage"+ />+ }+ onPrevious={() => {+ setIndex(Math.max(0, index - 1));+ setExpanded(false);+ }}+ onNext={() => {+ setIndex(Math.min(reports.length - 1, index + 1));+ setExpanded(false);+ }}+ onToggleSummary={() => setExpanded(!expanded)}+ />+ </InboxStoryData>);}const meta: Meta<typeof ReportTriageFocusView> = {title: "Inbox/Reports/Triage mode",component: ReportTriageFocusView,+ tags: ["inbox"],parameters: { layout: "fullscreen" },decorators: [viewportAt(1100)],+ render: (args) => <TriagePreview {...args} />,args: {report,position: 2,@@ -116,7 +93,13 @@ const meta: Meta<typeof ReportTriageFocusView> = {expanded: false,prShortcut: "create",canRemoveSelfFromReviewers: true,- actions: createPrActions(),+ actions: (+ <ReportVerdictBanner+ report={report}+ variant="triage-actions"+ surface="triage"+ />+ ),reviewers: (<span className="rounded bg-(--gray-3) px-1.5 py-0.5 text-[12px] text-gray-11">2 reviewers@@ -135,13 +118,47 @@ type Story = StoryObj<typeof ReportTriageFocusView>;export const NeedsAPr: Story = {};-export const ExistingPr: Story = {- args: {- report: inboxStoryReport({- implementation_pr_url: "https://github.com/PostHog/posthog/pull/12345",- }),- prShortcut: "open",- actions: openPrActions(),+export const FailedTask: Story = {+ args: { report: inboxStoryImplementations[1].report },+ play: async ({ canvas }): Promise<void> => {+ await expect(+ await canvas.findByText(/PR task failed. Open the report to continue/),+ ).toBeVisible();+ },+};++export const WaitingOnYou: Story = {+ args: { report: inboxStoryImplementations[2].report, prShortcut: null },+};++export const NoPrCreated: Story = {+ args: { report: inboxStoryImplementations[4].report },+};++export const ReadAndNavigate: Story = {+ play: async ({ canvas, userEvent }): Promise<void> => {+ await userEvent.click(+ await canvas.findByRole("button", { name: "Read summary" }),+ );+ await expect(+ canvas.getByRole("button", { name: "Hide summary" }),+ ).toBeVisible();+ await userEvent.click(+ canvas.getByRole("button", { name: /preserve breakdown order/ }),+ );+ await expect(+ canvas.getByRole("heading", { name: /preserve breakdown order/ }),+ ).toBeVisible();+ },+};++export const CreatePrOptions: Story = {+ play: async ({ canvas, canvasElement, userEvent }): Promise<void> => {+ await userEvent.click(+ await canvas.findByRole("button", { name: "Create PR", exact: true }),+ );+ const body = within(canvasElement.ownerDocument.body);+ await expect(await body.findByRole("textbox")).toBeVisible();},};@@ -214,17 +231,19 @@ function SidebarRestorationPreview()}<main className="min-w-0 flex-1 overflow-auto">{isInboxTriagePath(pathname) ? (- <ReportTriageFocusView- {...props}- onExit={() => void navigate({ to: "/inbox" })}- onOpenReport={() =>- void navigate({- to: "/reports/$reportId",- params: { reportId: report.id },- search: { from: "/inbox/triage" },- })- }- />+ <InboxStoryData report={props.report}>+ <ReportTriageFocusView+ {...props}+ onExit={() => void navigate({ to: "/inbox" })}+ onOpenReport={() =>+ void navigate({+ to: "/reports/$reportId",+ params: { reportId: report.id },+ search: { from: "/inbox/triage" },+ })+ }+ />+ </InboxStoryData>) : pathname.startsWith("/reports/") ? (<InboxDetailFrameViewreport={report}@@ -253,4 +272,31 @@ function SidebarRestorationPreview(export const SidebarRestoration: Story = {render: (args) => <SidebarRestorationPreview {...args} />,+ play: async ({ canvas, userEvent }): Promise<void> => {+ await userEvent.click(+ await canvas.findByRole("button", { name: "Start triage" }),+ );+ await waitFor(() =>+ expect(+ canvas.queryByRole("complementary", { name: "Self-driving sidebar" }),+ ).not.toBeInTheDocument(),+ );+ await userEvent.click(+ await canvas.findByRole("button", { name: "Exit triage" }),+ );+ await expect(+ await canvas.findByRole("complementary", {+ name: "Self-driving sidebar",+ }),+ ).toBeVisible();+ await userEvent.click(canvas.getByRole("button", { name: "Start triage" }));+ await userEvent.click(+ await canvas.findByRole("button", { name: "Open report" }),+ );+ await expect(+ await canvas.findByRole("complementary", {+ name: "Self-driving sidebar",+ }),+ ).toBeVisible();+ },};diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.test.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.test.tsxindex 2a6a9df6ceed..83de5649cf87 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.test.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.test.tsx@@ -7,6 +7,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest";const {createPrReport,+ useCreatePrReport,+ updateInboxReportCaches,+ resolveInboxReportDetailCache,discussReport,invalidateQueries,openExternalUrl,@@ -21,6 +24,9 @@ const {fireAction,} = vi.hoisted(() => ({createPrReport: vi.fn(),+ useCreatePrReport: vi.fn(),+ updateInboxReportCaches: vi.fn(),+ resolveInboxReportDetailCache: vi.fn(),discussReport: vi.fn(),invalidateQueries: vi.fn(),openExternalUrl: vi.fn(),@@ -35,6 +41,12 @@ const {fireAction: vi.fn(),}));+vi.mock("@posthog/core/inbox/inboxQuery", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@posthog/core/inbox/inboxQuery")>()),+ updateInboxReportCaches,+ resolveInboxReportDetailCache,+}));+vi.mock("@tanstack/react-query", async (importOriginal) => {const actual = await importOriginal<typeof import("@tanstack/react-query")>();return {@@ -55,7 +67,7 @@ vi.mock();vi.mock("@posthog/ui/features/inbox/hooks/useCreatePrReport", () => ({- useCreatePrReport: () => ({ createPrReport, isCreatingPr: false }),+ useCreatePrReport,}));vi.mock("@posthog/ui/features/inbox/hooks/useDiscussReport", () => ({@@ -167,6 +179,7 @@ const repoArtefacts = {};describe("ReportVerdictBanner", () => {+ let onImplementationCreated: ((task: Task) => void) | undefined;let onDiscussionCreated: ((task: Task) => void) | undefined;beforeEach(() => {@@ -190,6 +203,15 @@ describe("ReportVerdictBanner", () => {fireAction.mockReset();setQueryData.mockReset();onDiscussionCreated = undefined;+ onImplementationCreated = undefined;+ updateInboxReportCaches.mockReset();+ resolveInboxReportDetailCache.mockReset();+ useCreatePrReport.mockImplementation(+ (options: { onTaskCreated?: (task: Task) => void }) => {+ onImplementationCreated = options.onTaskCreated;+ return { createPrReport, isCreatingPr: false };+ },+ );useDiscussReport.mockImplementation((options: { onTaskCreated?: (task: Task) => void }) => {onDiscussionCreated = options.onTaskCreated;@@ -500,4 +522,85 @@ describe("ReportVerdictBanner", () => {"Start with the smallest safe change",);});+ it("hands implementation off without opening chat or navigating", () => {+ const onEngaged = vi.fn();+ render(+ <ReportVerdictBanner+ report={report}+ variant="triage-actions"+ surface="triage"+ onEngaged={onEngaged}+ />,+ );+ const task = {+ id: "implementation-1",+ latest_run: { status: "queued" },+ } as Task;+ act(() => onImplementationCreated?.(task));+ expect(updateInboxReportCaches).toHaveBeenCalledWith(expect.anything(), [+ expect.objectContaining({+ id: report.id,+ status: report.status,+ work_state: "working",+ assignee: { kind: "task", task_id: task.id },+ }),+ ]);+ expect(useReportChatPanelStore.getState().open).toBe(false);+ expect(openTask).not.toHaveBeenCalled();+ expect(onEngaged).not.toHaveBeenCalled();+ });++ it("explains why a failed implementation returned to triage", () => {+ const task = {+ id: "implementation-1",+ latest_run: { status: "failed" },+ } as Task;+ useReportTasks.mockReturnValue({+ data: [{ task, purpose: "implementation" }],+ isLoading: false,+ });+ render(+ <ReportVerdictBanner+ report={{ ...report, assignee: { kind: "task", task_id: task.id } }}+ variant="triage-actions"+ surface="triage"+ />,+ );+ expect(screen.getByRole("status")).toHaveTextContent(+ "PR task failed. Open the report to continue.",+ );+ });+ it("explains an assigned task the lookup can no longer find", () => {+ useReportTasks.mockReturnValue({ data: [], isLoading: false });+ render(+ <ReportVerdictBanner+ report={{+ ...report,+ assignee: { kind: "task", task_id: "implementation-gone" },+ }}+ variant="triage-actions"+ surface="triage"+ />,+ );+ expect(screen.getByRole("status")).toHaveTextContent(+ "Task status unavailable. Open the report to continue.",+ );+ });+ it("does not reopen a report dismissed while its task starts", () => {+ render(+ <ReportVerdictBanner+ report={report}+ variant="triage-actions"+ surface="triage"+ />,+ );+ resolveInboxReportDetailCache.mockReturnValue({+ ...report,+ status: "suppressed",+ });+ act(() => onImplementationCreated?.({ id: "implementation-1" } as Task));+ expect(updateInboxReportCaches).toHaveBeenCalledWith(expect.anything(), [+ expect.objectContaining({ status: "suppressed" }),+ ]);+ });});diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.tsxindex 419a8433156d..84d290c56e6f 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.tsx@@ -7,10 +7,19 @@ import {GitPullRequestIcon,} from "@phosphor-icons/react";import { extractRepoSelectionRepository } from "@posthog/core/inbox/artefacts";+import {+ resolveInboxReportDetailCache,+ updateInboxReportCaches,+} from "@posthog/core/inbox/inboxQuery";import {canCreateImplementationPr,canResolveReport,} from "@posthog/core/inbox/reportActions";+import {+ deriveReportImplementationState,+ needsImplementationDecision,+ REPORT_IMPLEMENTATION_LABELS,+} from "@posthog/core/inbox/reportImplementation";import { parsePrUrl } from "@posthog/core/inbox/reportPresentation";import { deriveReportVerdict } from "@posthog/core/inbox/reportVerdict";import {@@ -145,6 +154,18 @@ export function ReportVerdictBanner({isLoading: reportTasksLoading,isError: reportTasksFailed,} = useReportTasks(report.id, report.status);+ const assignedTask = reportTasks?.find(+ (entry) => entry.task.id === report.assignee?.task_id,+ )?.task;+ const implementationState = deriveReportImplementationState(+ report,+ assignedTask,+ // A settled lookup that still has no assigned task means the task is gone:+ // fetchReportTasks drops a row whose task returns 404. Treat that as a+ // failed lookup, the same way the batch list does, so the banner shows the+ // unavailable status instead of staying in "checking" forever.+ reportTasksFailed || (!!reportTasks && !assignedTask),+ );const continuableTask = findContinuableImplementationTask(reportTasks);const canCreatePr = canCreateImplementationPr(report, {hasLiveImplementationTask: continuableTask !== null,@@ -213,17 +234,31 @@ export function ReportVerdictBanner({[queryClient, rememberStartedTask, report.id, setChatOpen, onEngaged],);+ const handleImplementationStarted = useCallback(+ (task: Task) => {+ queryClient.setQueryData(taskDetailQuery(task.id).queryKey, task);+ rememberStartedTask(report.id, task.id);+ updateInboxReportCaches(queryClient, [+ {+ ...(resolveInboxReportDetailCache(queryClient, report.id) ?? report),+ work_state: "working",+ assignee: { kind: "task", task_id: task.id },+ },+ ]);+ void queryClient.invalidateQueries({+ queryKey: ["inbox", "report-tasks", report.id],+ });+ },+ [queryClient, rememberStartedTask, report],+ );+const { createPrReport, isCreatingPr } = useCreatePrReport({reportId: report.id,reportTitle: report.title ?? null,cloudRepository,surface,triageId,- // The dock binds to the new task the moment it exists — and only then does- // the view advance. A failed create (offline, missing repo/integration/- // model, API error) never reaches here, so the report and its actions stay- // put instead of opening an empty dock or, in triage, navigating away.- onTaskCreated: handleTaskCreated,+ onTaskCreated: handleImplementationStarted,});const { discussReport, isDiscussing } = useDiscussReport({report,@@ -258,8 +293,6 @@ export function ReportVerdictBanner({});setPrFeedback("");setPrOpen(false);- // The view advances from onTaskCreated once the task exists, not here — a- // failed create leaves the report and its actions in place.void createPrReport(trimmed || undefined);}, [createPrReport, fireAction, prFeedback]);@@ -618,6 +651,13 @@ export function ReportVerdictBanner({if (variant === "triage-actions") {return (<>+ {implementationState &&+ needsImplementationDecision(implementationState) && (+ <output className="w-full rounded border border-(--amber-6) bg-(--amber-2) px-3 py-2 text-[13px] text-amber-11">+ {REPORT_IMPLEMENTATION_LABELS[implementationState]}. Open the+ report to continue.+ </output>+ )}{actionsRow}{resolveDialog}{dismissDialog}diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.test.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.test.tsxindex d6df23224c3e..f378e090bb18 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.test.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.test.tsx@@ -1,12 +1,16 @@+import { INBOX_ACTIONABLE_REPORT_STATUS_FILTER } from "@posthog/core/inbox/reportFiltering";+import type { ReportImplementationState } from "@posthog/core/inbox/reportImplementation";import type { SignalReport } from "@posthog/shared/types";import { useInboxSignalsFilterStore } from "@posthog/ui/features/inbox/stores/inboxSignalsFilterStore";-import { render, screen } from "@testing-library/react";+import { render, renderHook, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import type { ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({activeReports: [] as SignalReport[],+ implementationStates: new Map<string, ReportImplementationState>(),+ implementationStatesLoading: false,setupStatusLoading: false,setupConfigured: true,navigateToSettings: vi.fn(),@@ -26,6 +30,8 @@ const mocks = vi.hoisted(() => ({navigate: vi.fn(),fetchNextPage: vi.fn(),pagedStatus: null as string | null,+ pagedCount: 400,+ totalCount: null as number | null,allReportsOptions: [] as {applySourceFilter?: boolean;applySearchFilter?: boolean;@@ -38,6 +44,16 @@ const mocks = vi.hoisted(() => ({}[],}));+vi.mock(+ "@posthog/ui/features/inbox/hooks/useReportImplementationStates",+ () => ({+ useReportImplementationStates: () => ({+ states: mocks.implementationStates,+ isLoading: mocks.implementationStatesLoading,+ }),+ }),+);+vi.mock("@posthog/ui/features/feature-flags/useTriageFocusEnabled", () => ({useTriageFocusEnabled: () => mocks.triageFocusEnabled,}));@@ -81,7 +97,9 @@ vi.mock("@posthog/ui/features/inbox/hooks/useInboxAllReports", () => ({scopedReports: reports,allReports:options.statusFilter === mocks.pagedStatus- ? Array.from({ length: 400 }, () => reports[0]).filter(Boolean)+ ? Array.from({ length: mocks.pagedCount }, () => reports[0]).filter(+ Boolean,+ ): reports,isLoading: false,isPending: false,@@ -91,7 +109,7 @@ vi.mock("@posthog/ui/features/inbox/hooks/useInboxAllReports", () => ({fetchNextPage: mocks.fetchNextPage,refetch: vi.fn(),searchQuery: options.applySearchFilter === false ? "" : mocks.searchQuery,- totalCount: reports.length,+ totalCount: mocks.totalCount ?? reports.length,scope: "entire_project",isSuccess: true,sourceProductFilter: [],@@ -178,7 +196,7 @@ vi.mock("@posthog/ui/features/inbox/components/ReportTriageFocus", () => ({onExit: () => void;}) => {mocks.triageProps = props;- return null;+ return <div data-testid="triage-focus" />;},}));@@ -194,6 +212,7 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({useChannelsLayout: () => false,}));+import { useInboxSectionedReports } from "../hooks/useInboxSectionedReports";import { InboxTriagePane } from "./InboxTriagePane";import { ReportsInboxView } from "./ReportsInboxView";@@ -224,6 +243,8 @@ describe("ReportsInboxView", () => {beforeEach(() => {vi.clearAllMocks();mocks.activeReports = [];+ mocks.implementationStates = new Map();+ mocks.implementationStatesLoading = false;mocks.setupStatusLoading = false;mocks.setupConfigured = true;mocks.searchQuery = "checkout";@@ -232,6 +253,8 @@ describe("ReportsInboxView", () => {mocks.locationState = {};mocks.allReportsOptions = [];mocks.pagedStatus = null;+ mocks.pagedCount = 400;+ mocks.totalCount = null;useInboxSignalsFilterStore.setState({searchQuery: "checkout",sourceProductFilter: [],@@ -397,4 +420,82 @@ describe("ReportsInboxView", () => {"second-report",]);});+ it("does not count unloaded reports as triage decisions", () => {+ mocks.activeReports = [activeReport("working", "Working report")];+ mocks.implementationStates = new Map([["working", "working"]]);+ mocks.totalCount = 600;+ const { result } = renderHook(() =>+ useInboxSectionedReports({ autoPage: false }),+ );+ expect(result.current.triageReportCount).toBe(0);+ expect(result.current.triageReports).toEqual([]);+ expect(result.current.reportCount).toBeGreaterThan(0);+ });++ it("keeps working reports in the list but only decisions in triage", () => {+ mocks.activeReports = [+ activeReport("working", "Working report"),+ activeReport("failed", "Failed report"),+ ];+ mocks.implementationStates = new Map([+ ["working", "working"],+ ["failed", "failed"],+ ]);+ const list = render(<ReportsInboxView />);+ expect(screen.getByText("Working report")).toBeInTheDocument();+ expect(screen.getByText("Failed report")).toBeInTheDocument();+ list.unmount();+ render(<InboxTriagePane />);+ expect(mocks.triageProps?.reports.map((report) => report.id)).toEqual([+ "failed",+ ]);+ });++ it("keeps triage on screen while task state reloads", () => {+ mocks.activeReports = [+ activeReport("first", "First report"),+ activeReport("second", "Second report"),+ ];+ mocks.searchQuery = "";+ mocks.triageFocusEnabled = true;++ const pane = render(<InboxTriagePane />);+ expect(screen.getByTestId("triage-focus")).toBeInTheDocument();++ // Create PR puts a task on the report it hands off, which reloads task+ // state for the whole queue.+ mocks.implementationStatesLoading = true;+ pane.rerender(<InboxTriagePane />);++ expect(screen.getByTestId("triage-focus")).toBeInTheDocument();+ expect(mocks.triageProps?.reports.map((report) => report.id)).toEqual([+ "first",+ "second",+ ]);+ });++ it("waits for task state before triage runs out of reports", () => {+ mocks.activeReports = [activeReport("working", "Working report")];+ mocks.implementationStates = new Map([["working", "working"]]);+ mocks.implementationStatesLoading = true;+ mocks.searchQuery = "";+ mocks.triageFocusEnabled = true;++ render(<InboxTriagePane />);++ expect(screen.queryByTestId("triage-focus")).toBeNull();+ });++ it("waits for the next decision page before triage runs out of reports", () => {+ mocks.activeReports = [activeReport("working", "Working report")];+ mocks.implementationStates = new Map([["working", "working"]]);+ mocks.searchQuery = "";+ mocks.triageFocusEnabled = true;+ mocks.pagedStatus = INBOX_ACTIONABLE_REPORT_STATUS_FILTER;+ mocks.pagedCount = 50;++ render(<InboxTriagePane />);++ expect(mocks.triageProps).toBeNull();+ });});diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.tsxindex 2de5dd867b4a..be85102a43ec 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.tsx@@ -69,7 +69,11 @@ export function ReportsInboxView(): React.JSX.Element {filterControl={<InboxReportFilters />}scopeControl={<InboxScopeSelect />}renderReport={(report) => (- <InboxReportRow key={report.id} report={report} />+ <InboxReportRow+ key={report.id}+ report={report}+ implementationState={inbox.implementationStates.get(report.id)}+ />)}onConfigureAgents={() => navigateToSettings("agents")}onEnterTriage={() => void navigate({ to: INBOX_TRIAGE_ROUTE })}diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxViewPresentation.stories.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxViewPresentation.stories.tsxindex 3638e6cf4f30..7c5cc23cc433 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxViewPresentation.stories.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxViewPresentation.stories.tsx@@ -1,9 +1,16 @@+import {+ deriveReportImplementationState,+ needsImplementationDecision,+} from "@posthog/core/inbox/reportImplementation";import type { SignalReport } from "@posthog/shared/types";import { InboxReportContextMenu } from "@posthog/ui/features/inbox/components/InboxReportContextMenu";import { InboxReportFilters } from "@posthog/ui/features/inbox/components/InboxReportFilters";import { InboxReportRowView } from "@posthog/ui/features/inbox/components/InboxReportRowView";import { InboxScopeSelect } from "@posthog/ui/features/inbox/components/InboxScopeSelect";-import { inboxStoryReport } from "@posthog/ui/features/inbox/components/inboxStoryFixtures";+import {+ inboxStoryImplementations,+ inboxStoryReport,+} from "@posthog/ui/features/inbox/components/inboxStoryFixtures";import { ReportsInboxViewPresentation } from "@posthog/ui/features/inbox/components/ReportsInboxViewPresentation";import type { Meta, StoryObj } from "@storybook/react-vite";@@ -81,17 +88,18 @@ function reportRow(report: SignalReport): React.JSX.Element {const meta: Meta<typeof ReportsInboxViewPresentation> = {title: "Inbox/Reports/List view",component: ReportsInboxViewPresentation,+ tags: ["inbox"],parameters: { layout: "fullscreen" },decorators: [(Story) => (- <div className="h-[760px] min-w-[720px]">+ <div className="h-[760px] min-w-0"><Story /></div>),],args: {reports,- triageReportCount: reviewAndMerge.length + needsPr.length,+ triageReportCount: needsPr.length,isLoading: false,isFetchingNextPage: false,hasNextPage: false,@@ -143,6 +151,7 @@ export const FilteredEmpty: Story = {};export const Loading: Story = {+ parameters: { testOptions: { waitForLoadersToDisappear: false } },args: {reports: [],triageReportCount: 0,@@ -158,3 +167,42 @@ export const LoadError: Story = {isError: true,},};++const implementationReports = inboxStoryImplementations.map(+ (entry) => entry.report,+);+const implementationStates = new Map(+ inboxStoryImplementations.map(({ report, task }) => [+ report.id,+ deriveReportImplementationState(report, task),+ ]),+);++export const ImplementationProgress: Story = {+ args: {+ reports: [reviewAndMerge[0], ...implementationReports],+ triageReportCount: implementationReports.filter((report) =>+ needsImplementationDecision(implementationStates.get(report.id) ?? null),+ ).length,+ renderReport: (report) => (+ <InboxReportRowView+ key={report.id}+ report={report}+ implementationState={implementationStates.get(report.id)}+ onOpen={() => {}}+ onOpenPr={() => {}}+ />+ ),+ },+};++export const Narrow: Story = {+ ...ImplementationProgress,+ decorators: [+ (Story) => (+ <div className="w-full max-w-[520px]">+ <Story />+ </div>+ ),+ ],+};diff --git a/products/desktop/packages/ui/src/features/inbox/components/inboxStoryFixtures.ts b/products/desktop/packages/ui/src/features/inbox/components/inboxStoryFixtures.tsindex 2e4e3f1b1fd0..6578ef8af348 100644--- a/products/desktop/packages/ui/src/features/inbox/components/inboxStoryFixtures.ts+++ b/products/desktop/packages/ui/src/features/inbox/components/inboxStoryFixtures.ts@@ -1,4 +1,9 @@-import type { Signal, SignalReport } from "@posthog/shared/types";+import type {+ Signal,+ SignalReport,+ Task,+ TaskRunStatus,+} from "@posthog/shared/types";export function inboxStoryReport(overrides: Partial<SignalReport> = {},@@ -36,3 +41,68 @@ export function inboxStorySignal(overrides: Partial<Signal> = {}): Signal {...overrides,};}++export function inboxStoryImplementation(+ id: string,+ status: TaskRunStatus,+ overrides: Partial<SignalReport> = {},+): { report: SignalReport; task: Task } {+ const report = inboxStoryReport({+ id,+ assignee: { kind: "task", task_id: `task-${id}` },+ ...overrides,+ });+ const task: Task = {+ id: `task-${id}`,+ task_number: 1,+ slug: `task-${id}`,+ title: report.title ?? "Implement the report",+ description: "Create a PR for the report.",+ origin_product: "signal_report",+ created_at: report.created_at,+ updated_at: report.created_at,+ latest_run: {+ id: `run-${id}`,+ task: `task-${id}`,+ team: 1,+ branch: null,+ status,+ log_url: "",+ error_message: status === "failed" ? "The task could not finish." : null,+ output: null,+ state: {},+ created_at: report.created_at,+ updated_at: report.created_at,+ completed_at: null,+ },+ };+ return { report, task };+}++export const inboxStoryImplementations = [+ inboxStoryImplementation("working", "in_progress", {+ title: "fix(cohorts): coalesce pending calculations",+ }),+ inboxStoryImplementation("failed", "failed", {+ title: "fix(flags): retry a failed evaluation",+ summary:+ "Flag evaluation fails after a connection closes. Retry the request after reconnecting.",+ }),+ inboxStoryImplementation("waiting", "in_progress", {+ title: "feat(insights): choose a default breakdown order",+ summary:+ "The task needs a choice between alphabetical order and ranking by value before it can update the saved insight.",+ status: "pending_input",+ actionability: "requires_human_input",+ }),+ inboxStoryImplementation("cancelled", "cancelled", {+ title: "fix(webhooks): resume delivery after a timeout",+ summary:+ "Webhook delivery stops after a timeout. The implementation task stopped before it could add a retry.",+ }),+ inboxStoryImplementation("no-pr", "completed", {+ title: "fix(replay): show buffer health in the player",+ summary:+ "The player does not show when its buffer is empty. The task finished its investigation but did not create a PR.",+ }),+];diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useCreatePrReport.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useCreatePrReport.tsindex 8bfd7988fdec..fb31f757e232 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useCreatePrReport.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useCreatePrReport.ts@@ -17,7 +17,7 @@ interface UseCreatePrReportOptions {cloudRepository: string | null;surface?: InboxReportActionSurface;triageId?: string;- /** Fires once the implementation task exists (the chat dock binds to it). */+ /** Fires after the implementation task starts successfully. */onTaskCreated?: (task: Task) => void;}@@ -142,7 +142,7 @@ export function useCreatePrReport({buildInput,analyticsExtras,redirectOnSuccess: false,- onTaskCreated,+ onTaskStarted: onTaskCreated,});const createPrReport = useCallback(diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.test.tsx b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.test.tsxnew file mode 100644index 000000000000..af96d36e18dc--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.test.tsx@@ -0,0 +1,189 @@+import type { TaskCreationOutput } from "@posthog/shared";+import type { Task } from "@posthog/shared/types";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, renderHook, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ createTask: vi.fn(),+ resolveModel: vi.fn(),+ openTask: vi.fn(),+ success: vi.fn(),+ error: vi.fn(),+}));+vi.mock("@posthog/di/react", () => ({+ useService: () => ({ createTask: mocks.createTask }),+}));+vi.mock("@posthog/ui/features/auth/store", () => ({+ useAuthStateValue: (selector: (state: { cloudRegion: string }) => unknown) =>+ selector({ cloudRegion: "us" }),+}));+vi.mock("@posthog/ui/features/inbox/hooks/resolveDefaultModel", () => ({+ resolveDefaultModel: mocks.resolveModel,+}));+vi.mock("@posthog/ui/features/inbox/hooks/useInboxReports", () => ({+ reportKeys: { artefacts: (id: string) => ["artefacts", id] },+}));+vi.mock("@posthog/ui/features/integrations/useIntegrations", () => ({+ useUserRepositoryIntegration: () => ({+ getUserIntegrationIdForRepo: () => "integration-1",+ }),+}));+vi.mock("@posthog/ui/features/settings/settingsStore", () => ({+ useSettingsStore: { getState: () => ({}) },+}));+vi.mock("@posthog/ui/features/tasks/useTaskCrudMutations", () => ({+ useCreateTask: () => ({ invalidateTasks: vi.fn() }),+}));+vi.mock("@posthog/ui/hooks/useConnectivity", () => ({+ useConnectivity: () => ({ isOnline: true }),+}));+vi.mock("@posthog/ui/features/notifications/errorDetails", () => ({+ toastError: vi.fn(),+}));+vi.mock("@posthog/ui/primitives/toast", () => ({+ toast: {+ loading: vi.fn(),+ dismiss: vi.fn(),+ error: vi.fn(),+ success: mocks.success,+ },+}));+vi.mock("@posthog/ui/router/useOpenTask", () => ({ openTask: mocks.openTask }));+vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));+vi.mock("@posthog/ui/shell/logger", () => ({+ logger: { scope: () => ({ error: mocks.error }) },+}));++import { useInboxCloudTaskRunner } from "./useInboxCloudTaskRunner";++const task = {+ id: "implementation-1",+ title: "Fix the example report",+} as Task;+const output = { task, workspace: null } as TaskCreationOutput;++function renderRunner() {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const onTaskStarted = vi.fn();+ const hook = renderHook(+ () =>+ useInboxCloudTaskRunner({+ reportId: "report-1",+ cloudRepository: "example/project",+ loggerScope: "test",+ redirectOnSuccess: false,+ onTaskStarted,+ copy: {+ loadingTitle: "Starting PR task",+ errorTitle: "Could not start PR task",+ missingRepository: "Choose a repository",+ missingIntegration: "Connect GitHub",+ signedOut: "Sign in",+ missingModel: "Choose a model",+ },+ buildInput: () => ({ content: "Create a PR", workspaceMode: "cloud" }),+ }),+ {+ wrapper: ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>+ {children}+ </QueryClientProvider>+ ),+ },+ );+ return { ...hook, onTaskStarted, queryClient };+}++describe("useInboxCloudTaskRunner", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.resolveModel.mockResolvedValue("claude-sonnet-4-6");+ });++ it.each([true, false])(+ "waits for startup to finish before handing off (success: %s)",+ async (success) => {+ let settle!: (result: unknown) => void;+ mocks.createTask.mockImplementation((_input, onReady) => {+ onReady(output);+ return new Promise((resolve) => {+ settle = resolve;+ });+ });+ const { result, onTaskStarted } = renderRunner();+ let pending!: Promise<boolean>;+ act(() => {+ pending = result.current.run();+ });+ await waitFor(() => expect(mocks.createTask).toHaveBeenCalledOnce());+ expect(onTaskStarted).not.toHaveBeenCalled();+ expect(mocks.openTask).not.toHaveBeenCalled();+ expect(mocks.success).not.toHaveBeenCalled();+ expect(result.current.isRunning).toBe(true);+ await act(async () => {+ settle(+ success+ ? { success: true, data: output }+ : { success: false, error: "Startup failed" },+ );+ expect(await pending).toBe(success);+ });+ expect(onTaskStarted).toHaveBeenCalledTimes(success ? 1 : 0);+ expect(result.current.isRunning).toBe(false);+ expect(mocks.openTask).not.toHaveBeenCalled();+ if (success) {+ const options = mocks.success.mock.calls[0][1];+ expect(options.action.label).toBe("View task");+ options.action.onClick();+ expect(mocks.openTask).toHaveBeenCalledWith(task);+ }+ },+ );++ it("keeps successful startup when the handoff callback throws", async () => {+ mocks.createTask.mockResolvedValue({ success: true, data: output });+ const { result, onTaskStarted, queryClient } = renderRunner();+ const refresh = vi.spyOn(queryClient, "invalidateQueries");+ const error = new Error("Handoff failed");+ onTaskStarted.mockImplementation(() => {+ throw error;+ });+ await act(async () => {+ expect(await result.current.run()).toBe(true);+ });+ expect(mocks.error).toHaveBeenCalledWith(+ "Task started, but the handoff callback failed",+ error,+ );+ expect(refresh).toHaveBeenCalledWith({+ queryKey: ["inbox", "signal-reports"],+ });+ expect(mocks.success).toHaveBeenCalledOnce();+ expect(result.current.isRunning).toBe(false);+ expect(mocks.createTask).toHaveBeenCalledOnce();+ });++ it("blocks repeated clicks and permits retry after model lookup fails", async () => {+ mocks.resolveModel.mockRejectedValueOnce(new Error("Model lookup failed"));+ mocks.createTask.mockResolvedValue({ success: true, data: output });+ const { result, onTaskStarted } = renderRunner();+ await act(async () => {+ const first = result.current.run();+ const duplicate = result.current.run();+ expect(await duplicate).toBe(false);+ expect(await first).toBe(false);+ });+ expect(result.current.isRunning).toBe(false);+ expect(onTaskStarted).not.toHaveBeenCalled();+ expect(mocks.createTask).not.toHaveBeenCalled();+ await act(async () => {+ expect(await result.current.run()).toBe(true);+ });+ expect(mocks.createTask).toHaveBeenCalledOnce();+ expect(onTaskStarted).toHaveBeenCalledOnce();+ });+});diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.tsindex 578a857f2d79..d247bb4afdbb 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.ts@@ -3,6 +3,7 @@ import {REPORT_MODEL_RESOLVER,type ReportModelResolver,} from "@posthog/core/inbox/identifiers";+import { inboxReportKeys } from "@posthog/core/inbox/inboxQuery";import {isUsageLimitResult,TASK_SERVICE,@@ -37,7 +38,7 @@ import { openTask } from "@posthog/ui/router/useOpenTask";import { track } from "@posthog/ui/shell/analytics";import { logger } from "@posthog/ui/shell/logger";import { useQueryClient } from "@tanstack/react-query";-import { useCallback, useState } from "react";+import { useCallback, useRef, useState } from "react";/** Variant-specific copy used in the toasts/errors emitted by the runner. */interface InboxCloudTaskCopy {@@ -107,6 +108,7 @@ export interface UseInboxCloudTaskRunnerOptions {analyticsExtras?: Record<string, unknown>;/** Called with the created task record, before any navigation happens. */onTaskCreated?: (task: Task) => void;+ onTaskStarted?: (task: Task) => void;/*** When false, the runner does not navigate to the created task. The task is* still added to the sidebar via `invalidateTasks`, and a success toast with a@@ -139,9 +141,11 @@ export function useInboxCloudTaskRunner({buildInput,analyticsExtras,onTaskCreated,+ onTaskStarted,redirectOnSuccess = true,}: UseInboxCloudTaskRunnerOptions): UseInboxCloudTaskRunnerReturn {const [isRunning, setIsRunning] = useState(false);+ const runningRef = useRef(false);const { getUserIntegrationIdForRepo } = useUserRepositoryIntegration();const { invalidateTasks } = useCreateTask();const taskService = useService<TaskService>(TASK_SERVICE);@@ -151,7 +155,7 @@ export function useInboxCloudTaskRunner({const { isOnline } = useConnectivity();const run = useCallback(async () => {- if (isRunning) return false;+ if (runningRef.current) return false;const log = logger.scope(loggerScope);const startedAt = Date.now();const trackActionResult = (@@ -203,71 +207,70 @@ export function useInboxCloudTaskRunner({return false;}+ runningRef.current = true;setIsRunning(true);const toastId = toast.loading(copy.loadingTitle, reportTitle ?? undefined);- const settings = useSettingsStore.getState();- const adapter = settings.lastUsedAdapter ?? "claude";- const apiHost = getCloudUrlFromRegion(cloudRegion);+ try {+ const settings = useSettingsStore.getState();+ const adapter = settings.lastUsedAdapter ?? "claude";+ const apiHost = getCloudUrlFromRegion(cloudRegion);- // Pass the persisted model as a *preference*, not a hard selection: the- // resolver keeps it only if the gateway still offers it, otherwise it falls- // back to the server default. A stale id (e.g. one later de-listed for the- // org) would otherwise be sent here and fail the run with a gateway 403.- const preferredModel = defaultEligibleModel(settings.lastUsedModel);- const resolvedModel = await resolveDefaultModel(- queryClient,- apiHost,- adapter,- modelResolver,- preferredModel,- );- // The resolver returns undefined on a transient failure; fall back to the- // persisted id so a gateway outage degrades gracefully rather than blocking.- const model = resolvedModel ?? preferredModel;+ // Pass the persisted model as a *preference*, not a hard selection: the+ // resolver keeps it only if the gateway still offers it, otherwise it falls+ // back to the server default. A stale id (e.g. one later de-listed for the+ // org) would otherwise be sent here and fail the run with a gateway 403.+ const preferredModel = defaultEligibleModel(settings.lastUsedModel);+ const resolvedModel = await resolveDefaultModel(+ queryClient,+ apiHost,+ adapter,+ modelResolver,+ preferredModel,+ );+ // The resolver returns undefined on a transient failure; fall back to the+ // persisted id so a gateway outage degrades gracefully rather than blocking.+ const model = resolvedModel ?? preferredModel;- if (!model) {- toast.dismiss(toastId);- toast.error(copy.errorTitle, { description: copy.missingModel });- setIsRunning(false);- trackActionResult("failed", "missing_model");- return false;- }+ if (!model) {+ toast.dismiss(toastId);+ toast.error(copy.errorTitle, { description: copy.missingModel });+ setIsRunning(false);+ trackActionResult("failed", "missing_model");+ return false;+ }- // The persisted effort belongs to `lastUsedModel`; if the resolver swapped in- // a fallback default, that tier may be unsupported for the new model and the- // cloud runtime rejects the pair (see agent `bin.ts`). Carry the effort only- // when the model is unchanged AND the tier is actually supported for it —- // an effort-less model (e.g. a Cloudflare `@cf/*` model) carrying a stale- // tier would otherwise hard-fail the run at startup. Otherwise let the- // runtime pick its default.- const reasoningLevel =- model === settings.lastUsedModel &&- settings.lastUsedReasoningEffort &&- isSupportedReasoningEffort(+ // The persisted effort belongs to `lastUsedModel`; if the resolver swapped in+ // a fallback default, that tier may be unsupported for the new model and the+ // cloud runtime rejects the pair (see agent `bin.ts`). Carry the effort only+ // when the model is unchanged AND the tier is actually supported for it —+ // an effort-less model (e.g. a Cloudflare `@cf/*` model) carrying a stale+ // tier would otherwise hard-fail the run at startup. Otherwise let the+ // runtime pick its default.+ const reasoningLevel =+ model === settings.lastUsedModel &&+ settings.lastUsedReasoningEffort &&+ isSupportedReasoningEffort(+ adapter,+ model,+ settings.lastUsedReasoningEffort,+ )+ ? settings.lastUsedReasoningEffort+ : undefined;++ const input = buildInput({+ reportId,+ reportTitle,+ cloudRepository,+ githubUserIntegrationId: githubUserIntegrationId+ ? String(githubUserIntegrationId)+ : null,adapter,model,- settings.lastUsedReasoningEffort,- )- ? settings.lastUsedReasoningEffort- : undefined;-- const input = buildInput({- reportId,- reportTitle,- cloudRepository,- githubUserIntegrationId: githubUserIntegrationId- ? String(githubUserIntegrationId)- : null,- adapter,- model,- reasoningLevel,- });+ reasoningLevel,+ });- try {- let createdTask: Parameters<typeof openTask>[0] | null = null;const result = await taskService.createTask(input, (output) => {- createdTask = output.task;invalidateTasks(output.task);onTaskCreated?.(output.task);if (redirectOnSuccess) {@@ -276,10 +279,23 @@ export function useInboxCloudTaskRunner({});if (result.success) {+ try {+ onTaskStarted?.(result.data.task);+ } catch (error) {+ log.error("Task started, but the handoff callback failed", error);+ void queryClient+ .invalidateQueries({ queryKey: inboxReportKeys.all })+ .catch((refreshError) => {+ log.error(+ "Could not refresh reports after task startup",+ refreshError,+ );+ });+ }trackActionResult("succeeded");toast.dismiss(toastId);if (!redirectOnSuccess) {- const task = createdTask;+ const task = result.data.task;toast.success(copy.successTitle ?? "Task started", {description: reportTitle ?? undefined,action: task@@ -358,10 +374,10 @@ export function useInboxCloudTaskRunner({});return false;} finally {+ runningRef.current = false;setIsRunning(false);}}, [- isRunning,isOnline,loggerScope,cloudRepository,@@ -377,6 +393,7 @@ export function useInboxCloudTaskRunner({copy,analyticsExtras,onTaskCreated,+ onTaskStarted,modelResolver,taskService,redirectOnSuccess,diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReports.test.tsx b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReports.test.tsxindex 9ffad83b3c90..e34f7d475352 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReports.test.tsx+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReports.test.tsx@@ -1,27 +1,45 @@+import { applyRenameToSummaries } from "@posthog/core/tasks/taskRename";import type {+ SignalReport,SignalReportArtefactsResponse,SuggestedReviewer,SuggestedReviewersArtefact,} from "@posthog/shared/domain-types";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { renderHook } from "@testing-library/react";+import { renderHook, waitFor } from "@testing-library/react";import { act, type ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";const mockSetReviewers = vi.hoisted(() => vi.fn());const mockClient = vi.hoisted(() => ({setSignalReportReviewers: mockSetReviewers,+ getTask: vi.fn(),+ getTaskSummaries: vi.fn(),}));vi.mock("@posthog/ui/features/auth/authClient", () => ({useOptionalAuthenticatedClient: () => mockClient,}));+vi.mock("@posthog/di/react", async () => {+ const { ReportImplementationService } = await import(+ "@posthog/core/inbox/reportImplementationService"+ );+ const service = new ReportImplementationService();+ return { useService: () => service };+});+vi.mock("@posthog/ui/primitives/toast", () => ({toast: { error: vi.fn() },}));+import { taskKeys } from "../../tasks/taskKeys";+import { inboxStoryReport } from "../components/inboxStoryFixtures";import { reportKeys, useUpdateSuggestedReviewers } from "./useInboxReports";+import {+ reportImplementationStatesQueryRoot,+ useReportImplementationStates,+} from "./useReportImplementationStates";const REPORT_ID = "report-1";const ARTEFACT_ID = "art-1";@@ -65,7 +83,7 @@ function renderUpdateHook() {return { ...result, queryClient };}-describe("useUpdateSuggestedReviewers", () => {+describe("Inbox report queries", () => {beforeEach(() => {vi.clearAllMocks();});@@ -161,4 +179,198 @@ describe("useUpdateSuggestedReviewers", () => {"hubot",]);});+ it("restores implementation state from the server and returns failed work to triage", async () => {+ const report = inboxStoryReport({+ assignee: { kind: "task", task_id: "implementation-1" },+ work_state: "working",+ });+ mockClient.getTaskSummaries.mockResolvedValue([+ {+ id: "implementation-1",+ latest_run: { status: "in_progress" },+ },+ ]);+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ const { result, unmount } = renderHook(+ () => useReportImplementationStates([report]),+ { wrapper },+ );+ await waitFor(() =>+ expect(result.current.states.get(report.id)).toBe("working"),+ );+ unmount();+ client.clear();+ const reloaded = renderHook(() => useReportImplementationStates([report]), {+ wrapper,+ });+ await waitFor(() =>+ expect(reloaded.result.current.states.get(report.id)).toBe("working"),+ );+ expect(mockClient.getTaskSummaries).toHaveBeenCalledTimes(2);+ expect(mockClient.getTask).not.toHaveBeenCalled();+ mockClient.getTaskSummaries.mockResolvedValue([+ {+ id: "implementation-1",+ latest_run: { status: "failed" },+ },+ ]);+ await act(async () => {+ await client.invalidateQueries({+ queryKey: reportImplementationStatesQueryRoot,+ });+ });+ await waitFor(() =>+ expect(reloaded.result.current.states.get(report.id)).toBe("failed"),+ );+ mockClient.getTaskSummaries.mockRejectedValue(+ new Error("Status unavailable"),+ );+ await act(async () => {+ await client.invalidateQueries({+ queryKey: reportImplementationStatesQueryRoot,+ });+ });+ await waitFor(() =>+ expect(reloaded.result.current.states.get(report.id)).toBe("unknown"),+ );+ reloaded.unmount();+ client.clear();+ });+ it("scopes the implementation-state query so signing out clears it", async () => {+ const report = inboxStoryReport({+ assignee: { kind: "task", task_id: "implementation-2" },+ work_state: "working",+ });+ mockClient.getTaskSummaries.mockResolvedValue([+ {+ id: "implementation-2",+ latest_run: { status: "in_progress" },+ },+ ]);+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ const { result, unmount } = renderHook(+ () => useReportImplementationStates([report]),+ { wrapper },+ );+ await waitFor(() =>+ expect(result.current.states.get(report.id)).toBe("working"),+ );+ unmount();++ const cached = client+ .getQueryCache()+ .findAll({ queryKey: reportImplementationStatesQueryRoot });+ expect(cached).toHaveLength(1);+ expect(cached[0].meta).toEqual({ authScoped: true });++ client.removeQueries({+ predicate: (query) => query.meta?.authScoped === true,+ });+ expect(+ client+ .getQueryCache()+ .findAll({ queryKey: reportImplementationStatesQueryRoot }),+ ).toHaveLength(0);+ });+ it("keeps the state map out of reach of task-summary writers", async () => {+ const report = inboxStoryReport({+ assignee: { kind: "task", task_id: "implementation-3" },+ work_state: "working",+ });+ mockClient.getTaskSummaries.mockResolvedValue([+ {+ id: "implementation-3",+ latest_run: { status: "in_progress" },+ },+ ]);+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ const { result, unmount } = renderHook(+ () => useReportImplementationStates([report]),+ { wrapper },+ );+ await waitFor(() =>+ expect(result.current.states.get(report.id)).toBe("working"),+ );++ // The rename flow renames a task inside every cached TaskSummaryDTO[].+ expect(() =>+ client.setQueriesData<{ id: string; title: string }[]>(+ { queryKey: taskKeys.allSummaries() },+ (old) => applyRenameToSummaries(old, "implementation-3", "Renamed"),+ ),+ ).not.toThrow();+ expect(result.current.states.get(report.id)).toBe("working");+ unmount();+ });+ it("keeps checked task states while another report joins the query", async () => {+ const failed = inboxStoryReport({+ id: "report-failed",+ assignee: { kind: "task", task_id: "implementation-failed" },+ work_state: "working",+ });+ const started = inboxStoryReport({+ id: "report-started",+ assignee: { kind: "task", task_id: "implementation-started" },+ work_state: "working",+ });+ mockClient.getTaskSummaries.mockResolvedValue([+ { id: "implementation-failed", latest_run: { status: "failed" } },+ ]);+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ const { result, rerender, unmount } = renderHook(+ ({ reports }: { reports: SignalReport[] }) =>+ useReportImplementationStates(reports),+ { wrapper, initialProps: { reports: [failed] } },+ );+ await waitFor(() =>+ expect(result.current.states.get(failed.id)).toBe("failed"),+ );++ // Create PR puts a task on the second report, which rekeys the query.+ let release = (): void => {};+ mockClient.getTaskSummaries.mockReturnValue(+ new Promise((resolve) => {+ release = () =>+ resolve([+ { id: "implementation-failed", latest_run: { status: "failed" } },+ {+ id: "implementation-started",+ latest_run: { status: "in_progress" },+ },+ ]);+ }),+ );+ rerender({ reports: [failed, started] });++ expect(result.current.states.get(failed.id)).toBe("failed");+ expect(result.current.states.get(started.id)).toBe("checking");++ await act(async () => release());+ await waitFor(() =>+ expect(result.current.states.get(started.id)).toBe("working"),+ );+ expect(result.current.states.get(failed.id)).toBe("failed");+ unmount();+ client.clear();+ });});diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxSectionedReports.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxSectionedReports.tsindex eb1b55372dd7..c1a4ce576dc1 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxSectionedReports.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxSectionedReports.ts@@ -4,6 +4,10 @@ import {INBOX_ACTIONABLE_REPORT_STATUS_FILTER,sortInboxReports,} from "@posthog/core/inbox/reportFiltering";+import {+ needsImplementationDecision,+ type ReportImplementationState,+} from "@posthog/core/inbox/reportImplementation";import type { InboxScope } from "@posthog/core/inbox/reportMembership";import type {SignalReport,@@ -12,6 +16,7 @@ import type {SourceProduct,} from "@posthog/shared/types";import { useInboxAllReports } from "@posthog/ui/features/inbox/hooks/useInboxAllReports";+import { useReportImplementationStates } from "@posthog/ui/features/inbox/hooks/useReportImplementationStates";import {type InboxReportStateFilter,useInboxSignalsFilterStore,@@ -37,6 +42,10 @@ export interface InboxSectionedReports {/** The subset triage steps through: reports that still need a decision. */triageReports: SignalReport[];triageReportCount: number;+ triageLoading: boolean;+ /** Another page of decisions is in flight, or autopaging will ask for one. */+ triagePagePending: boolean;+ implementationStates: Map<string, ReportImplementationState | null>;reportCount: number;isLoading: boolean;isSuccess: boolean;@@ -53,7 +62,8 @@ export interface InboxSectionedReports {priorityFilter: SignalReportPriority[];}-function useAutoPage(query: InboxQuery, enabled: boolean): void {+/** Returns true while another page is in flight or still to come. */+function useAutoPage(query: InboxQuery, enabled: boolean): boolean {const shouldPage =enabled &&query.hasNextPage &&@@ -65,6 +75,8 @@ function useAutoPage(query: InboxQuery, enabled: boolean): void {useEffect(() => {if (shouldPage) void fetchNextPage();}, [shouldPage, fetchNextPage]);++ return shouldPage || (enabled && query.isFetchingNextPage);}/**@@ -127,13 +139,23 @@ export function useInboxSectionedReports(options?: {});useAutoPage(reviewAndMergeQuery, autoPage && showReviewAndMerge);- useAutoPage(needsDecisionQuery, autoPage && showNeedsDecision);+ const decisionPagePending = useAutoPage(+ needsDecisionQuery,+ autoPage && showNeedsDecision,+ );useAutoPage(terminalQuery, autoPage && showTerminal);const { searchQuery, scope, sourceProductFilter, priorityFilter } =reviewAndMergeQuery;+ const implementations = useReportImplementationStates(+ showNeedsDecision ? needsDecisionQuery.scopedReports : EMPTY_REPORTS,+ );const triageReports = showNeedsDecision- ? needsDecisionQuery.scopedReports+ ? needsDecisionQuery.scopedReports.filter((report) =>+ needsImplementationDecision(+ implementations.states.get(report.id) ?? null,+ ),+ ): EMPTY_REPORTS;const visibleReports = useMemo(() => {@@ -174,8 +196,11 @@ export function useInboxSectionedReports(options?: {return {reports: visibleReports,triageReports,- triageReportCount: showNeedsDecision ? needsDecisionQuery.totalCount : 0,+ triageReportCount: triageReports.length,+ implementationStates: implementations.states,reportCount,+ triageLoading: implementations.isLoading,+ triagePagePending: decisionPagePending,isLoading: selected.some((query) => query.isPending),isSuccess,isError:diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useReportImplementationStates.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useReportImplementationStates.tsnew file mode 100644index 000000000000..e7404330e7e9--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useReportImplementationStates.ts@@ -0,0 +1,80 @@+import {+ type ReportImplementationState,+ reportImplementationTaskId,+} from "@posthog/core/inbox/reportImplementation";+import {+ REPORT_IMPLEMENTATION_SERVICE,+ type ReportImplementationService,+} from "@posthog/core/inbox/reportImplementationService";+import { useService } from "@posthog/di/react";+import type { SignalReport } from "@posthog/shared/types";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";+import { DESKTOP_INBOX_REFETCH_INTERVAL_MS } from "@posthog/ui/features/inbox/hooks/inboxPolling";+import { useQuery } from "@tanstack/react-query";+import { useRef } from "react";++/**+ * This cache holds a report-to-state map, not a `TaskSummaryDTO[]`, so it owns+ * a root of its own. Under the task-summaries prefix the rename and auto-title+ * writers would map over it as an array and throw. Task changes that must+ * refresh these states invalidate this root beside that prefix.+ */+export const reportImplementationStatesQueryRoot = [+ "report-implementation-states",+] as const;++export function useReportImplementationStates(reports: SignalReport[]): {+ states: Map<string, ReportImplementationState | null>;+ isLoading: boolean;+} {+ const client = useOptionalAuthenticatedClient();+ const service = useService<ReportImplementationService>(+ REPORT_IMPLEMENTATION_SERVICE,+ );+ const assignedReports = reports.filter(reportImplementationTaskId);+ const query = useQuery({+ queryKey: [+ ...reportImplementationStatesQueryRoot,+ assignedReports+ .map((report) => [+ report.id,+ report.assignee,+ report.status,+ report.implementation_pr_url,+ report.implementation_pr_merged,+ ])+ .sort((left, right) => String(left[0]).localeCompare(String(right[0]))),+ ],+ queryFn: () => {+ if (!client) throw new Error("Not authenticated");+ return service.loadStates(client, assignedReports);+ },+ enabled: !!client && assignedReports.length > 0,+ // Task state belongs to the signed-in user, so logout and a project switch+ // have to drop it: clearAuthScopedQueries only removes queries carrying+ // this meta. The query stays hand-rolled rather than going through+ // useAuthenticatedQuery because that helper spreads caller options over its+ // own enabled, which would drop the client gate above and fire a request+ // that is certain to fail while signed out.+ meta: AUTH_SCOPED_QUERY_META,+ staleTime: 10_000,+ refetchInterval: DESKTOP_INBOX_REFETCH_INTERVAL_MS,+ refetchIntervalInBackground: false,+ });+ // Every report that gains or finishes a task rewrites the key above, so the+ // next fetch starts empty. Reports already checked keep the state they had+ // rather than going back to "checking", which would move the triage queue+ // under the reader for the length of the fetch.+ const resolved = useRef<Map<string, ReportImplementationState | null>>(+ new Map(),+ );+ if (query.data) resolved.current = query.data;+ return {+ states: query.isError+ ? service.initialStates(assignedReports, true)+ : (query.data ??+ service.pendingStates(assignedReports, resolved.current, !client)),+ isLoading: query.isLoading,+ };+}diff --git a/products/desktop/packages/ui/src/features/task-detail/taskCreationEffectsImpl.ts b/products/desktop/packages/ui/src/features/task-detail/taskCreationEffectsImpl.tsindex 5340024b4458..8304ca4390f5 100644--- a/products/desktop/packages/ui/src/features/task-detail/taskCreationEffectsImpl.ts+++ b/products/desktop/packages/ui/src/features/task-detail/taskCreationEffectsImpl.ts@@ -10,6 +10,7 @@ import {IMPERATIVE_QUERY_CLIENT,type ImperativeQueryClient,} from "../../shell/queryClient";+import { reportImplementationStatesQueryRoot } from "../inbox/hooks/useReportImplementationStates";import { useDraftStore } from "../message-editor/draftStore";import { useSettingsStore } from "../settings/settingsStore";import { taskKeys } from "../tasks/taskKeys";@@ -42,6 +43,9 @@ export const taskCreationEffects: TaskCreationEffects = {),);void client.invalidateQueries({ queryKey: taskKeys.allSummaries() });+ void client.invalidateQueries({+ queryKey: reportImplementationStatesQueryRoot,+ });},onCreateSuccess(output: TaskCreationOutput, input?: TaskCreationInput): void {diff --git a/products/desktop/packages/ui/src/features/tasks/useTaskMutations.ts b/products/desktop/packages/ui/src/features/tasks/useTaskMutations.tsindex b3c61d0c4146..58a56d818bba 100644--- a/products/desktop/packages/ui/src/features/tasks/useTaskMutations.ts+++ b/products/desktop/packages/ui/src/features/tasks/useTaskMutations.ts@@ -24,6 +24,7 @@ import {} from "@posthog/ui/features/canvas/hooks/useRecentSpaceTasks";import { TASK_CHANNELS_QUERY_KEY } from "@posthog/ui/features/canvas/hooks/useTaskChannels";import { taskFeedResultsQueryRoot } from "@posthog/ui/features/canvas/hooks/useTaskFeedResults";+import { reportImplementationStatesQueryRoot } from "@posthog/ui/features/inbox/hooks/useReportImplementationStates";import { taskKeys } from "@posthog/ui/features/tasks/taskKeys";import { useAuthenticatedMutation } from "@posthog/ui/hooks/useAuthenticatedMutation";import { useQueryClient } from "@tanstack/react-query";@@ -54,6 +55,9 @@ function useUpdateTask() {queryClient.invalidateQueries({ queryKey: taskKeys.lists() });queryClient.invalidateQueries({ queryKey: taskKeys.detail(taskId) });queryClient.invalidateQueries({ queryKey: taskKeys.allSummaries() });+ queryClient.invalidateQueries({+ queryKey: reportImplementationStatesQueryRoot,+ });queryClient.invalidateQueries({ queryKey: spaceTreeTasksQueryRoot });queryClient.invalidateQueries({ queryKey: channelFeedQueryRoot });queryClient.invalidateQueries({ queryKey: taskFeedResultsQueryRoot });@@ -79,6 +83,9 @@ export function useHandoffTask() {queryClient.invalidateQueries({ queryKey: taskKeys.lists() });queryClient.invalidateQueries({ queryKey: taskKeys.detail(taskId) });queryClient.invalidateQueries({ queryKey: taskKeys.allSummaries() });+ queryClient.invalidateQueries({+ queryKey: reportImplementationStatesQueryRoot,+ });queryClient.invalidateQueries({ queryKey: channelFeedQueryRoot });// A recipient's private channel may be created by the handoff, and the// task's channel can change (private space moves to the recipient's).