: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
feat(desktop): gate report canvas navigation (#80848)
Dylan Martin744fabc22c48
diff --git a/.env.example b/.env.exampleindex 48c2187c3144..141c9c7bfedc 100644--- a/.env.example+++ b/.env.example@@ -65,3 +65,4 @@ HEATMAP_BROWSERLESS_TOKEN=# dev keeps it off and $ai_generation events go through the standard capture lane instead.# Production leaves this unset (defaults to true).LLM_GATEWAY_POSTHOG_AI_LANE_CAPTURE=false+CANVAS_ARTIFACT_SIGNING_KEYS=canvas-artifact-development-key-32-bytesdiff --git a/products/desktop/docs/DEEP-LINKS.md b/products/desktop/docs/DEEP-LINKS.mdindex 81ea31c27338..ac3fb2886267 100644--- a/products/desktop/docs/DEEP-LINKS.md+++ b/products/desktop/docs/DEEP-LINKS.md@@ -98,11 +98,11 @@ An **https** bridge also exists for links sent outside the app (e.g. comment Sla### `posthog-code://inbox/<reportId>`-Open a specific inbox report.+Open a report in Inbox. When `posthog-desktop-report-canvases` is enabled and the report has a generated canvas, open that canvas instead.| Segment | Required | Description ||---|---|---|-| `<reportId>` | Yes | Inbox report ID |+| `<reportId>` | Yes | Report ID |```posthog-code://inbox/report_abc123diff --git a/products/desktop/packages/core/src/canvas/taskActivity.test.ts b/products/desktop/packages/core/src/canvas/taskActivity.test.tsindex ebd8f1aa8d4d..8b7e3cc0bc06 100644--- a/products/desktop/packages/core/src/canvas/taskActivity.test.ts+++ b/products/desktop/packages/core/src/canvas/taskActivity.test.ts@@ -21,6 +21,8 @@ function activity(overrides: Partial<TaskActivity> = {}): TaskActivity {snippet: "ping @[Me]([email protected])",latest_author: ann,latest_message_id: "m1",+ target_scope: null,+ target_id: null,is_unread: true,...overrides,};@@ -42,6 +44,8 @@ describe("toTaskActivityItems", () => {messageId: "m1",commentId: null,commentTarget: null,+ targetScope: null,+ targetId: null,isUnread: true,},]);@@ -64,6 +68,15 @@ describe("toTaskActivityItems", () => {});});+ it("maps a report canvas target for direct navigation", () => {+ const [item] = toTaskActivityItems([+ activity({ target_scope: "desktop_canvas", target_id: "canvas-1" }),+ ]);++ expect(item.targetScope).toBe("desktop_canvas");+ expect(item.targetId).toBe("canvas-1");+ });+it("labels untitled tasks and tolerates missing optional values", () => {const [item] = toTaskActivityItems([activity({diff --git a/products/desktop/packages/core/src/canvas/taskActivity.ts b/products/desktop/packages/core/src/canvas/taskActivity.tsindex 420c41e54724..6f4c7f217ff8 100644--- a/products/desktop/packages/core/src/canvas/taskActivity.ts+++ b/products/desktop/packages/core/src/canvas/taskActivity.ts@@ -29,6 +29,8 @@ export interface TaskActivityItem {messageId: string | null;commentId?: string | null;commentTarget?: CommentTarget | null;+ targetScope: "desktop_canvas" | null;+ targetId: string | null;isUnread: boolean;}@@ -55,6 +57,8 @@ export function toTaskActivityItems(itemId: row.latest_comment_item_id,}: null,+ targetScope: row.target_scope ?? null,+ targetId: row.target_id ?? null,isUnread: row.is_unread,}));}diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts b/products/desktop/packages/core/src/sessions/sessionViewState.test.tsindex a6a685fddb6a..c40b0d91d858 100644--- a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionViewState.test.ts@@ -46,6 +46,21 @@ function makeSession(}describe("deriveSessionViewState", () => {+ it("uses a live cloud session when task run metadata is unavailable", () => {+ const task = makeTask("in_progress");+ task.latest_run = undefined;++ const state = deriveSessionViewState(+ makeSession("in_progress"),+ task,+ null,+ false,+ );++ expect(state.isCloud).toBe(true);+ expect(state.isCloudRunNotTerminal).toBe(true);+ });+it("uses terminal task status over stale same-run session status", () => {const state = deriveSessionViewState(makeSession("in_progress"),diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.ts b/products/desktop/packages/core/src/sessions/sessionViewState.tsindex 26c5b5e4c2eb..3df51d341d79 100644--- a/products/desktop/packages/core/src/sessions/sessionViewState.ts+++ b/products/desktop/packages/core/src/sessions/sessionViewState.ts@@ -7,6 +7,7 @@ import {import { resolveEffectiveCloudStatus } from "../task-detail/cloudRunState";export interface SessionViewState {+ isCloud: boolean;isCloudRunNotTerminal: boolean;isCloudRunTerminal: boolean;cloudStatus: TaskRunStatus | null;@@ -28,16 +29,17 @@ export function deriveSessionViewState(workspace: Workspace | null,isCloud: boolean,): SessionViewState {+ const effectiveIsCloud = isCloud || session?.isCloud === true;const cloudStatus = resolveEffectiveCloudStatus(task, session);- const isCloudRunTerminal = isCloud && isTerminalStatus(cloudStatus);- const isCloudRunNotTerminal = isCloud && !isCloudRunTerminal;+ const isCloudRunTerminal = effectiveIsCloud && isTerminalStatus(cloudStatus);+ const isCloudRunNotTerminal = effectiveIsCloud && !isCloudRunTerminal;const hasError = session?.status === "error" && !session?.idleKilled;const handoffInProgress = session?.handoffInProgress ?? false;let isRunning = false;if (!handoffInProgress) {- if (isCloud) {+ if (effectiveIsCloud) {isRunning = !hasError;} else {isRunning = session?.status === "connected";@@ -52,8 +54,10 @@ export function deriveSessionViewState(!task.latest_run?.id && !!task.description;const isResumingExistingSession = !!task.latest_run?.id;const isHydratingEmptyTranscript =- isCloud && events.length === 0 && (session?.isHydratingTranscript ?? false);- const isInitializing = isCloud+ effectiveIsCloud &&+ events.length === 0 &&+ (session?.isHydratingTranscript ?? false);+ const isInitializing = effectiveIsCloud? isHydratingEmptyTranscript ||(!hasError &&(!session || (events.length === 0 && isCloudRunNotTerminal)))@@ -65,11 +69,12 @@ export function deriveSessionViewState(isNewSessionWithInitialPrompt ||isResumingExistingSession));- const cloudBranch = isCloud+ const cloudBranch = effectiveIsCloud? (workspace?.baseBranch ?? task.latest_run?.branch ?? null): null;return {+ isCloud: effectiveIsCloud,isCloudRunNotTerminal,isCloudRunTerminal,cloudStatus,@@ -83,7 +88,9 @@ export function deriveSessionViewState(errorTitle: session?.errorTitle,errorMessage:session?.errorMessage ??- (isCloud ? (session?.cloudErrorMessage ?? undefined) : undefined),+ (effectiveIsCloud+ ? (session?.cloudErrorMessage ?? undefined)+ : undefined),errorRetryable: session?.errorRetryable,};}diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex 737ebacfa62a..52aa8327bbbe 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -247,6 +247,8 @@ export interface TaskActivity {latest_comment_id?: string | null;latest_comment_scope?: string | null;latest_comment_item_id?: string | null;+ target_scope?: "desktop_canvas" | null;+ target_id?: string | null;is_unread: boolean;}@@ -629,6 +631,16 @@ export interface SignalReport {implementation_pr_url?: string | null;/** Charts the report shows, placed by `[label](chart:<chart_id>)` links in the summary. */charts?: SignalReportChart[];+ /** The persistent canvas session generated for this report, when available. */+ canvas_session?: {+ canvas_id: string;+ discussion_task_id: string;+ generation_task_id?: string | null;+ generation_status: "pending" | "generating" | "ready" | "failed";+ collaboration_mode: "managed" | "collaborative";+ failure_reason: string;+ updated_at: string;+ } | null;/** The report's PR refund, when one exists (one refund per report, ever). */refund?: SignalReportRefund | null;/** Marks reports that were never billable ("Free"), so there is nothing to refund. */diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.tsindex 55c0ed5f9c9c..e3a8a866c8f1 100644--- a/products/desktop/packages/shared/src/flags.ts+++ b/products/desktop/packages/shared/src/flags.ts@@ -47,3 +47,5 @@ export const TASK_COST_FLAG = "posthog-code-task-cost";export const ANNOUNCEMENTS_FLAG = "posthog-desktop-announcements";/** Gates the PR-refund action in the inbox (matches the web SIGNALS_PR_REFUNDS flag). */export const SIGNALS_PR_REFUNDS_FLAG = "signals-pr-refunds";+/** Gates replacing Inbox report navigation with generated report canvases. */+export const REPORT_CANVAS_INBOX_FLAG = "posthog-desktop-report-canvases";diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.test.tsxindex 2194ec975520..af15152de2cf 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.test.tsx@@ -41,10 +41,11 @@ const conversationItems = [function renderTimeline(canOpenInPlace?: boolean,items: ConversationItem[] = conversationItems,+ timelineTask: Task = task,) {return render(<ActivityTimeline- task={task}+ task={timelineTask}timeline={[]}messages={[]}// biome-ignore lint/suspicious/noExplicitAny: narrow fixture for the rows under test@@ -59,6 +60,18 @@ beforeEach(() => {});describe("ActivityTimeline", () => {+ it("attributes an internal Signals task to its report", () => {+ renderTimeline(false, [], {+ ...task,+ created_by: undefined,+ origin_product: "signal_report",+ });++ expect(+ screen.getByText("PostHog started this task from a Signals report"),+ ).toBeInTheDocument();+ });+it("names each message row by its own content, not a shared template", () => {renderTimeline(true);diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsxindex e38705ea8b1a..162b106c3223 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityTimeline.tsx@@ -336,7 +336,9 @@ export function ActivityTimeline({gutter={<PersonBead user={task.created_by} badge={CREATED_BADGE} />}timestamp={task.created_at}>- {`${task.created_by ? userDisplayName(task.created_by) : "Someone"} created this task`}+ {!task.created_by && task.origin_product === "signal_report"+ ? "PostHog started this task from a Signals report"+ : `${task.created_by ? userDisplayName(task.created_by) : "Someone"} created this task`}</TimelineRow>);case "user_message":diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityView.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityView.test.tsxindex 7ac883b19f92..504265d34c95 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityView.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityView.test.tsx@@ -16,7 +16,8 @@ vi.mock("@posthog/ui/router/navigationBridge", () => ({vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";-import { ActivityRow, activityHeadline } from "./ActivityView";+import { ActivityRow } from "./ActivityView";+import { activityHeadline } from "./activityHeadline";function item(overrides: Partial<TaskActivityItem>): TaskActivityItem {return {@@ -30,6 +31,8 @@ function item(overrides: Partial<TaskActivityItem>): TaskActivityItem {snippet: "Hello!",author: null,messageId: "message-1",+ targetScope: null,+ targetId: null,isUnread: true,...overrides,};@@ -156,4 +159,30 @@ describe("activityHeadline", () => {intent: "navigate",});});++ it("opens report activity at its generated canvas", () => {+ const activity = item({+ activityKind: "completed",+ channelId: "channel-1",+ targetScope: "desktop_canvas",+ targetId: "canvas-1",+ });++ render(+ <ActivityRow+ item={activity}+ channelId="channel-1"+ onOpen={vi.fn()}+ onMarkRead={vi.fn()}+ blockedTaskIds={NO_BLOCKED_TASKS}+ />,+ );+ fireEvent.click(screen.getByText("A report canvas is ready"));++ expect(navigation.toChannelDashboard).toHaveBeenCalledWith(+ "channel-1",+ "canvas-1",+ );+ expect(navigation.toChannelTask).not.toHaveBeenCalled();+ });});diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityView.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityView.tsxindex 756e7183ee84..96e883d884aa 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityView.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityView.tsx@@ -5,7 +5,6 @@ import {LinkIcon,RobotIcon,} from "@phosphor-icons/react";-import { channelDisplayReference } from "@posthog/core/canvas/channelName";import type { TaskActivityItem } from "@posthog/core/canvas/taskActivity";import {Avatar,@@ -35,7 +34,6 @@ import { useActivityFilterStore } from "@posthog/ui/features/canvas/stores/activimport { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";import { useThreadPanelStore } from "@posthog/ui/features/canvas/stores/threadPanelStore";import { copyChannelLink } from "@posthog/ui/features/canvas/utils/copyChannelLink";-import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";import { DOT_TONE_VAR } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";import {@@ -54,108 +52,13 @@ import {} from "@posthog/ui/router/navigationBridge";import { track } from "@posthog/ui/shell/analytics";import { Text } from "@radix-ui/themes";-import type { ReactNode } from "react";import { useCallback, useEffect, useMemo } from "react";import {activityReadPayload,getUnreadActivityItems,markLoadedReadLabel,} from "./activityFeed";--function ChannelSuffix({ channelName }: { channelName: string | null }) {- if (!channelName) return null;- return (- <>- {" in "}- <span className="font-medium text-xs">- {channelDisplayReference(channelName)}- </span>- </>- );-}--function ownedItemName(item: TaskActivityItem): string {- switch (item.commentTarget?.scope) {- case "desktop_canvas":- return "canvas";- case "task_artifact":- return "artifact";- default:- return "task";- }-}--/** The lead line describing what happened, chosen by the row's activity kind. */-export function activityHeadline(- item: TaskActivityItem,- currentUserEmail?: string | null,-): ReactNode {- switch (item.activityKind) {- case "awaiting_input":- return (- <>- The agent is waiting for your reply- <ChannelSuffix channelName={item.channelName} />- </>- );- case "completed":- return (- <>- The agent completed this task- <ChannelSuffix channelName={item.channelName} />- </>- );- case "message":- if (!item.author) {- return (- <>- The agent replied- <ChannelSuffix channelName={item.channelName} />- </>- );- }- return (- <>- {item.author.email === currentUserEmail- ? "You replied"- : `${userDisplayName(item.author)} replied`}- <ChannelSuffix channelName={item.channelName} />- </>- );- case "mention":- return (- <>- <Text as="span" size="1" weight="medium">- {userDisplayName(item.author)}- </Text>{" "}- mentioned you- <ChannelSuffix channelName={item.channelName} />- </>- );- case "thread_reply":- return (- <>- <Text as="span" size="1" weight="medium">- {userDisplayName(item.author)}- </Text>{" "}- replied to a thread you participated in- <ChannelSuffix channelName={item.channelName} />- </>- );- case "owned_item_comment":- return (- <>- <Text as="span" size="1" weight="medium">- {userDisplayName(item.author)}- </Text>{" "}- commented on your {ownedItemName(item)}- <ChannelSuffix channelName={item.channelName} />- </>- );- default:- return "You created this task";- }-}+import { activityHeadline } from "./activityHeadline";export function ActivityRow({item,@@ -212,6 +115,10 @@ export function ActivityRow({.requestCommentFocus(item.taskId, item.commentTarget, item.commentId);}onNavigate?.();+ if (channelId && item.targetScope === "desktop_canvas" && item.targetId) {+ navigateToChannelDashboard(channelId, item.targetId);+ return;+ }if (channelId && item.commentTarget?.scope === "desktop_canvas") {useCanvasChatPanelStore.getState().openComments();navigateToChannelDashboard(channelId, item.commentTarget.itemId);diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsxindex d8bb19d4dd0b..af7e218e22f7 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx@@ -192,6 +192,7 @@ export function ChannelItemRow({const rowIcon = (<TaskStatusDot dot={deleting ? DELETING_DOT : taskDot(status ?? {})} />);+// A canvas gets the same menu with the items it actually has: pin, and delete// instead of archive. Filing and command-centre cells are task-shaped, and the// menu drops them rather than showing them dead.diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.test.tsxindex 95ced96dde07..865f679bd209 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelNav.test.tsx@@ -40,6 +40,12 @@ describe("ChannelNav", () => {mocks.view = { type: "task-input" };});+ it("keeps Inbox available in the channels navigation", () => {+ render(<ChannelNav />);++ expect(screen.getByLabelText("Inbox")).toBeEnabled();+ });+it("opens recent activity from the bell after the hover delay", async () => {const user = userEvent.setup();render(<ChannelNav />);diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.test.tsxindex a0cb7440f3ca..e2f7787d66ef 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.test.tsx@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({starred: boolean;}[],channelsLoading: false,+ createChannel: vi.fn(),archivedTaskIds: new Set<string>(),navigateToArchived: vi.fn(),track: vi.fn(),@@ -35,6 +36,9 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({channels: mocks.channels,isLoading: mocks.channelsLoading,}),+ useChannelMutations: () => ({+ createChannel: mocks.createChannel,+ }),}));vi.mock("@posthog/ui/features/canvas/hooks/useMarkChannelSeen", () => ({useMarkChannelSeen: (channelId: string | undefined) =>@@ -85,7 +89,10 @@ vi.mock("@tanstack/react-router", () => ({useParams: () => ({ channelId: mocks.routeChannelId }),}));-import { PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";+import {+ PROJECT_BLUEBIRD_FLAG,+ REPORT_CANVAS_INBOX_FLAG,+} from "@posthog/shared";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import {showChannelList,@@ -123,6 +130,7 @@ describe("ChannelsSidebar", () => {mocks.channelsLayout = false;mocks.channels = [];mocks.channelsLoading = false;+ mocks.createChannel.mockResolvedValue({ id: "general-id" });mocks.archivedTaskIds = new Set();mocks.track.mockClear();mocks.routeChannelId = undefined;@@ -137,6 +145,14 @@ describe("ChannelsSidebar", () => {});});+ it("does not provision #general outside the report canvas rollout", () => {+ mocks.featureFlags.set(REPORT_CANVAS_INBOX_FLAG, false);++ renderSidebar();++ expect(mocks.createChannel).not.toHaveBeenCalled();+ });+// The sidebar is a two-pane slider: the channel list, and the channel you're// in. Both stay mounted, so "which one is showing" is the offscreen pane// being inert rather than unmounted.diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsxindex bde9ebf63941..662780a1a6f2 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx@@ -1,6 +1,9 @@import { ArchiveIcon } from "@phosphor-icons/react";import { cn, Separator } from "@posthog/quill";-import { PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";+import {+ PROJECT_BLUEBIRD_FLAG,+ REPORT_CANVAS_INBOX_FLAG,+} from "@posthog/shared";import { useArchivedTaskIds } from "@posthog/ui/features/archive/useArchivedTaskIds";import { ChannelItemPreviewCardProvider } from "@posthog/ui/features/canvas/components/ChannelItemHoverCard";import { ChannelNav } from "@posthog/ui/features/canvas/components/ChannelNav";@@ -12,6 +15,7 @@ import { useChannelPaneSwipe } from "@posthog/ui/features/canvas/hooks/useChanneimport { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import { useCurrentChannel } from "@posthog/ui/features/canvas/hooks/useCurrentChannel";import { useMarkChannelSeen } from "@posthog/ui/features/canvas/hooks/useMarkChannelSeen";+import { useReportSpace } from "@posthog/ui/features/canvas/hooks/useReportSpace";import { useTrackChannelsSpaceViewed } from "@posthog/ui/features/canvas/hooks/useTrackChannelsSpaceViewed";import {consumeKeepListForNextRoute,@@ -108,6 +112,11 @@ function ChannelPanes({);}export function ChannelsSidebar() {+ const reportCanvasesEnabled = useFeatureFlag(+ REPORT_CANVAS_INBOX_FLAG,+ import.meta.env.DEV,+ );+ useReportSpace(reportCanvasesEnabled);const width = useChannelsSidebarStore((state) => state.width);const setWidth = useChannelsSidebarStore((state) => state.setWidth);const isResizing = useChannelsSidebarStore((state) => state.isResizing);diff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelsIndex.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelsIndex.tsxindex 059fdf772ca3..9e4a3e81f80c 100644--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelsIndex.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelsIndex.tsx@@ -1,5 +1,6 @@import { PlusIcon } from "@phosphor-icons/react";import { Button } from "@posthog/quill";+import { REPORT_CANVAS_INBOX_FLAG } from "@posthog/shared";import { BlankTabView } from "@posthog/ui/features/browser-tabs/BlankTabView";import {useActiveTabIsBlank,@@ -8,6 +9,8 @@ import {import { CreateChannelModal } from "@posthog/ui/features/canvas/components/CreateChannelModal";import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";+import { useReportSpace } from "@posthog/ui/features/canvas/hooks/useReportSpace";+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { Flex, Text } from "@radix-ui/themes";import { Navigate, useRouterState } from "@tanstack/react-router";import { useState } from "react";@@ -17,6 +20,13 @@ import { useState } from "react";export function WebsiteChannelsIndex() {const spacesLayout = useChannelsLayout();const { channels, isLoading } = useChannels();+ const reportCanvasesEnabled = useFeatureFlag(+ REPORT_CANVAS_INBOX_FLAG,+ import.meta.env.DEV,+ );+ const { reportSpaceId, isLoading: isLoadingReportSpace } = useReportSpace(+ reportCanvasesEnabled,+ );const [modalOpen, setModalOpen] = useState(false);// A blank "+" tab parks at /website; RootLayout renders the placeholder for// it. Never redirect to the first channel while it's active.@@ -35,13 +45,23 @@ export function WebsiteChannelsIndex() {select: (s) => s.location.pathname === "/website",});- if (isLoading) return null;+ if (isLoading || isLoadingReportSpace) return null;if (!onIndexPath || activeTabIsBlank) return null;- if (channels.length > 0) {+ if (reportSpaceId) {// Empty tab strip → the new-tab screen, not a redirect that re-opens a tab.if (hasNoTabs) return <BlankTabView />;+ return (+ <Navigate+ to="/website/$channelId"+ params={{ channelId: reportSpaceId }}+ replace+ />+ );+ }++ if (channels.length > 0) {return (<Navigateto="/website/$channelId"diff --git a/products/desktop/packages/ui/src/features/canvas/components/activityHeadline.tsx b/products/desktop/packages/ui/src/features/canvas/components/activityHeadline.tsxnew file mode 100644index 000000000000..004127bb638c--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/components/activityHeadline.tsx@@ -0,0 +1,109 @@+import type { TaskActivityItem } from "@posthog/core/canvas/taskActivity";+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";+import type { ReactNode } from "react";++function ChannelSuffix({+ channelName,+}: {+ channelName: string | null;+}): ReactNode {+ if (!channelName) return null;+ const label =+ channelName === "personal" ? "your personal space" : `#${channelName}`;+ return (+ <>+ {" in "}+ <span className="font-medium text-xs">{label}</span>+ </>+ );+}++function ownedItemName(item: TaskActivityItem): string {+ switch (item.commentTarget?.scope) {+ case "desktop_canvas":+ return "canvas";+ case "task_artifact":+ return "artifact";+ default:+ return "task";+ }+}++export function activityHeadline(+ item: TaskActivityItem,+ currentUserEmail?: string | null,+): ReactNode {+ if (item.targetScope === "desktop_canvas") {+ return (+ <>+ A report canvas is ready+ <ChannelSuffix channelName={item.channelName} />+ </>+ );+ }+ switch (item.activityKind) {+ case "awaiting_input":+ return (+ <>+ The agent is waiting for your reply+ <ChannelSuffix channelName={item.channelName} />+ </>+ );+ case "completed":+ return (+ <>+ The agent completed this task+ <ChannelSuffix channelName={item.channelName} />+ </>+ );+ case "message":+ if (!item.author) {+ return (+ <>+ The agent replied+ <ChannelSuffix channelName={item.channelName} />+ </>+ );+ }+ return (+ <>+ {item.author.email === currentUserEmail+ ? "You replied"+ : `${userDisplayName(item.author)} replied`}+ <ChannelSuffix channelName={item.channelName} />+ </>+ );+ case "mention":+ return (+ <>+ <span className="font-medium text-xs">+ {userDisplayName(item.author)}+ </span>{" "}+ mentioned you+ <ChannelSuffix channelName={item.channelName} />+ </>+ );+ case "thread_reply":+ return (+ <>+ <span className="font-medium text-xs">+ {userDisplayName(item.author)}+ </span>{" "}+ replied to a thread you participated in+ <ChannelSuffix channelName={item.channelName} />+ </>+ );+ case "owned_item_comment":+ return (+ <>+ <span className="font-medium text-xs">+ {userDisplayName(item.author)}+ </span>{" "}+ commented on your {ownedItemName(item)}+ <ChannelSuffix channelName={item.channelName} />+ </>+ );+ default:+ return "You created this task";+ }+}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasGenerationStatus.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasGenerationStatus.test.tsindex 0c4791cc28dc..31a1cc736102 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasGenerationStatus.test.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasGenerationStatus.test.ts@@ -9,16 +9,32 @@ import {} from "./canvasGenerationStatus";type Run = Pick<TaskRun, "environment" | "status">;-type Session = Pick<AgentSession, "status" | "cloudStatus" | "isPromptPending">;+type Session = Pick<+ AgentSession,+ | "status"+ | "isCloud"+ | "cloudStatus"+ | "isPromptPending"+ | "taskRunId"+ | "agentIdleForRunId"+>;type GenSession = Session;const genSession = (status: AgentSession["status"],- opts?: { cloudStatus?: TaskRunStatus; isPromptPending?: boolean },+ opts?: {+ cloudStatus?: TaskRunStatus;+ isPromptPending?: boolean;+ agentIdle?: boolean;+ isCloud?: boolean;+ },): GenSession => ({status,cloudStatus: opts?.cloudStatus,isPromptPending: opts?.isPromptPending ?? false,+ isCloud: opts?.isCloud,+ taskRunId: "r1",+ agentIdleForRunId: opts?.agentIdle ? "r1" : undefined,});const run = (environment: "local" | "cloud", status: TaskRunStatus): Run => ({@@ -28,7 +44,14 @@ const run = (environment: "local" | "cloud", status: TaskRunStatus): Run => ({const session = (status: AgentSession["status"],cloudStatus?: TaskRunStatus,-): Session => ({ status, cloudStatus, isPromptPending: false });+): Session => ({+ status,+ cloudStatus,+ isPromptPending: false,+ isCloud: undefined,+ taskRunId: "r1",+ agentIdleForRunId: undefined,+});describe("isCanvasGenerationRunning", () => {it("is not running when there is no generation task", () => {@@ -73,7 +96,7 @@ describe("isCanvasGenerationRunning", () => {["turn settled on the lingering sandbox",run("cloud", "in_progress"),- genSession("connected", { isPromptPending: false }),+ genSession("connected", { agentIdle: true }),false,],[@@ -173,6 +196,17 @@ describe("isCanvasGenerating", () => {).toBe(true);});+ it("uses a streaming cloud session before latest run metadata arrives", () => {+ expect(+ isCanvasGenerating({+ genTaskId: "t1",+ genTaskLoading: false,+ latestRun: undefined,+ session: genSession("connected", { isCloud: true }),+ }),+ ).toBe(true);+ });+it.each<[string, Run, GenSession | undefined, boolean]>([["cloud in_progress", run("cloud", "in_progress"), undefined, true],[@@ -191,10 +225,16 @@ describe("isCanvasGenerating", () => {genSession("connected", { isPromptPending: true }),true,],+ [+ "cloud automatic turn attached after its prompt",+ run("cloud", "in_progress"),+ genSession("connected"),+ true,+ ],["cloud turn settled while the sandbox lingers",run("cloud", "in_progress"),- genSession("connected", { isPromptPending: false }),+ genSession("connected", { agentIdle: true }),false,],[diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasGenerationStatus.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasGenerationStatus.tsindex 904cdfd73bd3..9ebb659f209c 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasGenerationStatus.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasGenerationStatus.ts@@ -14,7 +14,15 @@ export interface CanvasGenerationStatusInput {latestRun: Pick<TaskRun, "environment" | "status"> | undefined;/** The live ACP session for the task, if one is connected in this client. */session:- | Pick<AgentSession, "status" | "cloudStatus" | "isPromptPending">+ | Pick<+ AgentSession,+ | "status"+ | "isCloud"+ | "cloudStatus"+ | "isPromptPending"+ | "taskRunId"+ | "agentIdleForRunId"+ >| undefined;}@@ -25,20 +33,23 @@ export type CanvasTerminalStatus = Extract<// A cloud run's turn-level activity. The sandbox lingers after the agent's// turn so follow-ups can reuse it — the run record only completes on the-// inactivity timeout, long after generation actually ended — so a non-terminal-// status alone can't mean "generating". A live session mirror carries the-// turn-level signal (prompt-pending arms on session/prompt and clears on-// turn_complete); when one exists it decides, with "connecting" covering the-// attach/replay window before the prompt event has streamed in. Without a-// mirror the run status is all there is.+// inactivity timeout, long after generation actually ended. A live session+// therefore decides: prompt-pending proves work is active, while the per-run+// idle marker proves turn_complete arrived. The marker also covers attachment+// after an automatic prompt, where the prompt event itself may not be replayed.+// Without a mirror the run status is all there is.function isCloudRunActive(- latestRun: Pick<TaskRun, "status">,+ latestRun: Pick<TaskRun, "status"> | undefined,session: CanvasGenerationStatusInput["session"],): boolean {- const cloudStatus = session?.cloudStatus ?? latestRun.status;+ const cloudStatus = session?.cloudStatus ?? latestRun?.status;if (isTerminalStatus(cloudStatus)) return false;if (session) {- return session.status === "connecting" || session.isPromptPending === true;+ return (+ session.status === "connecting" ||+ session.isPromptPending === true ||+ session.agentIdleForRunId !== session.taskRunId+ );}return true;}@@ -63,7 +74,7 @@ export function isCanvasGenerationRunning({// Assume running while the task record is still loading.if (genTaskLoading) return true;- if (latestRun?.environment === "cloud") {+ if (latestRun?.environment === "cloud" || session?.isCloud === true) {return isCloudRunActive(latestRun, session);}@@ -88,7 +99,7 @@ export function isCanvasGenerating({if (!genTaskId) return false;if (genTaskLoading) return true;- if (latestRun?.environment === "cloud") {+ if (latestRun?.environment === "cloud" || session?.isCloud === true) {return isCloudRunActive(latestRun, session);}diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useReportSpace.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useReportSpace.test.tsxnew file mode 100644index 000000000000..227d8bc6f4e4--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useReportSpace.test.tsx@@ -0,0 +1,82 @@+// @vitest-environment jsdom++import { renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useReportSpace } from "./useReportSpace";++const createChannel = vi.fn(async () => ({ id: "general-id" }));+let currentProjectId = 1;+const channelsState: {+ channels: Array<{+ id: string;+ name: string;+ channelType: "public";+ starred: boolean;+ }>;+} = {+ channels: [],+};++vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({+ useChannels: () => ({ channels: channelsState.channels, isLoading: false }),+ useChannelMutations: () => ({ createChannel }),+}));+vi.mock("@posthog/ui/features/auth/store", () => ({+ useAuthStateValue: (+ selector: (state: { currentProjectId: number }) => number,+ ) => selector({ currentProjectId }),+}));++describe("useReportSpace", () => {+ beforeEach(() => {+ channelsState.channels = [];+ currentProjectId = 1;+ createChannel.mockClear();+ });++ it("provisions the default report space once and resolves its id", async () => {+ const { rerender, result } = renderHook(() => useReportSpace());+ await waitFor(() => expect(createChannel).toHaveBeenCalledTimes(1));+ expect(createChannel).toHaveBeenCalledWith("general", { star: true });++ rerender();+ expect(createChannel).toHaveBeenCalledTimes(1);++ channelsState.channels = [+ {+ id: "general-id",+ name: "general",+ channelType: "public",+ starred: false,+ },+ ];+ rerender();+ expect(result.current.reportSpaceId).toBe("general-id");+ });++ it("does not provision or expose the report space when disabled", () => {+ channelsState.channels = [+ {+ id: "general-id",+ name: "general",+ channelType: "public",+ starred: false,+ },+ ];++ const { result } = renderHook(() => useReportSpace(false));++ expect(createChannel).not.toHaveBeenCalled();+ expect(result.current).toEqual({ reportSpaceId: null, isLoading: false });+ });++ it("provisions again after the current project changes", async () => {+ const { rerender } = renderHook(() => useReportSpace());+ await waitFor(() => expect(createChannel).toHaveBeenCalledTimes(1));++ currentProjectId = 2;+ rerender();++ await waitFor(() => expect(createChannel).toHaveBeenCalledTimes(2));+ });+});diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useReportSpace.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useReportSpace.tsnew file mode 100644index 000000000000..f29e2081d9bf--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useReportSpace.ts@@ -0,0 +1,73 @@+import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import {+ useChannelMutations,+ useChannels,+} from "@posthog/ui/features/canvas/hooks/useChannels";+import { toast } from "@posthog/ui/primitives/toast";+import { useEffect, useRef, useState } from "react";++export const DEFAULT_REPORT_SPACE_NAME = "general";++export function useReportSpace(enabled = true): {+ reportSpaceId: string | null;+ isLoading: boolean;+} {+ const { channels, isLoading } = useChannels();+ const { createChannel } = useChannelMutations();+ const currentProjectId = useAuthStateValue((state) => state.currentProjectId);+ const creationStarted = useRef(false);+ const provisioningProjectId = useRef(currentProjectId);+ const [creationFailed, setCreationFailed] = useState(false);+ const reportSpace = channels.find(+ (channel) =>+ channel.channelType === "public" &&+ channel.name === DEFAULT_REPORT_SPACE_NAME,+ );++ useEffect(() => {+ if (provisioningProjectId.current === currentProjectId) return;+ provisioningProjectId.current = currentProjectId;+ creationStarted.current = false;+ setCreationFailed(false);+ }, [currentProjectId]);++ useEffect(() => {+ if (+ provisioningProjectId.current !== currentProjectId ||+ !enabled ||+ isLoading ||+ reportSpace ||+ creationStarted.current ||+ creationFailed+ )+ return;+ creationStarted.current = true;+ void createChannel(DEFAULT_REPORT_SPACE_NAME, { star: true }).catch(+ (error: unknown) => {+ creationStarted.current = false;+ setCreationFailed(true);+ toast.error("Couldn't create the report space", {+ // Stable id so concurrent hook instances collapse to one toast+ // instead of stacking identical failures.+ id: "report-space-creation-error",+ description:+ error instanceof Error+ ? error.message+ : "Refresh the page to try again.",+ });+ },+ );+ }, [+ createChannel,+ creationFailed,+ currentProjectId,+ enabled,+ isLoading,+ reportSpace,+ ]);++ return {+ reportSpaceId: enabled ? (reportSpace?.id ?? null) : null,+ isLoading: enabled && (isLoading || (!reportSpace && !creationFailed)),+ };+}diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.tsindex 72c83210dc80..343c5f8f182d 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.ts@@ -1,10 +1,14 @@import { seedInboxReportDetailCache } from "@posthog/core/inbox/inboxQuery";+import { REPORT_CANVAS_INBOX_FLAG } from "@posthog/shared";import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";+import { useReportSpace } from "@posthog/ui/features/canvas/hooks/useReportSpace";+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { reportKeys } from "@posthog/ui/features/inbox/hooks/useInboxReports";import { useInboxSignalsFilterStore } from "@posthog/ui/features/inbox/stores/inboxSignalsFilterStore";import { toast } from "@posthog/ui/primitives/toast";import {+ navigateToChannelDashboard,navigateToInboxDismissedDetail,navigateToInboxPullRequestDetail,navigateToInboxReportDetail,@@ -30,6 +34,11 @@ export function useOpenInboxReport() {const queryClient = useQueryClient();const client = useOptionalAuthenticatedClient();const resetFilters = useInboxSignalsFilterStore((s) => s.resetFilters);+ const reportCanvasesEnabled = useFeatureFlag(+ REPORT_CANVAS_INBOX_FLAG,+ import.meta.env.DEV,+ );+ const { reportSpaceId } = useReportSpace(reportCanvasesEnabled);return useCallback(async (reportId: string) => {@@ -53,6 +62,18 @@ export function useOpenInboxReport() {return;}+ if (+ reportCanvasesEnabled &&+ reportSpaceId &&+ report.canvas_session?.generation_status === "ready"+ ) {+ navigateToChannelDashboard(+ reportSpaceId,+ report.canvas_session.canvas_id,+ );+ return;+ }+resetFilters();seedInboxReportDetailCache(queryClient, report);if (report.status === "suppressed") {@@ -68,6 +89,6 @@ export function useOpenInboxReport() {toast.error("Failed to open report");}},- [client, queryClient, resetFilters],+ [client, queryClient, reportCanvasesEnabled, reportSpaceId, resetFilters],);}diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useSessionViewState.ts b/products/desktop/packages/ui/src/features/sessions/hooks/useSessionViewState.tsindex e582ea1658fe..120809a2ea75 100644--- a/products/desktop/packages/ui/src/features/sessions/hooks/useSessionViewState.ts+++ b/products/desktop/packages/ui/src/features/sessions/hooks/useSessionViewState.ts@@ -9,14 +9,13 @@ export function useSessionViewState(taskId: string, task: Task) {const session = useSessionForTask(taskId);const repoPath = useCwd(taskId) ?? null;const workspace = useWorkspace(taskId);- const isCloud = useIsCloudTask(taskId, task);+ const taskIsCloud = useIsCloudTask(taskId, task);- const derived = deriveSessionViewState(session, task, workspace, isCloud);+ const derived = deriveSessionViewState(session, task, workspace, taskIsCloud);return {session,repoPath,- isCloud,...derived,};}diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useRefreshedTask.test.tsx b/products/desktop/packages/ui/src/features/task-detail/hooks/useRefreshedTask.test.tsxindex 9d11d1c35add..2d6ebaf72dac 100644--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useRefreshedTask.test.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useRefreshedTask.test.tsx@@ -27,6 +27,16 @@ function task(runId: string, status: "failed" | "in_progress"): Task {} as Task;}+function signalsTaskWithoutRun(): Task {+ return {+ ...task("pending-run", "in_progress"),+ title: "Generate report canvas",+ description: "Generate a canvas",+ origin_product: "signal_report",+ latest_run: undefined,+ };+}+describe("useRefreshedTask", () => {beforeEach(() => {mocks.getTask.mockReset();@@ -54,4 +64,34 @@ describe("useRefreshedTask", () => {});expect(mocks.getTask).toHaveBeenCalledWith("task-123");});++ it("polls a Signals task until its cloud run is attached", async () => {+ const pendingTask = signalsTaskWithoutRun();+ const runningTask = {+ ...task("run-child", "in_progress"),+ origin_product: "signal_report",+ } as Task;+ mocks.getTask+ .mockResolvedValueOnce(pendingTask)+ .mockResolvedValueOnce(runningTask);+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const wrapper = ({ children }: PropsWithChildren) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );++ const { result } = renderHook(+ () => useRefreshedTask("task-123", pendingTask),+ { wrapper },+ );++ await waitFor(+ () => {+ expect(result.current.latest_run?.id).toBe("run-child");+ },+ { timeout: 3_000 },+ );+ expect(mocks.getTask).toHaveBeenCalledTimes(2);+ });});diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useRefreshedTask.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useRefreshedTask.tsindex df35a8f382f2..d50f62c1140d 100644--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useRefreshedTask.ts+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useRefreshedTask.ts@@ -2,11 +2,19 @@ import type { Task } from "@posthog/shared/domain-types";import { useQuery } from "@tanstack/react-query";import { taskDetailQuery } from "../../tasks/queries";+const SIGNALS_RUN_POLL_INTERVAL_MS = 2_000;+export function useRefreshedTask(taskId: string, initialTask: Task): Task {const { data } = useQuery({...taskDetailQuery(taskId),initialData: initialTask,refetchOnMount: "always",+ refetchInterval: (query) => {+ const task = query.state.data;+ return task?.origin_product === "signal_report" && !task.latest_run?.id+ ? SIGNALS_RUN_POLL_INTERVAL_MS+ : false;+ },});// The refetch can resolve without data (e.g. a stale / cross-project iddiff --git a/products/desktop/packages/ui/src/features/workspace/useIsCloudTask.ts b/products/desktop/packages/ui/src/features/workspace/useIsCloudTask.tsindex 5c2e6a633511..a759444e2b4f 100644--- a/products/desktop/packages/ui/src/features/workspace/useIsCloudTask.ts+++ b/products/desktop/packages/ui/src/features/workspace/useIsCloudTask.ts@@ -1,8 +1,8 @@import type { Task } from "@posthog/shared/domain-types";-import { useWorkspace } from "./useWorkspace";+import { isCloudTask, useWorkspace } from "./useWorkspace";export function useIsCloudTask(taskId: string, task?: Task): boolean {const workspace = useWorkspace(taskId);- if (workspace?.mode === "cloud") return true;- return task?.latest_run?.environment === "cloud";+ if (!task) return workspace?.mode === "cloud";+ return isCloudTask(task, workspace);}diff --git a/products/desktop/packages/ui/src/features/workspace/useWorkspace.test.ts b/products/desktop/packages/ui/src/features/workspace/useWorkspace.test.tsindex 3b35c184a348..d2874919be00 100644--- a/products/desktop/packages/ui/src/features/workspace/useWorkspace.test.ts+++ b/products/desktop/packages/ui/src/features/workspace/useWorkspace.test.ts@@ -10,6 +10,10 @@ function task(environment?: TaskRunEnvironment): Task {} as Task;}+function signalReportTask(): Task {+ return { ...task(), origin_product: "signal_report" };+}+function workspace(mode: Workspace["mode"]): Workspace {return { mode } as Workspace;}@@ -34,6 +38,12 @@ describe("isCloudTask", () => {workspace: null,expected: false,},+ {+ name: "Signals report before its run is visible",+ task: signalReportTask(),+ workspace: null,+ expected: true,+ },{name: "cloud workspace row",task: task(),diff --git a/products/desktop/packages/ui/src/features/workspace/useWorkspace.ts b/products/desktop/packages/ui/src/features/workspace/useWorkspace.tsindex 131c1b98ba2d..b91d4c5da8d2 100644--- a/products/desktop/packages/ui/src/features/workspace/useWorkspace.ts+++ b/products/desktop/packages/ui/src/features/workspace/useWorkspace.ts@@ -39,7 +39,10 @@ export function isCloudTask(task: Task, workspace: Workspace | null): boolean {if (workspace) {return workspace.mode === "cloud";}- return task.latest_run?.environment === "cloud";+ return (+ task.origin_product === "signal_report" ||+ task.latest_run?.environment === "cloud"+ );}export function useIsCloudTask(task: Task): boolean {diff --git a/products/desktop/packages/ui/src/router/routes/code/inbox.test.tsx b/products/desktop/packages/ui/src/router/routes/code/inbox.test.tsxnew file mode 100644index 000000000000..c07b2a0c9bad--- /dev/null+++ b/products/desktop/packages/ui/src/router/routes/code/inbox.test.tsx@@ -0,0 +1,78 @@+import { render, screen } from "@testing-library/react";+import type { ReactElement } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ reportId: "report-id" as string | undefined,+ pathname: "/code/inbox/reports/report-id",+ openReport: vi.fn(),+}));++vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({+ useFeatureFlag: () => true,+}));+vi.mock("@posthog/ui/features/inbox/hooks/useOpenInboxReport", () => ({+ useOpenInboxReport: () => mocks.openReport,+}));+vi.mock("@posthog/ui/features/inbox/components/InboxView", () => ({+ InboxView: () => <div>Inbox content</div>,+}));+vi.mock("@posthog/ui/router/routeSkeletons", () => ({+ AppPageSkeleton: () => null,+ withRouteSkeleton: () => ({}),+}));+vi.mock("@tanstack/react-router", () => ({+ createFileRoute: () => (options: { component: () => ReactElement }) => ({+ options,+ }),+ useLocation: () => ({ pathname: mocks.pathname }),+ useParams: () => ({ reportId: mocks.reportId }),+}));++import { Route } from "./inbox";++const InboxRoute = Route.options.component as () => ReactElement;++describe("InboxRoute", () => {+ beforeEach(() => {+ mocks.reportId = "report-id";+ mocks.pathname = "/code/inbox/reports/report-id";+ mocks.openReport.mockClear();+ });++ it("keeps Inbox visible while resolving a report without a canvas", () => {+ render(<InboxRoute />);++ expect(screen.getByText("Inbox content")).toBeInTheDocument();+ expect(mocks.openReport).toHaveBeenCalledWith("report-id");+ });++ it("opens an eligible report once while keeping Inbox mounted", () => {+ const { rerender } = render(<InboxRoute />);+ rerender(<InboxRoute />);++ expect(mocks.openReport).toHaveBeenCalledTimes(1);+ expect(screen.getByText("Inbox content")).toBeInTheDocument();+ });++ it.each(["pulls", "reports", "dismissed", "runs", "agents"])(+ "keeps the %s list route in Inbox",+ (tab) => {+ mocks.reportId = undefined;+ mocks.pathname = `/code/inbox/${tab}`;++ render(<InboxRoute />);++ expect(screen.getByText("Inbox content")).toBeInTheDocument();+ expect(mocks.openReport).not.toHaveBeenCalled();+ },+ );++ it("does not treat an agent run as a Signal report", () => {+ mocks.pathname = "/code/inbox/runs/report-id";++ render(<InboxRoute />);++ expect(mocks.openReport).not.toHaveBeenCalled();+ });+});diff --git a/products/desktop/packages/ui/src/router/routes/code/inbox.tsx b/products/desktop/packages/ui/src/router/routes/code/inbox.tsxindex edd58890d132..8e0386e9ec04 100644--- a/products/desktop/packages/ui/src/router/routes/code/inbox.tsx+++ b/products/desktop/packages/ui/src/router/routes/code/inbox.tsx@@ -1,11 +1,47 @@+import { REPORT_CANVAS_INBOX_FLAG } from "@posthog/shared";+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { InboxView } from "@posthog/ui/features/inbox/components/InboxView";+import { useOpenInboxReport } from "@posthog/ui/features/inbox/hooks/useOpenInboxReport";import {AppPageSkeleton,withRouteSkeleton,} from "@posthog/ui/router/routeSkeletons";-import { createFileRoute } from "@tanstack/react-router";+import {+ createFileRoute,+ useLocation,+ useParams,+} from "@tanstack/react-router";+import { type ReactElement, useEffect, useRef } from "react";export const Route = createFileRoute("/code/inbox")({- component: InboxView,+ component: InboxRoute,...withRouteSkeleton(AppPageSkeleton),});++function InboxRoute(): ReactElement {+ const reportCanvasesEnabled = useFeatureFlag(+ REPORT_CANVAS_INBOX_FLAG,+ import.meta.env.DEV,+ );+ const { reportId } = useParams({ strict: false });+ const { pathname } = useLocation();+ const openReport = useOpenInboxReport();+ const openedReportId = useRef<string | null>(null);+ const isSignalReportDetail = ["reports", "pulls", "dismissed"].some((tab) =>+ pathname.startsWith(`/code/inbox/${tab}/`),+ );++ useEffect(() => {+ if (+ reportCanvasesEnabled &&+ isSignalReportDetail &&+ reportId &&+ openedReportId.current !== reportId+ ) {+ openedReportId.current = reportId;+ void openReport(reportId);+ }+ }, [isSignalReportDetail, openReport, reportCanvasesEnabled, reportId]);++ return <InboxView />;+}