: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): preserve navigation context on report pages (#97143)
Shy Alteradaf427051ed
diff --git a/products/desktop/packages/ui/src/features/agents/agentsPageStore.test.tsx b/products/desktop/packages/ui/src/features/agents/agentsPageStore.test.tsxindex 850042c43fe4..56032700c5ab 100644--- a/products/desktop/packages/ui/src/features/agents/agentsPageStore.test.tsx+++ b/products/desktop/packages/ui/src/features/agents/agentsPageStore.test.tsx@@ -1,55 +1,87 @@-import { act, renderHook } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";-const location = vi.hoisted(() => ({- state: { tabId: "first" },- href: "/settings/agents",-}));-vi.mock("@tanstack/react-router", () => ({- useRouterState: ({- select,- }: {- select: (state: { location: typeof location }) => unknown;- }) => select({ location }),-}));+const navigate = vi.hoisted(() => vi.fn());vi.mock("@posthog/ui/router/routerRef", () => ({- getRouterOrNull: () => ({ history: { location } }),+ getRouterOrNull: () => ({ navigate }),}));import {+ type AgentsPageSearch,agentsPageActions,- useAgentsPageActions,- useAgentsTab,- useOpenAgent,+ agentsTabFrom,+ openAgentFrom,} from "./agentsPageStore";-describe("agent browser tab selection", () => {- it("restores a separate selection when tabs have the same href", () => {- const { result, rerender } = renderHook(() => ({- tab: useAgentsTab(),- agent: useOpenAgent(),- actions: useAgentsPageActions(),- }));- act(() =>- result.current.actions.openAgent("first-agent", {- findingId: "finding-1",- }),- );- location.state.tabId = "second";- rerender();- expect(result.current.agent).toBeNull();- act(() => result.current.actions.showTab("memory"));- location.state.tabId = "first";- rerender();- expect(result.current.agent).toMatchObject({- slug: "first-agent",- tab: "output",- findingId: "finding-1",+const lastCall = () =>+ navigate.mock.lastCall?.[0] as {+ to: string;+ params: { category: string };+ replace: boolean;+ search: (previous: AgentsPageSearch) => AgentsPageSearch;+ };++const lastSearch = (previous: AgentsPageSearch): AgentsPageSearch =>+ lastCall().search(previous);++describe("agents page selection", () => {+ it.each([+ [{}, "agents"],+ [{ tab: "memory" }, "memory"],+ [{ tab: "nonsense" }, "agents"],+ ])("reads the page tab from %o", (search, tab) =>+ expect(agentsTabFrom(search)).toBe(tab),+ );++ it.each([+ [{}, null],+ [+ { agent: "signals-scout-aio" },+ { slug: "signals-scout-aio", tab: "activity" },+ ],+ [+ { agent: "a", finding: "f-1" },+ { slug: "a", tab: "output", findingId: "f-1" },+ ],+ [+ { agent: "a", agentTab: "settings" },+ { slug: "a", tab: "settings" },+ ],+ [+ { agent: "a", agentTab: "nonsense" },+ { slug: "a", tab: "activity" },+ ],+ ])("reads the open agent from %o", (search, agent) =>+ agent+ ? expect(openAgentFrom(search)).toMatchObject(agent)+ : expect(openAgentFrom(search)).toBeNull(),+ );++ it("puts the open agent in the URL and keeps the report source", () => {+ agentsPageActions().openAgent("signals-scout-aio", { tab: "output" });+ const { to, params, replace } = lastCall();+ expect(to).toBe("/settings/$category");+ expect(params).toEqual({ category: "agents" });+ expect(replace).toBe(false);+ expect(lastSearch({ from: "/inbox/reports" })).toEqual({+ from: "/inbox/reports",+ agent: "signals-scout-aio",+ agentTab: "output",+ });+ });++ it("drops the agent when returning to a page tab", () =>+ expect(+ (agentsPageActions().showTab("memory"),+ lastSearch({ from: "/activity", agent: "a", agentTab: "output" })),+ ).toEqual({ from: "/activity", tab: "memory" }));++ it("replaces the entry when switching the agent's own tab", () => {+ agentsPageActions().showAgentTab("settings");+ expect(lastCall().replace).toBe(true);+ expect(lastSearch({ agent: "a", finding: "f-1" })).toEqual({+ agent: "a",+ agentTab: "settings",+ finding: undefined,});- act(() => agentsPageActions().showTab("agents"));- expect(result.current.agent).toBeNull();- location.state.tabId = "second";- rerender();- expect(result.current.tab).toBe("memory");});});diff --git a/products/desktop/packages/ui/src/features/agents/agentsPageStore.ts b/products/desktop/packages/ui/src/features/agents/agentsPageStore.tsindex 8ced00bca51d..5d686933bcb1 100644--- a/products/desktop/packages/ui/src/features/agents/agentsPageStore.ts+++ b/products/desktop/packages/ui/src/features/agents/agentsPageStore.ts@@ -1,78 +1,111 @@-import type { ScoutDetailTab } from "@posthog/core/scouts/scoutDetailTabs";+import {+ SCOUT_DETAIL_TABS,+ type ScoutDetailTab,+} from "@posthog/core/scouts/scoutDetailTabs";import { getRouterOrNull } from "@posthog/ui/router/routerRef";import { useRouterState } from "@tanstack/react-router";import { useMemo } from "react";-import { create } from "zustand";export type AgentsTab = "agents" | "memory" | "setup";+export const AGENTS_TABS: readonly AgentsTab[] = ["agents", "memory", "setup"];+interface OpenAgent {slug: string;tab: ScoutDetailTab;findingId?: string;}-interface AgentsPageState {- tab: AgentsTab;- agent: OpenAgent | null;+export interface AgentsPageSearch {+ from?: string;+ tab?: AgentsTab;+ agent?: string;+ agentTab?: ScoutDetailTab;+ finding?: string;}-const DEFAULT_STATE: AgentsPageState = { tab: "agents", agent: null };-const useStore = create<{ pages: Record<string, AgentsPageState> }>(() => ({- pages: {},-}));+export function agentsTabFrom(search: unknown): AgentsTab {+ const tab = (search as AgentsPageSearch | undefined)?.tab;+ return tab && AGENTS_TABS.includes(tab) ? tab : "agents";+}-function usePageKey(): string {- return useRouterState({- select: (state) => state.location.state.tabId ?? "default",- });+export function openAgentFrom(search: unknown): OpenAgent | null {+ const value = search as AgentsPageSearch | undefined;+ if (!value?.agent) return null;+ const tab =+ value.agentTab && SCOUT_DETAIL_TABS.includes(value.agentTab)+ ? value.agentTab+ : value.finding+ ? "output"+ : "activity";+ return { slug: value.agent, tab, findingId: value.finding };}-export function agentsPageActions(- key = getRouterOrNull()?.history.location.state.tabId ?? "default",-) {- const update = (change: (state: AgentsPageState) => AgentsPageState) => {- useStore.setState((state) => ({- pages: {- ...state.pages,- [key]: change(state.pages[key] ?? DEFAULT_STATE),- },- }));+export function agentsPageActions() {+ const update = (+ change: (previous: AgentsPageSearch) => AgentsPageSearch,+ replace: boolean,+ ) => {+ void getRouterOrNull()?.navigate({+ to: "/settings/$category",+ params: { category: "agents" },+ search: change,+ replace,+ });};+ const keepSource = ({ from }: AgentsPageSearch): AgentsPageSearch =>+ from ? { from } : {};return {- showTab: (tab: AgentsTab) => update(() => ({ tab, agent: null })),+ showTab: (tab: AgentsTab) =>+ update((previous) => ({ ...keepSource(previous), tab }), false),openAgent: (slug: string,options?: { tab?: ScoutDetailTab; findingId?: string },) =>- update(() => ({- tab: "agents",- agent: {- slug,- tab: options?.tab ?? (options?.findingId ? "output" : "activity"),- findingId: options?.findingId,- },- })),+ update(+ (previous) => ({+ ...keepSource(previous),+ agent: slug,+ ...(options?.tab ? { agentTab: options.tab } : {}),+ ...(options?.findingId ? { finding: options.findingId } : {}),+ }),+ false,+ ),showAgentTab: (tab: ScoutDetailTab) =>- update((state) =>- state.agent- ? { ...state, agent: { ...state.agent, tab, findingId: undefined } }- : state,+ update(+ (previous) =>+ previous.agent+ ? { ...previous, agentTab: tab, finding: undefined }+ : previous,+ true,),};}-export function useAgentsTab() {- const key = usePageKey();- return useStore((state) => (state.pages[key] ?? DEFAULT_STATE).tab);+export function useAgentsTab(): AgentsTab {+ return useRouterState({+ select: (state) => agentsTabFrom(state.location.search),+ });}-export function useOpenAgent() {- const key = usePageKey();- return useStore((state) => (state.pages[key] ?? DEFAULT_STATE).agent);+export function useOpenAgent(): OpenAgent | null {+ const packed = useRouterState({+ select: (state) => {+ const open = openAgentFrom(state.location.search);+ return open ? `${open.slug} ${open.tab} ${open.findingId ?? ""}` : null;+ },+ });+ return useMemo(() => {+ if (!packed) return null;+ const [slug, tab, findingId] = packed.split(" ");+ return {+ slug,+ tab: tab as ScoutDetailTab,+ findingId: findingId || undefined,+ };+ }, [packed]);}export function useAgentsPageActions() {- const key = usePageKey();- return useMemo(() => agentsPageActions(key), [key]);+ return useMemo(() => agentsPageActions(), []);}diff --git a/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsx b/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsxindex bf013b176a7c..747aa9f3819e 100644--- a/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsx+++ b/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsx@@ -2,7 +2,6 @@ import { PlusIcon } from "@phosphor-icons/react";import { Button } from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared";import {- useAgentsPageActions,useAgentsTab,useOpenAgent,} from "@posthog/ui/features/agents/agentsPageStore";@@ -12,32 +11,14 @@ import { NewAgentDialog } from "@posthog/ui/features/scouts/components/NewAgentDimport { ScoutDetailView } from "@posthog/ui/features/scouts/components/ScoutDetailView";import { ScoutsFleetView } from "@posthog/ui/features/scouts/components/ScoutsFleetView";import { ScratchpadView } from "@posthog/ui/features/scouts/components/ScratchpadView";-import { getRouterOrNull } from "@posthog/ui/router/routerRef";import { track } from "@posthog/ui/shell/analytics";-import { useEffect, useRef, useState } from "react";+import { useState } from "react";import { AgentsTabLayout } from "./AgentsTabLayout";/** The Agents settings page: the fleet, what it found, and what it connects to. */export function AgentsView() {const tab = useAgentsTab();const agent = useOpenAgent();- const { showTab } = useAgentsPageActions();-- const mounted = useRef(false);- useEffect(() => {- mounted.current = true;- return () => {- mounted.current = false;- // StrictMode mounts again before this check. A real exit resets only this tab.- queueMicrotask(() => {- if (- !mounted.current &&- getRouterOrNull()?.state.location.pathname !== "/settings/agents"- )- showTab("agents");- });- };- }, [showTab]);if (agent) {return (diff --git a/products/desktop/packages/ui/src/features/billing/UsageButton.tsx b/products/desktop/packages/ui/src/features/billing/UsageButton.tsxindex 1a4432b4a147..425566e1b056 100644--- a/products/desktop/packages/ui/src/features/billing/UsageButton.tsx+++ b/products/desktop/packages/ui/src/features/billing/UsageButton.tsx@@ -16,6 +16,7 @@ import {ANALYTICS_EVENTS,type UpgradePromptClickedSurface,} from "@posthog/shared/analytics-events";+import { settingsSourceHref } from "@posthog/ui/router/reportNavigation";import { Link } from "@tanstack/react-router";import { useState } from "react";import { track } from "../../shell/analytics";@@ -122,6 +123,7 @@ export function UsageButton() {<Linkto="/settings/$category"params={{ category: "plan-usage" }}+ search={{ from: settingsSourceHref() }}onClick={handleTriggerClick}/>}diff --git a/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.md b/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.mdindex a0c5844a028b..8f164894c46d 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.md+++ b/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.md@@ -215,9 +215,9 @@ retarget its originating background tab as described below. `railHistoryStore`- `rewriteSavedLocation` (in `@posthog/shared`) runs over persisted hrefs onload, so a snapshot written before the routes were flattened does not restoretabs onto `/website/*` routes that no longer exist.-- Per-tab `scrollState` is reserved but **unwired** — scroll restoration is a- later follow-up (it needs a sandbox postMessage contract; the canvas iframe is- null-origin so the host can't read scroll).+- Per-tab `scrollState` is reserved but **unwired**. Router history restores native+ page scroll for report visits and their source pages. Canvas iframe scrolling+ still needs a sandbox postMessage contract; the iframe is null-origin.## Gotchas / implementation notesdiff --git a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsxindex 47397630d788..ed31c9c9b494 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx+++ b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx@@ -1,4 +1,5 @@import { MagnifyingGlassIcon } from "@phosphor-icons/react";+import { humanizeReportTitle } from "@posthog/core/inbox/reportPresentation";import { useService } from "@posthog/di/react";import {closeTab as closeTabLocal,@@ -46,6 +47,7 @@ import { getLeafPanel } from "@posthog/ui/features/panels/panelStoreHelpers";import { getTaskInputSessionId } from "@posthog/ui/features/task-detail/taskInputSession";import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";import { useTasks } from "@posthog/ui/features/tasks/useTasks";+import { reportIdFromHref } from "@posthog/ui/router/reportNavigation";import { useAppView } from "@posthog/ui/router/useAppView";import { isMac } from "@posthog/ui/utils/platform";import { useQuery } from "@tanstack/react-query";@@ -142,6 +144,7 @@ function BrowserTabStripImpl() {dashboardId?: string;taskId?: string;feedId?: string;+ reportId?: string;};const routeFeedId = params.feedId ?? null;// The in-flight tag: flips the instant you navigate, so the strip's highlight@@ -180,6 +183,9 @@ function BrowserTabStripImpl() {routeAppView === "activity" && activitySelection?.kind === "report"? activitySelection.reportId: null;+ const activeReportId =+ activeActivityReportId ??+ (routeAppView === "report" ? (params.reportId ?? null) : null);const { channels, isLoading: channelsLoading } = useChannels();// The scoped space is null until the channel list has loaded and the route@@ -261,9 +267,7 @@ function BrowserTabStripImpl() {...taskDetailQuery(activeSession.taskId ?? ""),enabled: !!activeSession.taskId,});- const { data: activeReportRecord } = useInboxReportById(- activeActivityReportId,- );+ const { data: activeReportRecord } = useInboxReportById(activeReportId);// Remember names so a background tab from another channel keeps its label// after its channel's list unloads. Written in an effect (not during render)// to keep render pure; the tabs memo reads the live lists first anyway.@@ -297,15 +301,15 @@ function BrowserTabStripImpl() {if (activeRecord?.id === params.dashboardId) return activeRecord.name;return dashboards.find((d) => d.id === params.dashboardId)?.name ?? null;}- if (activeActivityReportId) {- if (activeReportRecord?.id !== activeActivityReportId) return null;- return activeReportRecord.title?.trim() || "Untitled report";+ if (activeReportId) {+ if (activeReportRecord?.id !== activeReportId) return null;+ return humanizeReportTitle(activeReportRecord.title, "Untitled report");}return null;}, [activeSession.taskId,params.dashboardId,- activeActivityReportId,+ activeReportId,activeTaskRecord,allTasks,activeRecord,@@ -324,7 +328,7 @@ function BrowserTabStripImpl() {}// A selected Activity report owns the tab label. While its query resolves,// keep the tab's stored title instead of replacing it with "Activity".- if (activeActivityReportId) return null;+ if (activeReportId) return null;if (routeAppView) return TAB_APP_VIEW_META[routeAppView].label;return null;}, [@@ -333,7 +337,7 @@ function BrowserTabStripImpl() {feedName,params.channelId,activeSession.channelId,- activeActivityReportId,+ activeReportId,channelName,routeChannelSection,routeAppView,@@ -606,17 +610,17 @@ function BrowserTabStripImpl() {// space to Activity, persisted channel context must not turn the new// top-level tab into a space tab.if (appView && isTabAppView(appView)) {- const activityReportId = isActive- ? activeActivityReportId- : activityReportIdFromHref(t.href);- const activityReport = activityReportId+ const tabReportId = isActive+ ? activeReportId+ : (activityReportIdFromHref(t.href) ?? reportIdFromHref(t.href));+ const reportTab = tabReportId? {title: isActive? (activeTitle ?? t.viewState?.title): t.viewState?.title,}: null;- const display = resolveTabAppViewDisplay(appView, activityReport);+ const display = resolveTabAppViewDisplay(appView, reportTab);return {id: t.id,...display,@@ -668,7 +672,7 @@ function BrowserTabStripImpl() {params.dashboardId,activeSession.taskId,activeSession.channelId,- activeActivityReportId,+ activeReportId,activeTitle,routeChannelSection,routeAppView,@@ -736,6 +740,7 @@ function BrowserTabStripImpl() {navigate({ to: "/activity", state });break;case "home":+ case "report":navigate({ to: "/", state });break;case "inbox":diff --git a/products/desktop/packages/ui/src/features/browser-tabs/tabAppViews.test.tsx b/products/desktop/packages/ui/src/features/browser-tabs/tabAppViews.test.tsxindex b6a3a7aa7aa4..050ad9e2cf0a 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/tabAppViews.test.tsx+++ b/products/desktop/packages/ui/src/features/browser-tabs/tabAppViews.test.tsx@@ -1,25 +1,32 @@-import { EnvelopeSimple } from "@phosphor-icons/react";+import { EnvelopeSimple, FileTextIcon } from "@phosphor-icons/react";import { isValidElement } from "react";import { describe, expect, it } from "vitest";import { resolveTabAppViewDisplay } from "./tabAppViews";describe("resolveTabAppViewDisplay", () => {- it("shows the report title and rail mail icon for an Activity report", () => {- const display = resolveTabAppViewDisplay("activity", {- title: "Checkout errors increased",- });+ it.each([+ ["activity", EnvelopeSimple],+ ["report", FileTextIcon],+ ] as const)(+ "shows the report title on a %s tab, with its own icon",+ (appView, icon) => {+ const display = resolveTabAppViewDisplay(appView, {+ title: "Checkout errors increased",+ });- expect(display.label).toBe("Checkout errors increased");- expect(isValidElement(display.icon)).toBe(true);- if (!isValidElement(display.icon)) return;- expect(display.icon.type).toBe(EnvelopeSimple);- });+ expect(display.label).toBe("Checkout errors increased");+ expect(isValidElement(display.icon)).toBe(true);+ if (!isValidElement(display.icon)) return;+ expect(display.icon.type).toBe(icon);+ },+ );- it("keeps static labels for top-level destinations", () => {- expect(resolveTabAppViewDisplay("activity", null).label).toBe("Activity");- expect(- resolveTabAppViewDisplay("inbox", { title: "Ignored report title" })- .label,- ).toBe("Self-driving");- });+ it.each([+ ["activity", null, "Activity"],+ ["report", null, "Report"],+ ["report", { title: " " }, "Report"],+ ["inbox", { title: "Ignored report title" }, "Self-driving"],+ ] as const)("labels a %s tab with %o as %s", (appView, report, label) =>+ expect(resolveTabAppViewDisplay(appView, report).label).toBe(label),+ );});diff --git a/products/desktop/packages/ui/src/features/browser-tabs/tabAppViews.tsx b/products/desktop/packages/ui/src/features/browser-tabs/tabAppViews.tsxindex 42de74b23c95..40e3b34fbc17 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/tabAppViews.tsx+++ b/products/desktop/packages/ui/src/features/browser-tabs/tabAppViews.tsx@@ -4,6 +4,7 @@ import {BookOpenTextIcon,BrainIcon,EnvelopeSimple,+ FileTextIcon,GearIcon,PlugsConnectedIcon,RepeatIcon,@@ -19,6 +20,7 @@ export type TabAppView = Extract<| "activity"| "home"| "inbox"+ | "report"| "agents"| "loops"| "archived"@@ -39,6 +41,7 @@ export const TAB_APP_VIEW_META: Record<},home: { label: "Home", icon: <SquaresFourIcon size={14} /> },inbox: { label: "Self-driving", icon: <TrayIcon size={14} /> },+ report: { label: "Report", icon: <FileTextIcon size={14} /> },agents: { label: "Agents", icon: <RobotIcon size={14} /> },loops: { label: "Loops", icon: <RepeatIcon size={14} /> },archived: { label: "Archived", icon: <ArchiveIcon size={14} /> },@@ -59,18 +62,25 @@ export function isTabAppView(value: string): value is TabAppView {return Object.hasOwn(TAB_APP_VIEW_META, value);}-interface ActivityReportTabContext {+interface ReportTabContext {title: string | null | undefined;}+const REPORT_TITLED_VIEWS: readonly TabAppView[] = ["activity", "report"];+export function resolveTabAppViewDisplay(appView: TabAppView,- activityReport: ActivityReportTabContext | null,+ report: ReportTabContext | null,): { label: string; icon: ReactNode } {- if (appView === "activity" && activityReport) {+ if (report && REPORT_TITLED_VIEWS.includes(appView)) {return {- label: activityReport.title?.trim() || TAB_APP_VIEW_META.activity.label,- icon: <EnvelopeSimple size={14} />,+ label: report.title?.trim() || TAB_APP_VIEW_META[appView].label,+ icon:+ appView === "report" ? (+ <FileTextIcon size={14} />+ ) : (+ <EnvelopeSimple size={14} />+ ),};}return TAB_APP_VIEW_META[appView];diff --git a/products/desktop/packages/ui/src/features/canvas/AGENTS.md b/products/desktop/packages/ui/src/features/canvas/AGENTS.mdindex 9cb50cf1e2fa..4c2f2183e69a 100644--- a/products/desktop/packages/ui/src/features/canvas/AGENTS.md+++ b/products/desktop/packages/ui/src/features/canvas/AGENTS.md@@ -42,6 +42,10 @@ changing breadcrumbs, canvas naming, or the canvas generation harness. The root`railPane.ts`: Home (`/`), Spaces (`/spaces`), Activity (`/activity`),Inbox (`/inbox`), Command Center (`/command-center`), Loops (`/loops`).Unclaimed routes belong to Spaces.+ Canonical report pages (`/reports/$reportId`) are not a new rail button.+ `useRailPane` keeps the source pane from the validated `?from=` search param;+ a report with no source selects no rail button and has no contextual sidebar.+ Space and feed sources retain their own sidebar, not the report's owning space.Only Spaces and Activity own the column beside the rail; the rest arewhole-screen, so no route under them may draw a second nav.- **A rail pick returns you to where that destination was**, not to its index.diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelBreadcrumb.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelBreadcrumb.tsxindex 91c60aa03443..858731a775e4 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelBreadcrumb.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelBreadcrumb.tsx@@ -1,12 +1,10 @@import { LinkIcon, StarIcon } from "@phosphor-icons/react";import {- Button,ContextMenu,ContextMenuContent,ContextMenuItem,ContextMenuSeparator,ContextMenuTrigger,- cn,Tooltip,TooltipContent,TooltipTrigger,@@ -18,9 +16,13 @@ import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import { copyChannelLink } from "@posthog/ui/features/canvas/utils/copyChannelLink";import { HeaderTitleEditor } from "@posthog/ui/features/task-detail/HeaderTitleEditor";+import {+ BreadcrumbSegment,+ BreadcrumbSeparator,+} from "@posthog/ui/primitives/Breadcrumb";import { toast } from "@posthog/ui/primitives/toast";import { track } from "@posthog/ui/shell/analytics";-import { Flex, Text } from "@radix-ui/themes";+import { Flex } from "@radix-ui/themes";import { useNavigate, useRouterState } from "@tanstack/react-router";import { type ReactNode, useState } from "react";@@ -175,85 +177,6 @@ export function ChannelBreadcrumb({);}-/**- * One segment of the breadcrumb. Always a Button, so every segment carries the- * same padding, height and icon gap whether or not it goes anywhere — the leaf- * used to be bare text, which left it visually adrift from its siblings.- *- * Without `onClick` the segment is genuinely inert: `aria-disabled` (so quill- * drops the hover fill and assistive tech reads it as unavailable) plus- * `pointer-events-none`, and out of the tab order. The disabled dimming is- * overridden — a breadcrumb has to stay readable.- */-function BreadcrumbSegment({- icon,- label,- strong,- muted,- shrink,- onClick,- contextMenu = false,- className,- ...rest-}: {- icon?: ReactNode;- label: string;- /** The leaf gives up width first, since it carries the longest name. */- shrink?: boolean;- /** The root segment carries the space name, which reads heavier. */- strong?: boolean;- /** The leaf is the current page, so it sits back from the linked segments. */- muted?: boolean;- /** Navigates, or (on a renamable leaf) opens the inline editor. */- onClick?: () => void;- contextMenu?: boolean;- className?: string;-}) {- const interactive = Boolean(onClick);-- return (- <Button- {...rest}- type="button"- size="sm"- aria-disabled={interactive ? undefined : true}- tabIndex={interactive ? undefined : -1}- onClick={onClick}- className={cn(- "no-drag min-w-0",- // `shrink` beats quill's own `shrink-0`. Only the leaf takes it: a- // segment that cannot shrink keeps its full width in a row that has- // run out, and paints its label over the marks after it. The fixed- // segments stay whole, so a long session name is what gives.- shrink && "shrink",- // Live segments (a link, or a click-to-rename leaf) behave like- // any other button: pointer cursor and hover fill. Inert ones read as- // plain text — full opacity, ordinary cursor, and no hover (quill's- // hover rules already skip aria-disabled) — and leave the tab order.- interactive || contextMenu- ? "cursor-pointer!"- : "pointer-events-none cursor-default! opacity-100!",- className,- )}- >- {icon && (- <span className="flex shrink-0 text-muted-foreground/80">{icon}</span>- )}- {/* No `title`: the native tooltip duplicated the styled one, and on the- fixed segments there was nothing worth revealing. */}- <Text- className={cn(- "min-w-0 truncate whitespace-nowrap text-[13px]",- strong && "font-medium",- muted && "text-muted-foreground",- )}- >- {label}- </Text>- </Button>- );-}-function ChannelSegmentContextMenu({channelId,children,@@ -310,9 +233,3 @@ function ChannelSegmentContextMenu({</ContextMenu>);}--function BreadcrumbSeparator() {- return (- <Text className="shrink-0 text-[13px] text-muted-foreground/20">/</Text>- );-}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelRouteSync.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelRouteSync.tsxindex 094c084104a6..29da641bc260 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelRouteSync.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelRouteSync.tsx@@ -6,7 +6,11 @@ import {showChannelPane,} from "@posthog/ui/features/canvas/stores/channelPaneStore";import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";-import { useParams } from "@tanstack/react-router";+import {+ reportSourceHrefFromLocation,+ resolveNavigationSource,+} from "@posthog/ui/router/reportNavigation";+import { useParams, useRouterState } from "@tanstack/react-router";import { useEffect, useRef } from "react";/**@@ -16,7 +20,14 @@ import { useEffect, useRef } from "react";*/export function ChannelRouteSync() {const channelsLayout = useChannelsLayout();- const routeChannelId = useParams({ strict: false }).channelId;+ const sourceChannelId = useRouterState({+ select: (state) =>+ resolveNavigationSource(+ reportSourceHrefFromLocation(state.resolvedLocation ?? state.location),+ )?.spaceId ?? undefined,+ });+ const routeChannelId =+ useParams({ strict: false }).channelId ?? sourceChannelId;const setCurrentChannel = useCurrentChannelStore((s) => s.setCurrentChannel);const { currentChannelId, channels } = useCurrentChannel({enabled: channelsLayout,diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsxindex a2603abda259..12b3dd40cd5f 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx@@ -51,7 +51,11 @@ import { ErrorBoundary } from "@posthog/ui/primitives/ErrorBoundary";import { useSidebarEdgeHoverPeek } from "@posthog/ui/primitives/hooks/useSidebarEdgeHoverPeek";import { ResizableSidebar } from "@posthog/ui/primitives/ResizableSidebar";import { navigateToArchived } from "@posthog/ui/router/navigationBridge";-import { useParams } from "@tanstack/react-router";+import {+ reportSourceHrefFromLocation,+ resolveNavigationSource,+} from "@posthog/ui/router/reportNavigation";+import { useParams, useRouterState } from "@tanstack/react-router";import { memo, useDeferredValue, useEffect, useRef } from "react";/**@@ -210,10 +214,17 @@ function ChannelsSidebarImpl() {// slide to there's only the list.const { pane: railPane, showsActivityDetail } = useRailSurface();const selectedActivityId = useActivitySelection()?.id;- const feedId = useParams({- strict: false,- select: (params) => params.feedId,+ const sourceFeedId = useRouterState({+ select: (state) =>+ resolveNavigationSource(+ reportSourceHrefFromLocation(state.resolvedLocation ?? state.location),+ )?.feedId ?? undefined,});+ const feedId =+ useParams({+ strict: false,+ select: (params) => params.feedId,+ }) ?? sourceFeedId;const pane = useChannelPaneStore((s) => s.pane);const { isPending: pendingTabSwitch, viewState: pendingTabViewState } =usePendingTabViewState();diff --git a/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsxindex c1cd3b948e09..2c455428cd23 100644--- a/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsx@@ -22,8 +22,19 @@ vi.mock("@tanstack/react-router", () => ({useRouterState: ({select,}: {- select: (s: { matches: { fullPath: string }[] }) => unknown;- }) => select({ matches: [{ fullPath: mocks.fullPath }] }),+ select: (s: {+ matches: { fullPath: string }[];+ location: { pathname: string; href: string; search: object };+ }) => unknown;+ }) =>+ select({+ matches: [{ fullPath: mocks.fullPath }],+ location: {+ pathname: mocks.fullPath,+ href: mocks.fullPath,+ search: {},+ },+ }),}));vi.mock("@posthog/ui/router/routerRef", () => ({getRouterOrNull: () => ({diff --git a/products/desktop/packages/ui/src/features/canvas/components/ShellLayout.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ShellLayout.test.tsxindex c0d63112b229..0575fa807bd5 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ShellLayout.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ShellLayout.test.tsx@@ -30,6 +30,7 @@ const {vi.mock("@tanstack/react-router", () => ({Outlet: () => null,useNavigate: () => vi.fn(),+ useSearch: () => ({}),useParams: (opts?: {select?: (p: Record<string, string | undefined>) => unknown;}) => {diff --git a/products/desktop/packages/ui/src/features/canvas/components/SpaceHeaderRow.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/SpaceHeaderRow.test.tsxindex 3d69c97d0ae8..ae69658aa827 100644--- a/products/desktop/packages/ui/src/features/canvas/components/SpaceHeaderRow.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/SpaceHeaderRow.test.tsx@@ -35,6 +35,7 @@ vi.mock("@tanstack/react-router", () => ({// The route's own pane, which is where the header's writer lives.Outlet: () => <ActivityDetailPane />,useNavigate: () => vi.fn(),+ useSearch: () => ({}),useParams: () => ({ channelId: "chan-1", taskId: "task-1" }),useRouterState: ({select,diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskFeedDetailPane.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedDetailPane.tsxindex 995114e60370..bb13cb5de8ce 100644--- a/products/desktop/packages/ui/src/features/canvas/components/TaskFeedDetailPane.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedDetailPane.tsx@@ -12,12 +12,22 @@ import { TaskDetail } from "@posthog/ui/features/task-detail/components/TaskDetaimport { useResolvedTask } from "@posthog/ui/features/tasks/useResolvedTask";import { TaskDetailSkeleton } from "@posthog/ui/router/routeSkeletons";-export function TaskFeedDetailPane({ feedId }: { feedId: string }) {+export function TaskFeedDetailPane({+ feedId,+ routeTaskId,+}: {+ feedId: string;+ /** The task named by the URL, when the location carries one. */+ routeTaskId?: string;+}) {const selected = useTaskFeedSelection(feedId);- const task = useResolvedTask(selected?.taskId);+ // The URL wins: a location that names a task shows it, even in a fresh tab+ // or after a reload where the in-memory selection is empty.+ const taskId = routeTaskId ?? selected?.taskId;+ const task = useResolvedTask(taskId);const { channels } = useChannels();- if (!selected) {+ if (!taskId) {return (<div className="flex h-full items-center justify-center"><Empty className="border-0">@@ -37,7 +47,7 @@ export function TaskFeedDetailPane({ feedId }: { feedId: string }) {if (!task) return <TaskDetailSkeleton />;- const channelId = task.channel ?? selected.channelId ?? undefined;+ const channelId = task.channel ?? selected?.channelId ?? undefined;const channelName = channels.find((c) => c.id === channelId)?.name;return (diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskFeedPane.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedPane.tsxindex 0b6980335922..f82f4209e86f 100644--- a/products/desktop/packages/ui/src/features/canvas/components/TaskFeedPane.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskFeedPane.tsx@@ -31,6 +31,7 @@ import {} from "@posthog/ui/features/canvas/stores/taskFeedSelectionStore";import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";import { toast } from "@posthog/ui/primitives/toast";+import { getRouterOrNull } from "@posthog/ui/router/routerRef";import { track } from "@posthog/ui/shell/analytics";import { useEffect, useMemo } from "react";@@ -68,12 +69,27 @@ export function TaskFeedPane({const actions = useMemo<ChannelItemActions>(() => ({- open: (item) =>+ open: (item) => {select({feedId,taskId: item.id,channelId: item.task?.channel ?? null,- }),+ });+ // Name the picked task in the URL, as Activity does, so a tab, a+ // reload or a report detour all return to the same task. On the feed+ // route itself this replaces the entry — a push per click would spam+ // history.+ const onFeedRoute =+ getRouterOrNull()?.state.location.pathname.startsWith(+ `/feeds/${feedId}`,+ );+ void getRouterOrNull()?.navigate({+ to: "/feeds/$feedId",+ params: { feedId },+ search: { task: item.id },+ replace: onFeedRoute,+ });+ },togglePin: (item) => {togglePin(item.id).catch(() => toast.error("Couldn't update pin"));},diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useRailSurface.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useRailSurface.tsindex 98854ed83ffc..b8bcc5b29007 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useRailSurface.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useRailSurface.ts@@ -2,8 +2,10 @@ import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsimport {type NavRailPane,railPaneForMatches,+ railPaneForPath,railPaneHasSidebar,} from "@posthog/ui/features/canvas/railPane";+import { reportSourceHrefFromLocation } from "@posthog/ui/router/reportNavigation";import { useRouterState } from "@tanstack/react-router";export interface RailSurface {@@ -15,7 +17,19 @@ export interface RailSurface {/** The rail destination the route names. A string, so the selector's result is* stable and unrelated route changes don't re-render every consumer. */export function useRailPane(): NavRailPane {- return useRouterState({ select: (s) => railPaneForMatches(s.matches) });+ return useRouterState({+ select: (state) => {+ // The settled location, not the in-flight one: during a pending+ // navigation `location` is already the destination while `matches` still+ // describe the page being left. Pairing the two unmounts the sidebar for+ // one painted frame (the yieldToPaint skeleton) and rebuilds it after.+ const location = state.resolvedLocation ?? state.location;+ const source = reportSourceHrefFromLocation(location);+ return source+ ? railPaneForPath(source.split(/[?#]/)[0])+ : railPaneForMatches(state.matches);+ },+ });}/** What the rail is putting on screen. The one answer, for all three surfacesdiff --git a/products/desktop/packages/ui/src/features/canvas/railPane.test.ts b/products/desktop/packages/ui/src/features/canvas/railPane.test.tsindex 000c3c0b8764..75989132cd52 100644--- a/products/desktop/packages/ui/src/features/canvas/railPane.test.ts+++ b/products/desktop/packages/ui/src/features/canvas/railPane.test.ts@@ -12,6 +12,7 @@ describe("railPaneForPath", () => {["/activity", "activity"],["/command-center", "command-center"],["/inbox", "inbox"],+ ["/reports/$reportId", "reports"],["/inbox/pulls/$reportId", "inbox"],["/loops", "loops"],["/loops/$loopId/edit", "loops"],@@ -76,7 +77,7 @@ describe("isRestorableVisitHref", () => {});describe("railPaneHasSidebar", () => {- it.each(["home", "inbox", "command-center", "loops"] as const)(+ it.each(["home", "inbox", "reports", "command-center", "loops"] as const)("gives %s the whole screen",(pane) => {expect(railPaneHasSidebar(pane)).toBe(false);diff --git a/products/desktop/packages/ui/src/features/canvas/railPane.ts b/products/desktop/packages/ui/src/features/canvas/railPane.tsindex 151cdc9260ad..82be31d3d786 100644--- a/products/desktop/packages/ui/src/features/canvas/railPane.ts+++ b/products/desktop/packages/ui/src/features/canvas/railPane.ts@@ -10,6 +10,7 @@ import { getCurrentMatches } from "@posthog/ui/router/navigationBridge";*/export type NavRailPane =| "home"+ | "reports"| "spaces"| "activity"| "canvases"@@ -28,6 +29,7 @@ export type NavRailPane =*/export const RAIL_PANE_ROOT: Readonly<Record<NavRailPane, string>> = {home: "/",+ reports: "/reports",spaces: "/spaces",activity: "/activity",canvases: "/canvases",@@ -42,6 +44,7 @@ export const RAIL_PANE_ROOT: Readonly<Record<NavRailPane, string>> = {// would only shadow that fallback with the same answer.const CLAIMED: readonly NavRailPane[] = ["home",+ "reports","activity","canvases","inbox",diff --git a/products/desktop/packages/ui/src/features/inbox/AGENTS.md b/products/desktop/packages/ui/src/features/inbox/AGENTS.mdindex 35cd10644da1..896fb3c8e483 100644--- a/products/desktop/packages/ui/src/features/inbox/AGENTS.md+++ b/products/desktop/packages/ui/src/features/inbox/AGENTS.md@@ -24,7 +24,22 @@ Inbox has four tabs and one reviewer-scope control:| Runs | `/inbox/runs` | Reports that are still in progress or waiting on input || Archive | `/inbox/dismissed` | Terminal reports: archived/suppressed (`status === "suppressed"`) and resolved-by-merged-PR (`status === "resolved"`) |-Detail pages live under the same tab: `/inbox/<tab>/$reportId`.+Reports have one canonical detail route: `/reports/$reportId`. The old+`/inbox/{reports,pulls,dismissed}/$reportId` and space-report URLs replace-redirect+there. Runs remain at `/inbox/runs/$reportId`.++`ReportPage` renders the shared report, PR, or archived content based on current+status without changing the URL. In-app links carry the source in a validated+`?from=` search param, so it survives a reload, a new tab and a window restore:+the source rail/sidebar remains selected, and the report header breadcrumb links+to that source. `resolveNavigationSource` in `router/reportNavigation.ts` is the+only place that reads a source path; ask it for the label, space or feed rather+than matching the href again. A report with no source reads as+`Self-driving / <space>` and never renders inside another page's chrome.+The header identifies the object and links to its owning space rather than+treating ownership as a back destination. Report opening must not reset Inbox+filters. Restore updates the canonical page in place. Existing embedded Activity+previews remain supported.The Archive tab (route `/inbox/dismissed`, user-facing label "Archive") isthe exception: it holds the two terminal, not-in-inbox states — `suppressed`diff --git a/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsxindex 281f9cf2263f..f580b1857618 100644--- a/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/AgentRunDetail.tsx@@ -53,6 +53,10 @@ import {import { copyInboxReportLink } from "@posthog/ui/features/inbox/utils/copyInboxReportLink";import { TaskLogsPanel } from "@posthog/ui/features/task-detail/components/TaskLogsPanel";import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";+import {+ navigationSourceHref,+ reportNavigationState,+} from "@posthog/ui/router/reportNavigation";import { openTask } from "@posthog/ui/router/useOpenTask";import { DropdownMenu, Flex, Text } from "@radix-ui/themes";import { Link } from "@tanstack/react-router";@@ -139,38 +143,40 @@ function RunOutputReadyCard({ report }: { report: SignalReport }) {const prRef = prUrl ? parsePrUrl(prUrl) : null;const sourceMeta = getSourceProductMeta(report.source_products?.[0]);const headline = deriveHeadline(report.summary);+ // This card renders only on /inbox/runs/$reportId, which a source href must+ // not be (it would make the report's breadcrumb point at another report).+ // The run's own tab is the list the reader came from.+ const source = navigationSourceHref() ?? "/inbox/runs";return (<Link- to={isPr ? "/inbox/pulls/$reportId" : "/inbox/reports/$reportId"}+ to="/reports/$reportId"+ state={reportNavigationState}+ search={{ from: source }}params={{ reportId: report.id }}className="group block rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5 no-underline transition duration-150 hover:border-(--gray-6) hover:bg-(--gray-2) hover:shadow-sm focus-visible:outline-none">- <Flex direction="column" gap="2">- <Flex align="center" gap="2" wrap="wrap">- <Flex- align="center"- justify="center"- className="h-5 w-5 shrink-0 rounded-full bg-(--green-2) ring-(--green-5) ring-1 ring-inset"- >+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-(--green-2) ring-(--green-5) ring-1 ring-inset">{isPr ? (<GitPullRequestIcon size={11} className="text-(--green-11)" />) : (<FileTextIcon size={11} className="text-(--green-11)" />)}- </Flex>+ </div>{prRef ? (- <Text className="font-mono text-[12.5px] text-gray-12">+ <span className="font-mono text-[12.5px] text-gray-12">{prRef.repoSlug}#{prRef.number}- </Text>+ </span>) : (- <Text className="font-medium text-[13px] text-gray-12">Report</Text>+ <span className="font-medium text-[13px] text-gray-12">Report</span>)}<span className="flex-1" />{prUrl ? (<PrDiffStats prUrl={prUrl} hideWhileLoading />) : sourceMeta ? (- <Flex align="center" gap="1.5" className="text-[12px] text-gray-11">+ <div className="flex items-center gap-1.5 text-[12px] text-gray-11"><spanclassName="inline-flex shrink-0 items-center"style={{ color: sourceMeta.color }}@@ -179,22 +185,22 @@ function RunOutputReadyCard({ report }: { report: SignalReport }) {<sourceMeta.Icon size={12} /></span><span>{sourceMeta.label}</span>- </Flex>+ </div>) : null}- </Flex>+ </div>{(report.title || headline) && (- <Text className="line-clamp-2 text-[12.5px] text-gray-11 leading-snug">+ <span className="line-clamp-2 text-[12.5px] text-gray-11 leading-snug">{report.title || headline}- </Text>+ </span>)}- <Flex align="center" gap="1" className="text-[12px] text-gray-10">+ <div className="flex items-center gap-1 text-[12px] text-gray-10"><span>{isPr ? "Open the pull request" : "Open the report"}</span><ArrowRightIconsize={12}className="transition-transform group-hover:translate-x-0.5"/>- </Flex>- </Flex>+ </div>+ </div></Link>);}diff --git a/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx b/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsxindex f7bc070dc85f..8398309e4934 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx@@ -48,6 +48,7 @@ import {import { useCreateTask } from "@posthog/ui/features/tasks/useTaskCrudMutations";import { Badge } from "@posthog/ui/primitives/Badge";import { toast } from "@posthog/ui/primitives/toast";+import { settingsSourceHref } from "@posthog/ui/router/reportNavigation";import { openTask } from "@posthog/ui/router/useOpenTask";import { track } from "@posthog/ui/shell/analytics";import { logger } from "@posthog/ui/shell/logger";@@ -199,6 +200,7 @@ export function ConfigureAgentsSection() {<Linkto="/settings/$category"params={{ category: "mcp-servers" }}+ search={{ from: settingsSourceHref() }}onClick={() =>track(ANALYTICS_EVENTS.AGENTS_ACTION, {action_type: "open_mcp_servers",diff --git a/products/desktop/packages/ui/src/features/inbox/components/DetailBackLink.test.tsx b/products/desktop/packages/ui/src/features/inbox/components/DetailBackLink.test.tsxnew file mode 100644index 000000000000..973f69f130ca--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/components/DetailBackLink.test.tsx@@ -0,0 +1,108 @@+import type { SignalReport } from "@posthog/shared/types";+import { ReportPageContext } from "@posthog/ui/features/inbox/components/ReportPageContext";+import { render } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ sourceHref: undefined as string | undefined,+ triageOrigin: null as { reportId: string } | null,+ locationState: {} as Record<string, unknown>,+}));++vi.mock("@tanstack/react-router", () => ({+ useLocation: ({ select }: { select: (location: unknown) => unknown }) =>+ select({ state: mocks.locationState }),+ Link: ({+ to,+ state,+ }: {+ to: string;+ state?: ((previous: unknown) => unknown) | undefined;+ }) => (+ <a+ href={to}+ data-state={state ? JSON.stringify(state(mocks.locationState)) : ""}+ >+ {to}+ </a>+ ),+ useRouterState: ({ select }: { select: (state: unknown) => unknown }) =>+ select({+ location: {+ pathname: "/reports/report-1",+ href: "/reports/report-1",+ search: { from: mocks.sourceHref },+ state: mocks.locationState,+ },+ }),+}));++vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({+ useChannels: () => ({ channels: [] }),+}));++import { DetailBackLink } from "./DetailBackLink";++const report = {+ id: "report-1",+ title: "Billing report",+ status: "ready",+} as SignalReport;++describe("DetailBackLink", () => {+ beforeEach(() => {+ mocks.sourceHref = "/inbox/reports";+ mocks.triageOrigin = null;+ mocks.locationState = { inboxTriageOrigin: { reportId: "report-1" } };+ });++ const renderCrumbs = () => {+ const { container } = render(+ <ReportPageContext value={report}>+ <DetailBackLink to="/inbox/reports" label="Self-driving" />+ </ReportPageContext>,+ );+ return container.querySelectorAll("a");+ };++ it("carries the triage origin on the Reports-list crumb", () => {+ mocks.triageOrigin = { reportId: "report-1" };+ const crumb = renderCrumbs()[0];+ expect(crumb?.getAttribute("href")).toBe("/inbox/reports");+ expect(JSON.parse(crumb?.getAttribute("data-state") ?? "{}")).toEqual({+ inboxTriageOrigin: { reportId: "report-1" },+ });+ });++ it("keeps other history state on the triage crumb", () => {+ mocks.triageOrigin = { reportId: "report-1" };+ mocks.locationState = {+ tabId: "tab-1",+ inboxTriageOrigin: { reportId: "report-1" },+ };+ const crumb = renderCrumbs()[0];+ expect(JSON.parse(crumb?.getAttribute("data-state") ?? "{}")).toEqual({+ tabId: "tab-1",+ inboxTriageOrigin: { reportId: "report-1" },+ });+ });++ it("leaves the crumb stateless outside triage", () => {+ mocks.locationState = {};+ const crumb = renderCrumbs()[0];+ expect(crumb?.getAttribute("data-state")).toBe("");+ });++ it("passes no state updater for a settings source", () => {+ mocks.sourceHref = "/settings/agents?agent=scout-1";+ // Category crumb, then agent crumb, both stateless.+ const crumbs = renderCrumbs();+ expect(crumbs).toHaveLength(2);+ for (const crumb of crumbs)+ expect(crumb?.getAttribute("data-state")).toBe("");+ // The agent crumb links to the full settings href, agent included.+ expect(crumbs[1]?.getAttribute("href")).toBe(+ "/settings/agents?agent=scout-1",+ );+ });+});diff --git a/products/desktop/packages/ui/src/features/inbox/components/DetailBackLink.tsx b/products/desktop/packages/ui/src/features/inbox/components/DetailBackLink.tsxindex eca80833e2e1..f66784916786 100644--- a/products/desktop/packages/ui/src/features/inbox/components/DetailBackLink.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/DetailBackLink.tsx@@ -1,14 +1,73 @@import { ArrowLeftIcon } from "@phosphor-icons/react";-import { useInboxTriageOrigin } from "@posthog/ui/features/inbox/hooks/useInboxBackTarget";+import { humanizeReportTitle } from "@posthog/core/inbox/reportPresentation";+import {+ prettifyScoutSkillName,+ scoutSkillNameFromSlug,+} from "@posthog/core/scouts/scoutPresentation";+import type { SignalReport } from "@posthog/shared/types";+import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";+import { useReportPage } from "@posthog/ui/features/inbox/components/ReportPageContext";+import {+ type InboxTriageOrigin,+ useInboxTriageOrigin,+} from "@posthog/ui/features/inbox/hooks/useInboxBackTarget";+import {+ BreadcrumbSegment,+ BreadcrumbSeparator,+} from "@posthog/ui/primitives/Breadcrumb";+import {+ type NavigationSource,+ resolveNavigationSource,+ useReportSourceHref,+} from "@posthog/ui/router/reportNavigation";import { Link } from "@tanstack/react-router";+import type { ReactElement } from "react";interface DetailBackLinkProps {to: string;label: string;}+interface Crumb {+ label: string;+ render?: ReactElement;+}+export function DetailBackLink({ to, label }: DetailBackLinkProps) {const triageOrigin = useInboxTriageOrigin();+ const report = useReportPage();+ const sourceHref = useReportSourceHref();+ const { channels } = useChannels({ enabled: report !== null });++ if (report) {+ const spaceName = (id: string) => channels.find((c) => c.id === id)?.name;+ const crumbs = reportCrumbs(+ resolveNavigationSource(sourceHref),+ report,+ triageOrigin,+ spaceName,+ );+ return (+ <div className="flex min-w-0 items-center gap-0.5">+ {crumbs.map((crumb, index) => (+ <div+ key={`${index}-${crumb.label}`}+ className="flex min-w-0 items-center gap-0.5"+ >+ {index > 0 && <BreadcrumbSeparator />}+ <BreadcrumbSegment+ label={crumb.label}+ strong={index === 0}+ muted={index === crumbs.length - 1}+ shrink={index === crumbs.length - 1}+ render={crumb.render}+ />+ </div>+ ))}+ </div>+ );+ }+const returnsToTriage = to === "/inbox/reports" && triageOrigin !== null;return (@@ -29,3 +88,81 @@ export function DetailBackLink({ to, label }: DetailBackLinkProps) {</Link>);}++function reportCrumbs(+ source: NavigationSource | null,+ report: SignalReport,+ triageOrigin: InboxTriageOrigin | null,+ spaceName: (id: string) => string | undefined,+): Crumb[] {+ const crumbs: Crumb[] = [];+ // TanStack blanks history state on a plain Link, so the Reports-list crumb+ // must carry the triage origin forward or triage focus mode dies on the way+ // back.+ const exact = source ? (+ <Link+ to={source.href}+ state={+ source.path === "/inbox/reports" && triageOrigin+ ? (previous) => ({ ...previous, inboxTriageOrigin: triageOrigin })+ : undefined+ }+ />+ ) : undefined;++ if (source?.settingsCategory) {+ crumbs.push({+ label: source.label,+ render: source.agentSlug ? (+ <Link+ to="/settings/$category"+ params={{ category: source.settingsCategory }}+ />+ ) : (+ exact+ ),+ });+ if (source.agentSlug) {+ crumbs.push({+ label: prettifyScoutSkillName(scoutSkillNameFromSlug(source.agentSlug)),+ render: exact,+ });+ }+ } else if (source?.spaceId) {+ const name = spaceName(source.spaceId);+ crumbs.push({ label: name ? `#${name}` : source.label, render: exact });+ } else if (source) {+ crumbs.push({ label: source.label, render: exact });+ } else {+ crumbs.push({+ label: "Self-driving",+ render: (+ <Link+ to="/inbox/reports"+ state={+ triageOrigin+ ? (previous) => ({ ...previous, inboxTriageOrigin: triageOrigin })+ : undefined+ }+ />+ ),+ });+ }++ const ownSpace =+ report.channel_id && report.channel_id !== source?.spaceId+ ? report.channel_id+ : null;+ const ownSpaceName = ownSpace ? spaceName(ownSpace) : undefined;+ if (ownSpace && ownSpaceName) {+ crumbs.push({+ label: `#${ownSpaceName}`,+ render: <Link to="/spaces/$channelId" params={{ channelId: ownSpace }} />,+ });+ }++ crumbs.push({+ label: humanizeReportTitle(report.title, "Untitled report"),+ });+ return crumbs;+}diff --git a/products/desktop/packages/ui/src/features/inbox/components/DismissedReportDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/DismissedReportDetail.tsxindex 240508b36e59..68a366d2ad10 100644--- a/products/desktop/packages/ui/src/features/inbox/components/DismissedReportDetail.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/DismissedReportDetail.tsx@@ -9,6 +9,7 @@ import type { SignalReport } from "@posthog/shared/types";import { InboxDetailFrame } from "@posthog/ui/features/inbox/components/InboxDetailFrame";import { InboxReportCopyLinkMenu } from "@posthog/ui/features/inbox/components/InboxReportCopyLinkMenu";import { InboxReportDetailGate } from "@posthog/ui/features/inbox/components/InboxReportDetailGate";+import { useReportPage } from "@posthog/ui/features/inbox/components/ReportPageContext";import {type InboxBackTarget,useInboxBackTarget,@@ -62,7 +63,7 @@ export function DismissedReportDetail({);}-function DismissedReportDetailContent({+export function DismissedReportDetailContent({report,back,}: {@@ -107,6 +108,7 @@ function DismissedReportDetailContent({function RestoreReportButton({ report }: { report: SignalReport }) {const restore = useInboxRestoreReport();const navigate = useNavigate();+ const reportPage = useReportPage();return (<Button@@ -118,7 +120,9 @@ function RestoreReportButton({ report }: { report: SignalReport }) {title="Restore this report to Self-driving"onClick={() =>restore.mutate(report.id, {- onSuccess: () => navigate({ to: "/inbox/dismissed" }),+ onSuccess: () => {+ if (!reportPage) void navigate({ to: "/inbox/dismissed" });+ },})}>diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsxindex ccd06eb8c3c3..25b9e47aedbb 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsx@@ -21,6 +21,7 @@ import {PageHeaderTitle,PageHeaderTitleRow,} from "@posthog/ui/primitives/PageHeader";+import { settingsSourceHref } from "@posthog/ui/router/reportNavigation";import { Link, useRouterState } from "@tanstack/react-router";interface InboxPageHeaderProps {@@ -37,7 +38,13 @@ function ConfigureAgentsButton() {<Buttonvariant="primary"size="sm"- render={<Link to="/settings/$category" params={{ category: "agents" }} />}+ render={+ <Link+ to="/settings/$category"+ params={{ category: "agents" }}+ search={{ from: settingsSourceHref() }}+ />+ }className="shrink-0"><RobotIcon size={14} />diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxReportDetailGate.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxReportDetailGate.tsxindex f8a90120bbf9..78dbd4c5051d 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxReportDetailGate.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxReportDetailGate.tsx@@ -17,7 +17,6 @@ import {useReportOpenTracker,} from "@posthog/ui/features/inbox/hooks/useReportOpenTracker";import { LoadingState } from "@posthog/ui/primitives/LoadingState";-import { Flex, Text } from "@radix-ui/themes";import { useNavigate } from "@tanstack/react-router";import { type ReactNode, useEffect } from "react";@@ -32,6 +31,7 @@ interface InboxReportDetailGateProps {* URL and so never needs the inbox's status↔route redirect.*/statusRedirect?: boolean;+ requireFreshStatus?: boolean;/*** Where the missing-report shell's back link points, when it should differ* from `backTo`. The Archive detail sets these to the recorded origin so the@@ -41,6 +41,12 @@ interface InboxReportDetailGateProps {*/backLinkTo?: string;backLinkLabel?: string;+ /**+ * Which inbox tab's list the open/close engagement events measure against.+ * Defaults to the tab derived from `backTo`; `null` skips tracking (the+ * Archive tab: its rank would be measured against the wrong list).+ */+ trackTab?: InboxDetailTab | null;missingCopy: string;children: (report: SignalReport) => ReactNode;}@@ -75,8 +81,10 @@ export function InboxReportDetailGate({backTo,backLabel,statusRedirect = true,+ requireFreshStatus = false,backLinkTo,backLinkLabel,+ trackTab = tabFromBackTo(backTo),missingCopy,children,}: InboxReportDetailGateProps) {@@ -123,7 +131,9 @@ export function InboxReportDetailGate({// fetch settles. Routes without status redirects and the Archive route render// from cache: neither can expose actions for the wrong status route.const statusUnconfirmed =- statusRedirect && !onDismissedRoute && isFetching && !isFetchedAfterMount;+ (requireFreshStatus || (statusRedirect && !onDismissedRoute)) &&+ isFetching &&+ !isFetchedAfterMount;const redirectReportId = resolvedReport?.id;useEffect(() => {if (!redirectTo || !redirectReportId) return;@@ -163,23 +173,18 @@ export function InboxReportDetailGate({if (!resolvedReport) {return (- <Flex direction="column" className="h-full min-h-0">- <Flex- direction="column"- gap="3"- className="border-(--gray-5) border-b px-6 py-6"- >+ <div className="flex h-full min-h-0 flex-col">+ <div className="flex flex-col gap-3 border-(--gray-5) border-b px-6 py-6"><DetailBackLinkto={backLinkTo ?? backTo}label={backLinkLabel ?? backLabel}/>- <Text className="text-[13px] text-gray-11">{missingCopy}</Text>- </Flex>- </Flex>+ <p className="m-0 text-[13px] text-gray-11">{missingCopy}</p>+ </div>+ </div>);}- const trackTab = tabFromBackTo(backTo);return (<>{trackTab && <ReportOpenTracker report={resolvedReport} tab={trackTab} />}@@ -206,7 +211,7 @@ function tabFromBackTo(* Mounts only once a report is resolved, so the OPENED/CLOSED engagement events* bracket the time the detail body is actually on screen. Renders nothing.*/-function ReportOpenTracker({+export function ReportOpenTracker({report,tab,}: {diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxReportRow.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxReportRow.tsxindex a2a514264ccf..7c1225611483 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxReportRow.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxReportRow.tsx@@ -13,7 +13,7 @@ export function InboxReportRow({report: SignalReport;}): React.JSX.Element {const { pointerHandlers } = useInboxReportDetailPrefetch({- to: "/inbox/reports/$reportId",+ to: "/reports/$reportId",params: { reportId: report.id },});diff --git a/products/desktop/packages/ui/src/features/inbox/components/PullRequestCard.tsx b/products/desktop/packages/ui/src/features/inbox/components/PullRequestCard.tsxindex a8aa7349f6e2..16649da8471e 100644--- a/products/desktop/packages/ui/src/features/inbox/components/PullRequestCard.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/PullRequestCard.tsx@@ -28,6 +28,10 @@ import { ReportImplementationPrLink } from "@posthog/ui/features/inbox/componentimport { useInboxReportDetailPrefetch } from "@posthog/ui/features/inbox/hooks/useInboxReportDetailPrefetch";import { useInboxReportArtefacts } from "@posthog/ui/features/inbox/hooks/useInboxReports";import { Button as UiButton } from "@posthog/ui/primitives/Button";+import {+ navigationSourceHref,+ reportNavigationState,+} from "@posthog/ui/router/reportNavigation";import { Link, useNavigate } from "@tanstack/react-router";import type { HTMLAttributes, MouseEvent, ReactNode } from "react";@@ -179,9 +183,11 @@ export function PullRequestCard({dismissDisabledReason = null,isDismissPending = false,}: PullRequestCardProps) {+ const source = navigationSourceHref();const detailRoute = {- to: "/inbox/pulls/$reportId" as const,+ to: "/reports/$reportId" as const,params: { reportId: report.id },+ search: source ? { from: source } : {},};const { prefetch, pointerHandlers } =useInboxReportDetailPrefetch(detailRoute);@@ -213,6 +219,7 @@ export function PullRequestCard({renderBody={(body, className) => (<Link{...detailRoute}+ state={reportNavigationState}preload="intent"onClick={(event) => {onRowClick?.(event);diff --git a/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsxindex a218970ba3b8..775acbcae6a2 100644--- a/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsx@@ -42,7 +42,7 @@ export function PullRequestDetail({* they're pipeline machinery, and the decision block distills what matters* from them into one line.*/-function PullRequestDetailContent({ report }: { report: SignalReport }) {+export function PullRequestDetailContent({ report }: { report: SignalReport }) {const prRef = report.implementation_pr_url? parsePrUrl(report.implementation_pr_url): null;@@ -54,16 +54,6 @@ function PullRequestDetailContent({ report }: { report: SignalReport }) {backTo="/inbox/pulls"backLabel="Back to pull requests"fallbackTitle="Untitled pull request"- breadcrumb={- prRef ? (- <>- <span className="text-(--gray-8)">/</span>- <span className="font-mono text-[13px] text-gray-11">- {prRef.repoSlug}#{prRef.number}- </span>- </>- ) : undefined- }metaSuffix={prUrl ? (<>diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportCard.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportCard.tsxindex e4da2046687c..d4c5cee561ce 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportCard.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportCard.tsx@@ -36,6 +36,10 @@ import { hasKnownSourceProduct } from "@posthog/ui/features/inbox/components/utiimport { useInboxReportDetailPrefetch } from "@posthog/ui/features/inbox/hooks/useInboxReportDetailPrefetch";import { useInboxReportArtefacts } from "@posthog/ui/features/inbox/hooks/useInboxReports";import { Button as UiButton } from "@posthog/ui/primitives/Button";+import {+ navigationSourceHref,+ reportNavigationState,+} from "@posthog/ui/router/reportNavigation";import { Link, useNavigate } from "@tanstack/react-router";import type { HTMLAttributes, MouseEvent, ReactNode } from "react";@@ -324,15 +328,12 @@ export function ReportCard(props: ReportCardProps) {const { report, isSelected = false, onRowClick } = props;const isArchived = props.variant === "archived";- const detailRoute = isArchived- ? {- to: "/inbox/dismissed/$reportId" as const,- params: { reportId: report.id },- }- : {- to: "/inbox/reports/$reportId" as const,- params: { reportId: report.id },- };+ const source = navigationSourceHref();+ const detailRoute = {+ to: "/reports/$reportId" as const,+ params: { reportId: report.id },+ search: source ? { from: source } : {},+ };const { prefetch, pointerHandlers } =useInboxReportDetailPrefetch(detailRoute);const navigate = useNavigate();@@ -350,6 +351,7 @@ export function ReportCard(props: ReportCardProps) {const renderBody = (body: ReactNode, className: string) => (<Link{...detailRoute}+ state={reportNavigationState}preload="intent"onClick={(event) => {onRowClick?.(event);diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsxindex 3a3e3fdccbc7..bd86a220249f 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx@@ -63,7 +63,7 @@ export function ReportDetail({* it: reading and asking share one screen, and highlighting a passage quotes* it into the chat.*/-function ReportDetailContent({+export function ReportDetailContent({report,backTo,backLabel,diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportPage.test.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportPage.test.tsxnew file mode 100644index 000000000000..b4acadbfed49--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportPage.test.tsx@@ -0,0 +1,158 @@+import type { SignalReport } from "@posthog/shared/types";+import { render, screen, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ report: { id: "report-1", status: "ready" } as SignalReport,+ source: undefined as string | undefined,+ gate: vi.fn(),+ tracker: vi.fn(() => null),+}));++vi.mock("@tanstack/react-router", () => ({+ useRouterState: ({ select }: { select: (state: unknown) => unknown }) =>+ select({+ location: {+ pathname: "/reports/report-1",+ href: "/reports/report-1",+ search: { from: mocks.source },+ },+ }),+}));++vi.mock("@posthog/ui/features/inbox/components/InboxReportDetailGate", () => ({+ InboxReportDetailGate: (props: {+ children: (report: SignalReport) => ReactNode;+ }) => {+ mocks.gate(props);+ return props.children(mocks.report);+ },+ ReportOpenTracker: mocks.tracker,+}));++vi.mock("@posthog/ui/features/settings/components/SettingsLayout", () => ({+ SettingsLayout: ({+ category,+ childBackHref,+ children,+ }: {+ category: string;+ childBackHref?: string;+ children: ReactNode;+ }) => (+ <section+ aria-label={`Settings ${category}`}+ data-child-back-href={childBackHref}+ >+ {children}+ </section>+ ),+}));++vi.mock("@posthog/ui/features/inbox/components/ReportDetail", () => ({+ ReportDetailContent: () => <div>Report content</div>,+}));++vi.mock("@posthog/ui/features/inbox/components/PullRequestDetail", () => ({+ PullRequestDetailContent: () => <div>PR content</div>,+}));++vi.mock("@posthog/ui/features/inbox/components/DismissedReportDetail", () => ({+ DismissedReportDetailContent: () => <div>Archived content</div>,+}));++import { ReportPage } from "./ReportPage";++describe("ReportPage", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.source = undefined;+ mocks.report = { id: "report-1", status: "ready" } as SignalReport;+ });++ it.each([+ ["/settings/agents", "Settings agents"],+ ["/settings/agents?agent=account-mrr", "Settings agents"],+ ["/spaces/space-1", null],+ [undefined, null],+ ])("renders a report from %s inside %s", async (source, region) => {+ mocks.source = source;+ render(<ReportPage reportId="report-1" cachedReport={null} />);+ // The settings portal is a lazy chunk; the report body draws first.+ await waitFor(() =>+ expect(screen.getByText("Report content")).toBeInTheDocument(),+ );+ if (region) {+ expect(+ await screen.findByRole("region", { name: region }),+ ).toBeInTheDocument();+ } else {+ expect(screen.queryByRole("region")).not.toBeInTheDocument();+ }+ });++ it.each([+ ["/settings/agents", "/settings/agents", "Agents"],+ ["/spaces/space-1", "/spaces/space-1", "Spaces"],+ [undefined, "/inbox/reports", "Self-driving"],+ ])(+ "points the missing-report link at the origin %s",+ (source, backLinkTo, backLabel) => {+ mocks.source = source;+ render(<ReportPage reportId="report-1" cachedReport={null} />);+ expect(screen.getByText("Report content")).toBeInTheDocument();+ expect(mocks.gate).toHaveBeenCalledWith(+ expect.objectContaining({ backLinkTo, backLabel, backTo: "/" }),+ );+ },+ );++ it.each(["suppressed", "resolved"] as const)(+ "renders %s reports read-only even with a PR",+ (status) => {+ mocks.report = {+ ...mocks.report,+ status,+ implementation_pr_url: "https://github.com/example/repo/pull/1",+ };+ render(<ReportPage reportId="report-1" cachedReport={null} />);+ expect(screen.getByText("Archived content")).toBeInTheDocument();+ expect(screen.queryByText("PR content")).not.toBeInTheDocument();+ expect(mocks.tracker).not.toHaveBeenCalled();+ },+ );++ it("sends the settings Back button to the full source href", async () => {+ mocks.source = "/settings/agents?agent=account-mrr&agentTab=output";+ render(<ReportPage reportId="report-1" cachedReport={null} />);+ const region = await screen.findByRole("region", {+ name: "Settings agents",+ });+ expect(region.getAttribute("data-child-back-href")).toBe(+ "/settings/agents?agent=account-mrr&agentTab=output",+ );+ });++ it("changes content in place as a report gains a PR, archives, and restores", () => {+ mocks.source = "/settings/agents";+ const { rerender } = render(+ <ReportPage reportId="report-1" cachedReport={null} />,+ );+ expect(screen.getByText("Report content")).toBeInTheDocument();+ mocks.report = {+ ...mocks.report,+ implementation_pr_url: "https://github.com/example/repo/pull/1",+ };+ rerender(<ReportPage reportId="report-1" cachedReport={null} />);+ expect(screen.getByText("PR content")).toBeInTheDocument();+ mocks.report = { ...mocks.report, status: "suppressed" };+ rerender(<ReportPage reportId="report-1" cachedReport={null} />);+ expect(screen.getByText("Archived content")).toBeInTheDocument();+ mocks.report = { ...mocks.report, status: "ready" };+ rerender(<ReportPage reportId="report-1" cachedReport={null} />);+ expect(screen.getByText("PR content")).toBeInTheDocument();+ for (const [props] of mocks.gate.mock.calls)+ expect(props.statusRedirect).toBe(false);+ });+});diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportPage.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportPage.tsxnew file mode 100644index 000000000000..aa3a16b0a1dd--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportPage.tsx@@ -0,0 +1,86 @@+import { isDismissedReport } from "@posthog/core/inbox/reportMembership";+import type { SignalReport } from "@posthog/shared/types";+import { DismissedReportDetailContent } from "@posthog/ui/features/inbox/components/DismissedReportDetail";+import {+ InboxReportDetailGate,+ ReportOpenTracker,+} from "@posthog/ui/features/inbox/components/InboxReportDetailGate";+import { PullRequestDetailContent } from "@posthog/ui/features/inbox/components/PullRequestDetail";+import { ReportDetailContent } from "@posthog/ui/features/inbox/components/ReportDetail";+import { ReportPageContext } from "@posthog/ui/features/inbox/components/ReportPageContext";+import { LoadingState } from "@posthog/ui/primitives/LoadingState";+import {+ resolveNavigationSource,+ useReportSourceHref,+} from "@posthog/ui/router/reportNavigation";+import { lazy, Suspense } from "react";++// The settings portal statically reaches every settings screen through+// SettingsPanel. A report read outside settings never mounts it, so keep that+// ~300-module tree out of the report route's chunk.+const SettingsLayout = lazy(() =>+ import("@posthog/ui/features/settings/components/SettingsLayout").then(+ (m) => ({ default: m.SettingsLayout }),+ ),+);++export function ReportPage({+ reportId,+ cachedReport,+}: {+ reportId: string;+ cachedReport: SignalReport | null;+}) {+ const source = resolveNavigationSource(useReportSourceHref());+ const content = (+ <div className="h-full min-h-0 w-full overflow-auto">+ <InboxReportDetailGate+ reportId={reportId}+ cachedReport={cachedReport}+ backTo="/"+ backLinkTo={source?.href ?? "/inbox/reports"}+ backLabel={source?.label ?? "Self-driving"}+ statusRedirect={false}+ requireFreshStatus+ trackTab={null}+ missingCopy="This report couldn't be found or you don't have access to it."+ >+ {(report) => <ReportPageContent report={report} />}+ </InboxReportDetailGate>+ </div>+ );+ return source?.settingsCategory ? (+ <Suspense fallback={<LoadingState />}>+ <SettingsLayout+ category={source.settingsCategory}+ childBackHref={source.href}+ >+ {content}+ </SettingsLayout>+ </Suspense>+ ) : (+ content+ );+}++function ReportPageContent({ report }: { report: SignalReport }) {+ const archived = isDismissedReport(report);+ const hasPr = Boolean(report.implementation_pr_url);+ return (+ <ReportPageContext value={report}>+ {!archived && (+ <ReportOpenTracker report={report} tab={hasPr ? "pulls" : "reports"} />+ )}+ {archived ? (+ <DismissedReportDetailContent+ report={report}+ back={{ to: "/inbox/dismissed", label: "Report" }}+ />+ ) : hasPr ? (+ <PullRequestDetailContent report={report} />+ ) : (+ <ReportDetailContent report={report} backTo="/" backLabel="Report" />+ )}+ </ReportPageContext>+ );+}diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportPageContext.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportPageContext.tsxnew file mode 100644index 000000000000..2bea07c7d126--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportPageContext.tsx@@ -0,0 +1,8 @@+import type { SignalReport } from "@posthog/shared/types";+import { createContext, useContext } from "react";++export const ReportPageContext = createContext<SignalReport | null>(null);++export function useReportPage() {+ return useContext(ReportPageContext);+}diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.tsxindex 88a95caceaee..f1f540ba3923 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportTriageFocus.tsx@@ -161,7 +161,7 @@ export function ReportTriageFocus({const { prefetch } = useInboxReportDetailPrefetch(report? {- to: "/inbox/reports/$reportId",+ to: "/reports/$reportId",params: { reportId: report.id },}: null,diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxDeepLink.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxDeepLink.tsindex 1e1a75a76333..c2914715db65 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxDeepLink.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxDeepLink.ts@@ -30,7 +30,7 @@ export function useInboxDeepLink() {const open = useCallback((reportId: string | null): void => {if (reportId) {- void openReport(reportId);+ void openReport(reportId, { preserveSource: false });} else {navigateToInbox();}diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReportDetailPrefetch.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReportDetailPrefetch.tsindex 2deb2478b219..279ff3c2c7c2 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReportDetailPrefetch.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReportDetailPrefetch.ts@@ -9,6 +9,10 @@ import { useRouter } from "@tanstack/react-router";import { useCallback, useMemo } from "react";export type InboxDetailRoute =+ | {+ to: "/reports/$reportId";+ params: { reportId: string };+ }| {to: "/inbox/pulls/$reportId";params: { reportId: string };diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.tsindex c5a00be78c05..e4dc4a5f9726 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.ts@@ -1,43 +1,22 @@import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";-import { useTaskChannels } from "@posthog/ui/features/canvas/hooks/useTaskChannels";-import { useChannelReportsEnabled } from "@posthog/ui/features/feature-flags/useChannelReportsEnabled";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 {- navigateToChannelReportDetail,- navigateToInboxDismissedDetail,- navigateToInboxPullRequestDetail,- navigateToInboxReportDetail,-} from "@posthog/ui/router/navigationBridge";+import { navigateToReport } from "@posthog/ui/router/navigationBridge";+import { getRouterOrNull } from "@posthog/ui/router/routerRef";import { logger } from "@posthog/ui/shell/logger";import { useQueryClient } from "@tanstack/react-query";import { useCallback } from "react";const log = logger.scope("open-inbox-report");-/**- * Returns a callback that opens an inbox report by id: fetch it directly- * (bypassing the paginated list), reset inbox-local- * filters so it isn't hidden, then navigate to the right tab – Archive when- * it's suppressed, Pulls when it has an implementation PR, otherwise Reports.- *- * Shared by the deep-link handler ({@link useInboxDeepLink}) and any in-app- * surface that links to a report it only knows by id (e.g. the scout finding- * → linked report chip). On 404/403 (wrong team / deleted) it toasts and- * leaves the current view untouched.- */export function useOpenInboxReport() {const queryClient = useQueryClient();const client = useOptionalAuthenticatedClient();- const resetFilters = useInboxSignalsFilterStore((s) => s.resetFilters);- const channelReportsEnabled = useChannelReportsEnabled();- const { generalChannel } = useTaskChannels();- const generalChannelId = generalChannel?.id;return useCallback(- async (reportId: string) => {+ async (reportId: string, options?: { preserveSource?: boolean }) => {+ const sourceKey = getRouterOrNull()?.history.location.state.__TSR_key;if (!client) {log.warn("Ignoring open-report request – not authenticated");return;@@ -58,35 +37,15 @@ export function useOpenInboxReport() {return;}- resetFilters();- // With channel reports on, detail lives in the report's owning space- // (general when unassigned) so the space sidebar keeps its context. The- // inbox routes stay the fallback while the general space isn't- // provisioned yet.- const targetChannelId = channelReportsEnabled- ? (report.channel_id ?? generalChannelId)- : undefined;- if (targetChannelId) {- navigateToChannelReportDetail(targetChannelId, report.id);- } else if (report.status === "suppressed") {- navigateToInboxDismissedDetail(report.id);- } else if (report.implementation_pr_url) {- navigateToInboxPullRequestDetail(report.id);- } else {- navigateToInboxReportDetail(report.id);- }+ if (getRouterOrNull()?.history.location.state.__TSR_key !== sourceKey)+ return;+ navigateToReport(report.id, options);log.info(`Successfully opened report: ${report.id}`);} catch (error) {log.error("Unexpected error opening report:", error);toast.error("Failed to open report");}},- [- client,- queryClient,- resetFilters,- channelReportsEnabled,- generalChannelId,- ],+ [client, queryClient],);}diff --git a/products/desktop/packages/ui/src/features/navigation/useActiveSession.ts b/products/desktop/packages/ui/src/features/navigation/useActiveSession.tsindex 5d4add2c7950..5e8ad6e43cc2 100644--- a/products/desktop/packages/ui/src/features/navigation/useActiveSession.ts+++ b/products/desktop/packages/ui/src/features/navigation/useActiveSession.ts@@ -1,7 +1,7 @@import { useRailSurface } from "@posthog/ui/features/canvas/hooks/useRailSurface";import { useActivitySelection } from "@posthog/ui/features/canvas/stores/activityDetailStore";import { useTaskFeedSelectionStore } from "@posthog/ui/features/canvas/stores/taskFeedSelectionStore";-import { useParams } from "@tanstack/react-router";+import { useParams, useSearch } from "@tanstack/react-router";export interface ActiveSession {taskId: string | undefined;@@ -23,6 +23,12 @@ export function useActiveSession(): ActiveSession {const taskId = useParams({ strict: false, select: (p) => p.taskId });const channelId = useParams({ strict: false, select: (p) => p.channelId });const feedId = useParams({ strict: false, select: (p) => p.feedId });+ // The feed route names its picked task in the search, so the session+ // survives a reload or a report detour, as the store alone cannot.+ const routeFeedTask = useSearch({+ strict: false,+ select: (s) => (s as { task?: string })?.task,+ });if (showsActivityDetail) {const taskSelection = selected?.kind === "task" ? selected : null;@@ -31,10 +37,10 @@ export function useActiveSession(): ActiveSession {channelId: taskSelection?.channelId ?? undefined,};}- if (feedId && feedSelected?.feedId === feedId) {+ if (feedId && (routeFeedTask || feedSelected?.feedId === feedId)) {return {- taskId: feedSelected.taskId,- channelId: feedSelected.channelId ?? undefined,+ taskId: routeFeedTask ?? feedSelected?.taskId,+ channelId: feedSelected?.channelId ?? undefined,};}return { taskId, channelId };diff --git a/products/desktop/packages/ui/src/features/navigation/useReviewInRightPanel.test.ts b/products/desktop/packages/ui/src/features/navigation/useReviewInRightPanel.test.tsindex d8e98b860309..4f0eb997dd6c 100644--- a/products/desktop/packages/ui/src/features/navigation/useReviewInRightPanel.test.ts+++ b/products/desktop/packages/ui/src/features/navigation/useReviewInRightPanel.test.ts@@ -13,6 +13,7 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({useChannelsLayout: () => mocks.channelsLayout,}));vi.mock("@tanstack/react-router", () => ({+ useSearch: () => ({}),useParams: (opts?: {select?: (p: {taskId?: string;@@ -25,10 +26,16 @@ vi.mock("@tanstack/react-router", () => ({}: {select: (s: {matches: { fullPath: string; search: Record<string, unknown> }[];+ location: { pathname: string; href: string; search: object };}) => unknown;}) =>select({matches: [{ fullPath: mocks.fullPath, search: mocks.search }],+ location: {+ pathname: mocks.fullPath,+ href: mocks.fullPath,+ search: mocks.search,+ },}),}));diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutHelperSkillLinks.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutHelperSkillLinks.tsxindex 8d7c9543a9fb..c6416d562fed 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutHelperSkillLinks.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutHelperSkillLinks.tsx@@ -1,6 +1,7 @@import type { ScoutSurface } from "@posthog/shared";import { ANALYTICS_EVENTS } from "@posthog/shared";import { useSkillsSelectionActions } from "@posthog/ui/features/skills/skillsSelectionStore";+import { settingsSourceHref } from "@posthog/ui/router/reportNavigation";import { track } from "@posthog/ui/shell/analytics";import { Text } from "@radix-ui/themes";import { Link } from "@tanstack/react-router";@@ -25,6 +26,7 @@ export function ScoutHelperSkillLinks({ surface }: { surface: ScoutSurface }) {<Linkto="/settings/$category"params={{ category: "skills" }}+ search={{ from: settingsSourceHref() }}onClick={() => {track(ANALYTICS_EVENTS.SCOUT_ACTION, {action_type: "open_helper_skill",diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.tsindex be3c2d647265..8169f32e69bf 100644--- a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.ts+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.ts@@ -38,8 +38,11 @@ export function useScoutDeepLink() {log.info(`Opening scout from deep link: skillSlug=${skillSlug} findingId=${findingId ?? "(none)"}`,);- agentsPageActions().openAgent(skillSlug, { findingId });+ // One navigation carries the whole target: a second call (openSettings+ // after openAgent) builds its own entry and clears the agent fields the+ // first one wrote.openSettings("agents");+ agentsPageActions().openAgent(skillSlug, { findingId });}, []);useEffect(() => {diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsLayout.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsLayout.tsxnew file mode 100644index 000000000000..02ad5445b7ed--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsLayout.tsx@@ -0,0 +1,60 @@+import { AnnouncementBanner } from "@posthog/ui/features/announcements/AnnouncementBanner";+import { ConnectivityBanner } from "@posthog/ui/features/connectivity/ConnectivityBanner";+import { SettingsPanel } from "@posthog/ui/features/settings/components/SettingsPanel";+import type { SettingsCategory } from "@posthog/ui/features/settings/types";+import { navigateToSettings } from "@posthog/ui/router/navigationBridge";+import { getRouterOrNull } from "@posthog/ui/router/routerRef";+import type { ReactNode } from "react";+import { createPortal } from "react-dom";++export function SettingsLayout({+ category,+ children,+ childBackHref,+}: {+ category: SettingsCategory;+ children?: ReactNode;+ /**+ * Where the panel's Back button goes when hosting child content. A child+ * page reached through this portal (a report opened from settings) knows its+ * own source; without this the Back handler rebuilds the target from the+ * category alone and drops the child's context (the open agent, its tab and+ * the nested source).+ */+ childBackHref?: string;+}) {+ const container =+ document.getElementById("portal-container") ?? document.body;+ return createPortal(+ <div+ className="absolute inset-0 z-[100] flex flex-col bg-(--color-background)"+ data-overlay="settings"+ >+ <ConnectivityBanner />+ <AnnouncementBanner />+ <div className="flex min-h-0 flex-1">+ <SettingsPanel+ activeCategory={category}+ onClose={+ children+ ? childBackHref+ ? // Same shape as leaving settings for a recorded source: push+ // the href and keep this tab's tag, so the composer session+ // keyed on it survives.+ () => {+ const router = getRouterOrNull();+ router?.history.push(childBackHref, {+ tabId: router.history.location.state.tabId,+ });+ }+ : () => navigateToSettings(category)+ : undefined+ }+ >+ {children}+ </SettingsPanel>+ </div>+ </div>,+ container,+ );+}diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsxindex 92e92935e3f1..82595e639b24 100644--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx@@ -126,12 +126,14 @@ export interface SettingsPanelProps {onClose?: () => void;/** Override the category-change handler. Defaults to router navigation. */onCategoryChange?: (category: SettingsCategory) => void;+ children?: ReactNode;}export function SettingsPanel({activeCategory: activeCategoryProp,onClose,onCategoryChange,+ children,}: SettingsPanelProps = {}) {const formMode = useSettingsPageStore((s) => s.formMode);const activeCategory = activeCategoryProp ?? "general";@@ -202,7 +204,7 @@ export function SettingsPanel({onClick={close}><ArrowLeft size={14} />- <span>Back to app</span>+ <span>{children ? "Back" : "Back to app"}</span></button><SettingsSearchInput@@ -289,11 +291,13 @@ export function SettingsPanel({fill="url(#settings-dot-pattern)"/></svg>- <SettingsPageContent- category={resolvedCategory}- formMode={formMode}- icon={activeCategoryIcon}- />+ {children ?? (+ <SettingsPageContent+ category={resolvedCategory}+ formMode={formMode}+ icon={activeCategoryIcon}+ />+ )}</div></div></div>diff --git a/products/desktop/packages/ui/src/features/settings/hooks/useOpenSettings.test.ts b/products/desktop/packages/ui/src/features/settings/hooks/useOpenSettings.test.tsindex d9753deae109..df4be72bcd17 100644--- a/products/desktop/packages/ui/src/features/settings/hooks/useOpenSettings.test.ts+++ b/products/desktop/packages/ui/src/features/settings/hooks/useOpenSettings.test.ts@@ -1,20 +1,19 @@import { beforeEach, describe, expect, it, vi } from "vitest";const navigateToSettings = vi.fn();+const leaveSettingsRoute = vi.fn();const isOnSettingsRoute = vi.fn(() => false);vi.mock("@posthog/ui/router/navigationBridge", () => ({navigateToSettings: (...args: unknown[]) => navigateToSettings(...args),isOnSettingsRoute: () => isOnSettingsRoute(),isSettingsRouteId: (routeId: string) => routeId.includes("/settings/"),- canGoBackInHistory: vi.fn(),- goBackInHistory: vi.fn(),- navigateToNewTask: vi.fn(),+ leaveSettingsRoute: () => leaveSettingsRoute(),}));-import { openSettings } from "./useOpenSettings";+import { closeSettings, openSettings } from "./useOpenSettings";-describe("openSettings", () => {+describe("settings navigation", () => {beforeEach(() => {vi.clearAllMocks();isOnSettingsRoute.mockReturnValue(false);@@ -27,8 +26,6 @@ describe("openSettings", () => {});});- // "Back to app" is a single history step, so a category change from inside- // settings must replace — otherwise it lands on the previous category.it("replaces the entry when already inside settings", () => {isOnSettingsRoute.mockReturnValue(true);openSettings("shortcuts");@@ -36,4 +33,13 @@ describe("openSettings", () => {replace: true,});});++ it.each([true, false])(+ "leaves settings by route when on a settings route: %s",+ (onRoute) => {+ isOnSettingsRoute.mockReturnValue(onRoute);+ closeSettings();+ expect(leaveSettingsRoute).toHaveBeenCalledTimes(onRoute ? 1 : 0);+ },+ );});diff --git a/products/desktop/packages/ui/src/features/settings/hooks/useOpenSettings.ts b/products/desktop/packages/ui/src/features/settings/hooks/useOpenSettings.tsindex 06d383d875fa..1c9d1a9e0296 100644--- a/products/desktop/packages/ui/src/features/settings/hooks/useOpenSettings.ts+++ b/products/desktop/packages/ui/src/features/settings/hooks/useOpenSettings.ts@@ -1,6 +1,7 @@import { useSettingsPageStore } from "@posthog/ui/features/settings/stores/settingsPageStore";import type { SettingsCategory } from "@posthog/ui/features/settings/types";import * as nav from "@posthog/ui/router/navigationBridge";+import { useReportSourceHref } from "@posthog/ui/router/reportNavigation";import { useRouterState } from "@tanstack/react-router";interface SettingsContext {@@ -19,8 +20,7 @@ export function openSettings(): void {prepareSettingsPage(contextOrAction);// A caller already inside settings is switching category, so replace rather- // than stack: one closeSettings() back-step must exit to the app instead of- // walking back through the categories visited.+ // than stack: the categories visited are not steps to walk back through.nav.navigateToSettings(category, { replace: nav.isOnSettingsRoute() });}@@ -52,25 +52,21 @@ export function leaveSettings(): void {useSettingsPageStore.getState().reset();}-/**- * Close the settings page — returns the user to their prior route via- * router history. If they came in via a deep link, falls back to /code.- */+/** A deep link carries no `from`, so it falls back to /code. */export function closeSettings(): void {useSettingsPageStore.getState().reset();if (!nav.isOnSettingsRoute()) return;- if (nav.canGoBackInHistory()) {- nav.goBackInHistory();- } else {- nav.navigateToNewTask();- }+ nav.leaveSettingsRoute();}/**- * True when the current route is anywhere under `/settings/*`.+ * True when settings covers the screen: a settings route, or a report opened+ * from one (it hosts the same portal).*/export function useIsSettingsOpen(): boolean {- return useRouterState({+ const route = useRouterState({select: (s) => s.matches.some((m) => nav.isSettingsRouteId(m.routeId)),});+ const reportFromSettings = useReportSourceHref()?.startsWith("/settings/");+ return route || reportFromSettings === true;}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsxindex bea87e5952dc..375b4362c0c4 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx@@ -37,7 +37,10 @@ const {}));vi.mock("@posthog/ui/shell/analytics", () => ({ track }));-vi.mock("@posthog/ui/router/useAppView", () => ({ useAppView }));+vi.mock("@posthog/ui/router/useAppView", () => ({+ useAppView,+ useReportSourceNavType: () => null,+}));// Channel reports defaults off here so the Inbox item renders; the flag-on// test flips it via `channelReportsFlag`.let channelReportsFlag = false;@@ -103,7 +106,16 @@ vi.mock("@posthog/ui/features/canvas/hooks/useTaskActivity", () => ({useTaskActivity: () => ({ items: [], unreadCount: 0, isLoading: false }),}));vi.mock("@tanstack/react-router", () => ({- useRouterState: () => false,+ useRouterState: ({ select }: { select: (state: unknown) => unknown }) =>+ select({+ matches: [],+ location: {+ pathname: "/",+ href: "/",+ search: {},+ state: {},+ },+ }),}));import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsxindex 5b14443e98e6..e8d905d72f65 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx@@ -23,7 +23,10 @@ import {navigateToLoops,navigateToSpacesContext,} from "@posthog/ui/router/navigationBridge";-import { useAppView } from "@posthog/ui/router/useAppView";+import {+ useAppView,+ useReportSourceNavType,+} from "@posthog/ui/router/useAppView";import { openTaskInput } from "@posthog/ui/router/useOpenTask";import { track } from "@posthog/ui/shell/analytics";import { useCommandMenuStore } from "@posthog/ui/shell/commandMenuStore";@@ -61,6 +64,9 @@ export function SidebarNavSection({commandCenterActiveCount: providedActiveCount,}: SidebarNavSectionProps = {}) {const view = useAppView();+ // A report names the surface it was opened from; its row stays marked so the+ // legacy sidebar answers "where am I" the way the rail does.+ const reportSourceNavType = useReportSourceNavType();const openBrowserTab = useOpenBrowserTab();// Loops stays behind the loops flag. Also gates the per-channel Loops tab// (see ChannelTabs).@@ -84,12 +90,21 @@ export function SidebarNavSection({const goNewTask = () => openTaskInput();// Active flags are pure functions of the current view — mirror what- // useSidebarData derives, without pulling in its task-loading.+ // useSidebarData derives, without pulling in its task-loading. On a report+ // they fall back to the row the report was opened from.const isHomeActive = view.type === "task-input";- const isActivityActive = view.type === "activity";- const isInboxActive = view.type === "inbox";- const isLoopsActive = view.type === "loops";- const isCommandCenterActive = view.type === "command-center";+ const isActivityActive =+ view.type === "activity" ||+ (view.type === "report" && reportSourceNavType === "activity");+ const isInboxActive =+ view.type === "inbox" ||+ (view.type === "report" && reportSourceNavType === "inbox");+ const isLoopsActive =+ view.type === "loops" ||+ (view.type === "report" && reportSourceNavType === "loops");+ const isCommandCenterActive =+ view.type === "command-center" ||+ (view.type === "report" && reportSourceNavType === "command-center");const isContextActive = view.type === "context";// Only subscribe to the task list when a parent hasn't already supplied thediff --git a/products/desktop/packages/ui/src/features/sidebar/useSidebarData.ts b/products/desktop/packages/ui/src/features/sidebar/useSidebarData.tsindex 32989c0d0347..cfcb94964aae 100644--- a/products/desktop/packages/ui/src/features/sidebar/useSidebarData.ts+++ b/products/desktop/packages/ui/src/features/sidebar/useSidebarData.ts@@ -16,6 +16,7 @@ import type {} from "@posthog/core/sidebar/sidebarData.types";import { computeSummaryIds } from "@posthog/core/sidebar/summaryIds";import type { AppView } from "@posthog/ui/router/useAppView";+import { useReportSourceNavType } from "@posthog/ui/router/useAppView";import { useEffect, useMemo, useRef } from "react";import { useArchivedTaskIds } from "../archive/useArchivedTaskIds";import { useFolders } from "../folders/useFolders";@@ -131,10 +132,16 @@ export function useSidebarData({],);+ // A report keeps the source surface's row marked, matching the rail.+ const reportSourceNavType = useReportSourceNavType();const isHomeActive = activeView.type === "task-input";- const isInboxActive = activeView.type === "inbox";+ const isInboxActive =+ activeView.type === "inbox" ||+ (activeView.type === "report" && reportSourceNavType === "inbox");const isAgentsActive = activeView.type === "agents";- const isCommandCenterActive = activeView.type === "command-center";+ const isCommandCenterActive =+ activeView.type === "command-center" ||+ (activeView.type === "report" && reportSourceNavType === "command-center");const isSkillsActive = activeView.type === "skills";const isMcpServersActive = activeView.type === "mcp-servers";diff --git a/products/desktop/packages/ui/src/primitives/Breadcrumb.tsx b/products/desktop/packages/ui/src/primitives/Breadcrumb.tsxnew file mode 100644index 000000000000..6a5b0d5224f0--- /dev/null+++ b/products/desktop/packages/ui/src/primitives/Breadcrumb.tsx@@ -0,0 +1,89 @@+import { Button, cn, Text } from "@posthog/quill";+import type { ReactElement, ReactNode } from "react";++/**+ * One segment of the breadcrumb. Always a Button, so every segment carries the+ * same padding, height and icon gap whether or not it goes anywhere — the leaf+ * used to be bare text, which left it visually adrift from its siblings.+ *+ * Without `onClick` or `render` the segment is genuinely inert: `aria-disabled`+ * (so quill drops the hover fill and assistive tech reads it as unavailable)+ * plus `pointer-events-none`, and out of the tab order. The disabled dimming is+ * overridden — a breadcrumb has to stay readable.+ */+export function BreadcrumbSegment({+ icon,+ label,+ strong,+ muted,+ shrink,+ onClick,+ render,+ contextMenu = false,+ className,+ ...rest+}: {+ icon?: ReactNode;+ label: string;+ /** The leaf gives up width first, since it carries the longest name. */+ shrink?: boolean;+ /** The root segment carries the space name, which reads heavier. */+ strong?: boolean;+ /** The leaf is the current page, so it sits back from the linked segments. */+ muted?: boolean;+ /** Navigates, or (on a renamable leaf) opens the inline editor. */+ onClick?: () => void;+ render?: ReactElement;+ contextMenu?: boolean;+ className?: string;+}) {+ const interactive = Boolean(onClick) || Boolean(render);++ return (+ <Button+ {...rest}+ {...(render ? { render } : { type: "button" as const })}+ size="sm"+ aria-disabled={interactive ? undefined : true}+ tabIndex={interactive ? undefined : -1}+ onClick={onClick}+ className={cn(+ "no-drag min-w-0",+ // `shrink` beats quill's own `shrink-0`. Only the leaf takes it: a+ // segment that cannot shrink keeps its full width in a row that has+ // run out, and paints its label over the marks after it. The fixed+ // segments stay whole, so a long session name is what gives.+ shrink && "shrink",+ // Live segments (a link, or a click-to-rename leaf) behave like+ // any other button: pointer cursor and hover fill. Inert ones read as+ // plain text — full opacity, ordinary cursor, and no hover (quill's+ // hover rules already skip aria-disabled) — and leave the tab order.+ interactive || contextMenu+ ? "cursor-pointer!"+ : "pointer-events-none cursor-default! opacity-100!",+ className,+ )}+ >+ {icon && (+ <span className="flex shrink-0 text-muted-foreground/80">{icon}</span>+ )}+ {/* No `title`: the native tooltip duplicated the styled one, and on the+ fixed segments there was nothing worth revealing. */}+ <Text+ className={cn(+ "min-w-0 truncate whitespace-nowrap text-[13px]",+ strong && "font-medium",+ muted && "text-muted-foreground",+ )}+ >+ {label}+ </Text>+ </Button>+ );+}++export function BreadcrumbSeparator() {+ return (+ <Text className="shrink-0 text-[13px] text-muted-foreground/20">/</Text>+ );+}diff --git a/products/desktop/packages/ui/src/router/navigationBridge.test.ts b/products/desktop/packages/ui/src/router/navigationBridge.test.tsindex 1763bb9a220d..8bd104100096 100644--- a/products/desktop/packages/ui/src/router/navigationBridge.test.ts+++ b/products/desktop/packages/ui/src/router/navigationBridge.test.ts@@ -9,9 +9,21 @@ vi.mock("./routerRef", () => ({}));import {+ leaveSettingsRoute,navigateToChannelNewTask,+ navigateToChannelReportDetail,+ navigateToInboxDismissedDetail,+ navigateToInboxPullRequestDetail,+ navigateToInboxReportDetail,navigateToNewTask,+ navigateToReport,+ navigateToSettings,} from "./navigationBridge";+import {+ reportSourceHrefFromLocation,+ resolveNavigationSource,+ validSourceHref,+} from "./reportNavigation";type StateUpdater = (prev: Record<string, unknown>) => Record<string, unknown>;@@ -79,3 +91,180 @@ describe("new-task navigation carries the tab tag", () => {expect(navigate).not.toHaveBeenCalled();});});++describe("canonical report navigation", () => {+ const navigate = vi.fn();+ const replace = vi.fn();+ const push = vi.fn();+ const location = {+ href: "/settings/agents?filter=custom",+ pathname: "/settings/agents",+ search: {},+ state: { tabId: "agents-tab" },+ };++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getRouterOrNull.mockReturnValue({+ navigate,+ state: { location },+ history: { location, replace, push },+ });+ });++ it.each([+ navigateToReport,+ navigateToInboxReportDetail,+ navigateToInboxPullRequestDetail,+ navigateToInboxDismissedDetail,+ (reportId: string) =>+ navigateToChannelReportDetail("owning-space", reportId),+ ])("opens the canonical path and keeps the source", (open) => {+ open("report-1");+ const { to, params, search, state } = navigate.mock.calls[0][0];+ expect(to).toBe("/reports/$reportId");+ expect(params).toEqual({ reportId: "report-1" });+ expect(search).toEqual({ from: location.href });+ expect(state(location.state)).toEqual({ tabId: "agents-tab" });+ });++ it("opens external deep links without inheriting a source", () => {+ navigateToReport("report-1", { preserveSource: false });+ expect(navigate.mock.calls[0][0].search).toEqual({});+ });++ it("keeps the original source when opening another report", () => {+ mocks.getRouterOrNull.mockReturnValue({+ navigate,+ state: {+ location: {+ href: "/reports/first",+ pathname: "/reports/first",+ search: { from: "/activity?task=task-1" },+ state: { tabId: "report-tab" },+ },+ },+ });+ navigateToReport("report-2");+ expect(navigate.mock.calls[0][0].search).toEqual({+ from: "/activity?task=task-1",+ });+ });++ it("records triage selection on the source history entry", () => {+ navigateToInboxReportDetail("report-1", { returnToTriage: true });+ expect(replace).toHaveBeenCalledWith(location.href, {+ ...location.state,+ inboxTriageOrigin: { reportId: "report-1" },+ });+ });++ it("carries the triage origin onto the report entry", () => {+ navigateToInboxReportDetail("report-1", { returnToTriage: true });+ const { state } = navigate.mock.calls[0][0];+ expect(+ state({ tabId: "agents-tab", inboxTriageOrigin: { reportId: "r" } }),+ ).toEqual({ tabId: "agents-tab", inboxTriageOrigin: { reportId: "r" } });+ });++ it.each([+ "/settings/agents",+ "/activity?task=task-1",+ "/spaces/space-1",+ "/inbox/reports",+ "/tasks/task-1",+ ])("accepts internal origin %s", (source) =>+ expect(validSourceHref(source)).toBe(source),+ );++ it.each([+ undefined,+ null,+ {},+ "https://example.com",+ "//example.com",+ "/\\example.com",+ "/reports/first",+ "/inbox/pulls/first",+ "/inbox/runs/first",+ "/spaces/space-1/reports/first",+ "/activity\n",+ ])("rejects unsafe or recursive origin %s", (source) =>+ expect(validSourceHref(source)).toBeUndefined(),+ );++ it("ignores an origin outside the report route", () => {+ expect(+ reportSourceHrefFromLocation({+ pathname: "/activity",+ href: "/activity",+ search: { from: "/settings/agents" },+ }),+ ).toBeUndefined();+ });++ it.each([+ ["/settings/agents", "Agents"],+ ["/settings/claude-code", "Harness"],+ ["/inbox/reports", "Self-driving"],+ ["/inbox/agents", "Agents"],+ ["/activity?task=task-1", "Activity"],+ ["/feeds/github", "Feeds"],+ ["/", "Home"],+ ["/tasks/task-1", "Back"],+ ])("labels the origin %s as %s", (href, label) =>+ expect(resolveNavigationSource(href)?.label).toBe(label),+ );++ it("names the space and feed an origin points at", () => {+ expect(resolveNavigationSource("/spaces/space-1")?.spaceId).toBe("space-1");+ expect(resolveNavigationSource("/feeds/github")?.feedId).toBe("github");+ });+});++describe("leaving the settings route", () => {+ const navigate = vi.fn();+ const push = vi.fn();++ const mountOn = (search: Record<string, unknown>) => {+ const location = {+ href: "/settings/agents",+ pathname: "/settings/agents",+ search,+ state: { tabId: "agents-tab" },+ };+ mocks.getRouterOrNull.mockReturnValue({+ navigate,+ state: { location },+ history: { location, push },+ });+ };++ beforeEach(() => vi.clearAllMocks());++ it("returns to the route that opened settings", () => {+ mountOn({ from: "/spaces/space-1" });+ leaveSettingsRoute();+ expect(push).toHaveBeenCalledWith("/spaces/space-1", {+ tabId: "agents-tab",+ });+ expect(navigate).not.toHaveBeenCalled();+ });++ it("falls back to the app when settings was reached directly", () => {+ mountOn({});+ leaveSettingsRoute();+ expect(push).not.toHaveBeenCalled();+ expect(navigate.mock.calls[0][0].to).toBe("/new");+ });++ it("keeps the source across a category switch", () => {+ mountOn({ from: "/spaces/space-1" });+ navigateToSettings("skills", { replace: true });+ const { to, params, search, replace } = navigate.mock.calls[0][0];+ expect(to).toBe("/settings/$category");+ expect(params).toEqual({ category: "skills" });+ expect(search).toEqual({ from: "/spaces/space-1" });+ expect(replace).toBe(true);+ });+});diff --git a/products/desktop/packages/ui/src/router/navigationBridge.ts b/products/desktop/packages/ui/src/router/navigationBridge.tsindex b874884ef000..8be778f5cbfb 100644--- a/products/desktop/packages/ui/src/router/navigationBridge.ts+++ b/products/desktop/packages/ui/src/router/navigationBridge.ts@@ -1,5 +1,11 @@import type { NotificationTarget } from "@posthog/platform/notifications";import type { SettingsCategory } from "@posthog/ui/features/settings/types";+import {+ navigationSourceHref,+ reportNavigationState,+ settingsSourceHref,+ sourceHrefFromSearch,+} from "./reportNavigation";import { getRouterOrNull } from "./routerRef";// This bridge isolates imperative router calls behind a stable API and, by@@ -147,53 +153,49 @@ export function navigateToInboxReports(): void {void getRouterOrNull()?.navigate({ to: "/inbox/reports" });}-export function navigateToInboxPullRequestDetail(reportId: string): void {- void getRouterOrNull()?.navigate({- to: "/inbox/pulls/$reportId",- params: { reportId },- });-}--export function navigateToInboxReportDetail(+export function navigateToReport(reportId: string,- options?: { returnToTriage?: boolean },+ options?: { preserveSource?: boolean; returnToTriage?: boolean },): void {const router = getRouterOrNull();if (!router) return;-- const inboxTriageOrigin = options?.returnToTriage ? { reportId } : undefined;- if (inboxTriageOrigin) {+ if (options?.returnToTriage) {const location = router.history.location;router.history.replace(location.href, {...location.state,- inboxTriageOrigin,+ inboxTriageOrigin: { reportId },});}-+ const from =+ options?.preserveSource === false ? undefined : navigationSourceHref();void router.navigate({- to: "/inbox/reports/$reportId",+ to: "/reports/$reportId",params: { reportId },- state: inboxTriageOrigin- ? (previous) => ({ ...previous, inboxTriageOrigin })- : undefined,+ search: from ? { from } : {},+ state: reportNavigationState,});}+export function navigateToInboxPullRequestDetail(reportId: string): void {+ navigateToReport(reportId);+}++export function navigateToInboxReportDetail(+ reportId: string,+ options?: { returnToTriage?: boolean },+): void {+ navigateToReport(reportId, options);+}+export function navigateToInboxDismissedDetail(reportId: string): void {- void getRouterOrNull()?.navigate({- to: "/inbox/dismissed/$reportId",- params: { reportId },- });+ navigateToReport(reportId);}export function navigateToChannelReportDetail(- channelId: string,+ _channelId: string,reportId: string,): void {- void getRouterOrNull()?.navigate({- to: "/spaces/$channelId/reports/$reportId",- params: { channelId, reportId },- });+ navigateToReport(reportId);}export function navigateToLoops(options?: { ignoreBlocker?: boolean }): void {@@ -250,12 +252,11 @@ export function navigateToSettings(category: SettingsCategory,options?: { replace?: boolean },): void {+ const from = settingsSourceHref();void getRouterOrNull()?.navigate({to: "/settings/$category",params: { category },- // Switching categories within settings should replace, not stack, so a- // single history.back() (closeSettings) exits to the app rather than- // walking back through every category that was visited.+ search: from ? { from } : {},replace: options?.replace,});}@@ -275,6 +276,17 @@ export function isOnSettingsRoute(): boolean {);}+export function leaveSettingsRoute(): void {+ const router = getRouterOrNull();+ if (!router) return;+ const from = sourceHrefFromSearch(router.state.location);+ if (!from) {+ void router.navigate({ to: "/new", state: keepTabTag });+ return;+ }+ router.history.push(from, { tabId: router.history.location.state.tabId });+}+export function goBackInHistory(): void {getRouterOrNull()?.history.back();}diff --git a/products/desktop/packages/ui/src/router/reportNavigation.ts b/products/desktop/packages/ui/src/router/reportNavigation.tsnew file mode 100644index 000000000000..c7a97ee86eb1--- /dev/null+++ b/products/desktop/packages/ui/src/router/reportNavigation.ts@@ -0,0 +1,161 @@+import {+ resolveSettingsCategory,+ SETTINGS_PAGE_LABELS,+ type SettingsCategory,+} from "@posthog/ui/features/settings/types";+import { type HistoryState, useRouterState } from "@tanstack/react-router";+import { getRouterOrNull } from "./routerRef";++export interface NavigationSource {+ href: string;+ path: string;+ label: string;+ settingsCategory: SettingsCategory | null;+ agentSlug: string | null;+ spaceId: string | null;+ feedId: string | null;+}++interface SourceLocation {+ pathname: string;+ href: string;+ search?: unknown;+}++export function isReportPath(pathname: string): boolean {+ return /^\/reports\/[^/]+\/?$/.test(pathname);+}++export function reportIdFromHref(href: string | null): string | null {+ if (!href) return null;+ const pathname = href.split(/[?#]/)[0];+ return isReportPath(pathname) ? (pathname.split("/")[2] ?? null) : null;+}++function isSettingsPath(pathname: string): boolean {+ return /^\/settings(\/|$)/.test(pathname);+}++export function validSourceHref(href: unknown): string | undefined {+ if (+ typeof href !== "string" ||+ !href.startsWith("/") ||+ href.startsWith("//") ||+ href.includes("\\") ||+ Array.from(href).some((character) => character.charCodeAt(0) <= 32)+ ) {+ return undefined;+ }+ const pathname = href.split(/[?#]/)[0];+ if (+ isReportPath(pathname) ||+ /^\/inbox\/(reports|pulls|runs|dismissed)\/[^/]+\/?$/.test(pathname) ||+ /^\/spaces\/[^/]+\/reports\/[^/]+\/?$/.test(pathname)+ ) {+ return undefined;+ }+ return href;+}++const SOURCE_LABELS: readonly (readonly [RegExp, string])[] = [+ [/^\/inbox\/agents(\/|$)/, "Agents"],+ [/^\/inbox(\/|$)/, "Self-driving"],+ [/^\/activity(\/|$)/, "Activity"],+ [/^\/loops(\/|$)/, "Loops"],+ [/^\/canvases(\/|$)/, "Canvases"],+ [/^\/command-center(\/|$)/, "Command center"],+ [/^\/feeds(\/|$)/, "Feeds"],+ [/^\/skills(\/|$)/, "Skills"],+ [/^\/mcp-servers(\/|$)/, "MCP servers"],+ [/^\/spaces(\/|$)/, "Spaces"],+];++function sourceLabel(path: string, category: SettingsCategory | null): string {+ if (category) return SETTINGS_PAGE_LABELS[category];+ if (path === "/") return "Home";+ return SOURCE_LABELS.find(([pattern]) => pattern.test(path))?.[1] ?? "Back";+}++export function resolveNavigationSource(+ href: string | undefined,+): NavigationSource | null {+ const valid = validSourceHref(href);+ if (!valid) return null;+ const path = valid.split(/[?#]/)[0];+ const category = resolveSettingsCategory(+ path.match(/^\/settings\/([^/]+)/)?.[1] ?? "",+ );+ return {+ href: valid,+ path,+ label: sourceLabel(path, category),+ settingsCategory: category,+ agentSlug: valid.match(/[?&]agent=([^&#]+)/)?.[1] ?? null,+ spaceId: path.match(/^\/spaces\/([^/]+)/)?.[1] ?? null,+ feedId: path.match(/^\/feeds\/([^/]+)/)?.[1] ?? null,+ };+}++export function sourceHrefFromSearch(+ location: SourceLocation,+): string | undefined {+ return validSourceHref(+ (location.search as { from?: unknown } | undefined)?.from,+ );+}++export function reportSourceHrefFromLocation(+ location: SourceLocation,+): string | undefined {+ return isReportPath(location.pathname)+ ? sourceHrefFromSearch(location)+ : undefined;+}++function currentSourceHref(+ carriesOwnSource: (pathname: string) => boolean,+): string | undefined {+ const location = getRouterOrNull()?.state?.location;+ if (!location) return undefined;+ return carriesOwnSource(location.pathname)+ ? sourceHrefFromSearch(location)+ : validSourceHref(location.href);+}++export function navigationSourceHref(): string | undefined {+ return currentSourceHref(isReportPath);+}++export function settingsSourceHref(): string | undefined {+ return currentSourceHref(isSettingsPath);+}++export function useReportSourceHref(): string | undefined {+ return useRouterState({+ select: (state) => reportSourceHrefFromLocation(state.location),+ });+}++/**+ * A settings route, or a report opened from one (the report route hosts the+ * settings portal). Everything the root pairs with that portal — inert chrome,+ * banner suppression, settings-only shortcuts — reads this, so the report+ * route gets the same pairing a plain settings route has.+ */+export function useSettingsOverlay(): boolean {+ return useRouterState({+ select: (state) =>+ state.matches.some((match) => match.routeId.includes("/settings/")) ||+ reportSourceHrefFromLocation(state.location)?.startsWith("/settings/") ===+ true,+ });+}++export function reportNavigationState(previous: HistoryState): HistoryState {+ return {+ ...(previous.tabId ? { tabId: previous.tabId } : {}),+ ...(previous.inboxTriageOrigin+ ? { inboxTriageOrigin: previous.inboxTriageOrigin }+ : {}),+ };+}diff --git a/products/desktop/packages/ui/src/router/routeTree.gen.ts b/products/desktop/packages/ui/src/router/routeTree.gen.tsindex da40fdfb7e6d..48a05cea9b73 100644--- a/products/desktop/packages/ui/src/router/routeTree.gen.ts+++ b/products/desktop/packages/ui/src/router/routeTree.gen.ts@@ -23,6 +23,7 @@ import { Route as AgentsIndexRouteImport } from './routes/agents.index'import { Route as ShellIndexRouteImport } from './routes/_shell/index'import { Route as WebsiteSplatRouteImport } from './routes/website.$'import { Route as TasksTaskIdRouteImport } from './routes/tasks/$taskId'+import { Route as ReportsReportIdRouteImport } from './routes/reports/$reportId'import { Route as LoopsNewRouteImport } from './routes/loops/new'import { Route as LoopsLoopIdRouteImport } from './routes/loops/$loopId'import { Route as InboxRunsRouteImport } from './routes/inbox/runs'@@ -136,6 +137,11 @@ const TasksTaskIdRoute = TasksTaskIdRouteImport.update({path: '/tasks/$taskId',getParentRoute: () => rootRouteImport,} as any)+const ReportsReportIdRoute = ReportsReportIdRouteImport.update({+ id: '/reports/$reportId',+ path: '/reports/$reportId',+ getParentRoute: () => rootRouteImport,+} as any)const LoopsNewRoute = LoopsNewRouteImport.update({id: '/loops/new',path: '/loops/new',@@ -385,6 +391,7 @@ export interface FileRoutesByFullPath {'/inbox/runs': typeof InboxRunsRouteWithChildren'/loops/$loopId': typeof LoopsLoopIdRouteWithChildren'/loops/new': typeof LoopsNewRoute+ '/reports/$reportId': typeof ReportsReportIdRoute'/tasks/$taskId': typeof TasksTaskIdRoute'/website/$': typeof WebsiteSplatRoute'/agents/': typeof AgentsIndexRoute@@ -436,6 +443,7 @@ export interface FileRoutesByTo {'/folders/$folderId': typeof FoldersFolderIdRoute'/inbox/agents': typeof InboxAgentsRoute'/loops/new': typeof LoopsNewRoute+ '/reports/$reportId': typeof ReportsReportIdRoute'/tasks/$taskId': typeof TasksTaskIdRoute'/website/$': typeof WebsiteSplatRoute'/': typeof ShellIndexRoute@@ -496,6 +504,7 @@ export interface FileRoutesById {'/inbox/runs': typeof InboxRunsRouteWithChildren'/loops/$loopId': typeof LoopsLoopIdRouteWithChildren'/loops/new': typeof LoopsNewRoute+ '/reports/$reportId': typeof ReportsReportIdRoute'/tasks/$taskId': typeof TasksTaskIdRoute'/website/$': typeof WebsiteSplatRoute'/_shell/': typeof ShellIndexRoute@@ -557,6 +566,7 @@ export interface FileRouteTypes {| '/inbox/runs'| '/loops/$loopId'| '/loops/new'+ | '/reports/$reportId'| '/tasks/$taskId'| '/website/$'| '/agents/'@@ -608,6 +618,7 @@ export interface FileRouteTypes {| '/folders/$folderId'| '/inbox/agents'| '/loops/new'+ | '/reports/$reportId'| '/tasks/$taskId'| '/website/$'| '/'@@ -667,6 +678,7 @@ export interface FileRouteTypes {| '/inbox/runs'| '/loops/$loopId'| '/loops/new'+ | '/reports/$reportId'| '/tasks/$taskId'| '/website/$'| '/_shell/'@@ -716,6 +728,7 @@ export interface RootRouteChildren {FoldersFolderIdRoute: typeof FoldersFolderIdRouteLoopsLoopIdRoute: typeof LoopsLoopIdRouteWithChildrenLoopsNewRoute: typeof LoopsNewRoute+ ReportsReportIdRoute: typeof ReportsReportIdRouteTasksTaskIdRoute: typeof TasksTaskIdRouteWebsiteSplatRoute: typeof WebsiteSplatRouteAgentsIndexRoute: typeof AgentsIndexRoute@@ -824,6 +837,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof TasksTaskIdRouteImportparentRoute: typeof rootRouteImport}+ '/reports/$reportId': {+ id: '/reports/$reportId'+ path: '/reports/$reportId'+ fullPath: '/reports/$reportId'+ preLoaderRoute: typeof ReportsReportIdRouteImport+ parentRoute: typeof rootRouteImport+ }'/loops/new': {id: '/loops/new'path: '/loops/new'@@ -1288,6 +1308,7 @@ const rootRouteChildren: RootRouteChildren = {FoldersFolderIdRoute: FoldersFolderIdRoute,LoopsLoopIdRoute: LoopsLoopIdRouteWithChildren,LoopsNewRoute: LoopsNewRoute,+ ReportsReportIdRoute: ReportsReportIdRoute,TasksTaskIdRoute: TasksTaskIdRoute,WebsiteSplatRoute: WebsiteSplatRoute,AgentsIndexRoute: AgentsIndexRoute,diff --git a/products/desktop/packages/ui/src/router/router.ts b/products/desktop/packages/ui/src/router/router.tsindex ad9887592530..82692268c10b 100644--- a/products/desktop/packages/ui/src/router/router.ts+++ b/products/desktop/packages/ui/src/router/router.ts@@ -4,9 +4,12 @@ import {} from "@tanstack/react-router";import { RouteNotFound } from "./RouteNotFound";import { RoutePending } from "./RoutePending";+import { isReportPath } from "./reportNavigation";import { setRouter } from "./routerRef";import { routeTree } from "./routeTree.gen";+const reportSourceEntries = new Set<string>();+export const router = createTanStackRouter({routeTree,history: createHashHistory(),@@ -26,7 +29,15 @@ export const router = createTanStackRouter({defaultPendingMinMs: 0,defaultPendingComponent: RoutePending,defaultNotFoundComponent: RouteNotFound,- scrollRestoration: false,+ scrollRestoration: ({ location }) =>+ isReportPath(location.pathname) ||+ reportSourceEntries.has(location.state.__TSR_key ?? ""),+});++router.subscribe("onBeforeLoad", ({ fromLocation, toLocation }) => {+ if (fromLocation?.state.__TSR_key && isReportPath(toLocation.pathname)) {+ reportSourceEntries.add(fromLocation.state.__TSR_key);+ }});// Publish the instance to the leaf ref so imperative callers reach it without adiff --git a/products/desktop/packages/ui/src/router/routes/__root.tsx b/products/desktop/packages/ui/src/router/routes/__root.tsxindex 8b07802b9a7d..693cddc1c55c 100644--- a/products/desktop/packages/ui/src/router/routes/__root.tsx+++ b/products/desktop/packages/ui/src/router/routes/__root.tsx@@ -64,7 +64,7 @@ import { UpdateAvailableModal } from "@posthog/ui/features/updates/UpdateAvailabimport { WhatsNewModal } from "@posthog/ui/features/updates/WhatsNewModal";import { useWorkspaces } from "@posthog/ui/features/workspace/useWorkspace";import { AnimatedLogo } from "@posthog/ui/primitives/AnimatedLogo";-import { isSettingsRouteId } from "@posthog/ui/router/navigationBridge";+import { useSettingsOverlay } from "@posthog/ui/router/reportNavigation";import { useAppView } from "@posthog/ui/router/useAppView";import { openTask, openTaskInput } from "@posthog/ui/router/useOpenTask";import { track } from "@posthog/ui/shell/analytics";@@ -282,10 +282,9 @@ function RootLayout() {useEffect(() => onFeatureFlagsLoaded(() => setFlagsLoaded(true)), []);// Settings is a full-page route — drop the app chrome (header/sidebar/- // space-switcher) so the panel occupies the full window.- const isSettingsRoute = useRouterState({- select: (s) => s.matches.some((m) => isSettingsRouteId(m.routeId)),- });+ // space-switcher) so the panel occupies the full window. A report opened+ // from settings hosts the same portal, so it counts as settings here too.+ const isSettingsRoute = useSettingsOverlay();// ShellLayout draws the in-pane header under `_shell`, so the shared// ContentHeader is mounted only where that layout isn't.diff --git a/products/desktop/packages/ui/src/router/routes/_shell/feeds/$feedId.tsx b/products/desktop/packages/ui/src/router/routes/_shell/feeds/$feedId.tsxindex ed081756b7b8..1df976881a11 100644--- a/products/desktop/packages/ui/src/router/routes/_shell/feeds/$feedId.tsx+++ b/products/desktop/packages/ui/src/router/routes/_shell/feeds/$feedId.tsx@@ -9,14 +9,22 @@ import { createFileRoute } from "@tanstack/react-router";export const Route = createFileRoute("/_shell/feeds/$feedId")({component: TaskFeedRoute,+ // The picked task rides in the URL, as it does on Activity, so the location+ // says what the pane shows: a tab can name it, a reload keeps it, and a+ // report opened from a task artifact can return to it.+ validateSearch: (search: Record<string, unknown>): { task?: string } => ({+ task:+ typeof search.task === "string" && search.task ? search.task : undefined,+ }),...withRouteSkeleton(ChannelSkeleton),});function TaskFeedRoute() {const { feedId } = Route.useParams();+ const { task: routeTaskId } = Route.useSearch();const channelsLayout = useChannelsLayout();return channelsLayout ? (- <TaskFeedDetailPane feedId={feedId} />+ <TaskFeedDetailPane feedId={feedId} routeTaskId={routeTaskId} />) : (<TaskFeedHome feedId={feedId} />);diff --git a/products/desktop/packages/ui/src/router/routes/_shell/settings/$category.tsx b/products/desktop/packages/ui/src/router/routes/_shell/settings/$category.tsxindex ce92ab3f1bca..af9f0c6ece35 100644--- a/products/desktop/packages/ui/src/router/routes/_shell/settings/$category.tsx+++ b/products/desktop/packages/ui/src/router/routes/_shell/settings/$category.tsx@@ -1,17 +1,31 @@-import { AnnouncementBanner } from "@posthog/ui/features/announcements/AnnouncementBanner";-import { ConnectivityBanner } from "@posthog/ui/features/connectivity/ConnectivityBanner";-import { SettingsPanel } from "@posthog/ui/features/settings/components/SettingsPanel";+import type { ScoutDetailTab } from "@posthog/core/scouts/scoutDetailTabs";+import type {+ AgentsPageSearch,+ AgentsTab,+} from "@posthog/ui/features/agents/agentsPageStore";+import { SettingsLayout } from "@posthog/ui/features/settings/components/SettingsLayout";import { useSettingsPageStore } from "@posthog/ui/features/settings/stores/settingsPageStore";import { resolveSettingsCategory } from "@posthog/ui/features/settings/types";+import { validSourceHref } from "@posthog/ui/router/reportNavigation";import { createFileRoute } from "@tanstack/react-router";import { useEffect } from "react";-import { createPortal } from "react-dom";// Nested under `_shell` so the sidebar, tab strip and panels stay mounted while// settings covers them; leaving settings then costs one tab switch instead of// rebuilding the whole shell.export const Route = createFileRoute("/_shell/settings/$category")({component: SettingsRoute,+ validateSearch: (search: Record<string, unknown>): AgentsPageSearch => {+ const text = (value: unknown) =>+ typeof value === "string" ? value : undefined;+ return {+ from: validSourceHref(search.from),+ tab: text(search.tab) as AgentsTab | undefined,+ agent: text(search.agent),+ agentTab: text(search.agentTab) as ScoutDetailTab | undefined,+ finding: text(search.finding),+ };+ },});function SettingsRoute() {@@ -25,24 +39,5 @@ function SettingsRoute() {return () => useSettingsPageStore.getState().reset();}, []);- // Portalling to document.body would land outside the Radix <Theme> subtree.- const container =- document.getElementById("portal-container") ?? document.body;-- return createPortal(- <div- className="absolute inset-0 z-[100] flex flex-col bg-(--color-background)"- data-overlay="settings"- >- {/* The shell's copies are covered by this overlay and inert, so the- banners move here for the duration: losing connectivity while- settings is open must still show the offline state and its Retry. */}- <ConnectivityBanner />- <AnnouncementBanner />- <div className="flex min-h-0 flex-1">- <SettingsPanel activeCategory={cat} />- </div>- </div>,- container,- );+ return <SettingsLayout category={cat} />;}diff --git a/products/desktop/packages/ui/src/router/routes/_shell/spaces/$channelId/reports/$reportId.tsx b/products/desktop/packages/ui/src/router/routes/_shell/spaces/$channelId/reports/$reportId.tsxindex 768da5496a33..d0997bf1f77a 100644--- a/products/desktop/packages/ui/src/router/routes/_shell/spaces/$channelId/reports/$reportId.tsx+++ b/products/desktop/packages/ui/src/router/routes/_shell/spaces/$channelId/reports/$reportId.tsx@@ -1,35 +1,16 @@-import type { SignalReport } from "@posthog/shared/types";-import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";-import { ReportDetail } from "@posthog/ui/features/inbox/components/ReportDetail";-import { getCachedInboxReportDetail } from "@posthog/ui/features/inbox/inboxQueries";-import { createFileRoute } from "@tanstack/react-router";+import { reportNavigationState } from "@posthog/ui/router/reportNavigation";+import { createFileRoute, redirect } from "@tanstack/react-router";export const Route = createFileRoute("/_shell/spaces/$channelId/reports/$reportId",)({- component: ChannelReportDetailRoute,- pendingComponent: () => null,- loader: ({ params }): SignalReport | null =>- getCachedInboxReportDetail(params.reportId) ?? null,+ beforeLoad: ({ params }) => {+ throw redirect({+ to: "/reports/$reportId",+ params: { reportId: params.reportId },+ search: { from: `/spaces/${params.channelId}` },+ state: reportNavigationState,+ replace: true,+ });+ },});--function ChannelReportDetailRoute() {- const { channelId, reportId } = Route.useParams();- const cachedReport = Route.useLoaderData();- const { channels } = useChannels();- const channelName = channels.find(- (channel) => channel.id === channelId,- )?.name;-- return (- <div className="h-full min-h-0">- <ReportDetail- reportId={reportId}- cachedReport={cachedReport}- backTo={`/spaces/${channelId}`}- backLabel={channelName ? `Back to #${channelName}` : "Back to space"}- statusRedirect={false}- />- </div>- );-}diff --git a/products/desktop/packages/ui/src/router/routes/agents.$.tsx b/products/desktop/packages/ui/src/router/routes/agents.$.tsxindex 4792f7b47e43..e73751606b37 100644--- a/products/desktop/packages/ui/src/router/routes/agents.$.tsx+++ b/products/desktop/packages/ui/src/router/routes/agents.$.tsx@@ -1,32 +1,43 @@-import { agentsPageActions } from "@posthog/ui/features/agents/agentsPageStore";+import type { AgentsPageSearch } from "@posthog/ui/features/agents/agentsPageStore";import { createFileRoute, redirect } from "@tanstack/react-router";// The agents pages became the Agents settings page, which has one URL for all// of its tabs. Old hrefs still arrive from deep links, notifications and// restored history. Findings links open Self-driving; other links open the-// tab or the agent they named.+// tab or the agent they named. The redirect carries the target in its search —+// a bare redirect would land on the fleet and drop what the href named.export const Route = createFileRoute("/agents/$")({beforeLoad: ({ params, location }) => {const rest = (params._splat ?? "").replace(/^scouts\/?/, "");- const actions = agentsPageActions();+ const search = location.search as { finding?: unknown };+ const finding =+ typeof search.finding === "string" ? search.finding : undefined;if (rest === "findings") {throw redirect({ to: "/inbox", replace: true });} else if (rest === "scratchpad") {- actions.showTab("memory");+ throw agentRedirect({ tab: "memory" });} else if (rest) {- const finding = (location.search as { finding?: unknown }).finding;- actions.openAgent(rest.split("/")[0], {- findingId: typeof finding === "string" ? finding : undefined,- });+ throw agentRedirect({ agent: rest.split("/")[0], finding });} else {- actions.showTab("agents");+ throw agentRedirect({ tab: "agents" });}-- throw redirect({- to: "/settings/$category",- params: { category: "agents" },- replace: true,- });},});++function agentRedirect(+ target: Pick<AgentsPageSearch, "tab"> &+ Partial<Pick<AgentsPageSearch, "agent" | "finding">>,+): never {+ const search: AgentsPageSearch = {+ ...(target.tab ? { tab: target.tab } : {}),+ ...(target.agent ? { agent: target.agent } : {}),+ ...(target.finding ? { finding: target.finding } : {}),+ };+ throw redirect({+ to: "/settings/$category",+ params: { category: "agents" },+ search,+ replace: true,+ });+}diff --git a/products/desktop/packages/ui/src/router/routes/inbox/dismissed.$reportId.tsx b/products/desktop/packages/ui/src/router/routes/inbox/dismissed.$reportId.tsxindex 5c18630aace7..a05f14f158e8 100644--- a/products/desktop/packages/ui/src/router/routes/inbox/dismissed.$reportId.tsx+++ b/products/desktop/packages/ui/src/router/routes/inbox/dismissed.$reportId.tsx@@ -1,19 +1,21 @@-import type { SignalReport } from "@posthog/shared/types";-import { DismissedReportDetail } from "@posthog/ui/features/inbox/components/DismissedReportDetail";-import { getCachedInboxReportDetail } from "@posthog/ui/features/inbox/inboxQueries";-import { createFileRoute } from "@tanstack/react-router";+import { asInboxBackTarget } from "@posthog/ui/features/inbox/hooks/useInboxBackTarget";+import { reportNavigationState } from "@posthog/ui/router/reportNavigation";+import { createFileRoute, redirect } from "@tanstack/react-router";export const Route = createFileRoute("/inbox/dismissed/$reportId")({- component: DismissedReportDetailRoute,- pendingComponent: () => null,- loader: ({ params }): SignalReport | null =>- getCachedInboxReportDetail(params.reportId) ?? null,+ beforeLoad: ({ params, location }) => {+ // The run-detail gate records where the open run came from when it+ // redirects an archived report here. Follow that path in (e.g. back to+ // Runs, not Archive) and fall back to the Archive tab when there is none.+ const from =+ asInboxBackTarget(location.state.inboxBackOrigin)?.to ??+ "/inbox/dismissed";+ throw redirect({+ to: "/reports/$reportId",+ params: { reportId: params.reportId },+ search: { from },+ state: reportNavigationState,+ replace: true,+ });+ },});--function DismissedReportDetailRoute() {- const { reportId } = Route.useParams();- const cachedReport = Route.useLoaderData();- return (- <DismissedReportDetail reportId={reportId} cachedReport={cachedReport} />- );-}diff --git a/products/desktop/packages/ui/src/router/routes/inbox/pulls.$reportId.tsx b/products/desktop/packages/ui/src/router/routes/inbox/pulls.$reportId.tsxindex 6babaefc3b2b..d69ae6689a48 100644--- a/products/desktop/packages/ui/src/router/routes/inbox/pulls.$reportId.tsx+++ b/products/desktop/packages/ui/src/router/routes/inbox/pulls.$reportId.tsx@@ -1,17 +1,14 @@-import type { SignalReport } from "@posthog/shared/types";-import { PullRequestDetail } from "@posthog/ui/features/inbox/components/PullRequestDetail";-import { getCachedInboxReportDetail } from "@posthog/ui/features/inbox/inboxQueries";-import { createFileRoute } from "@tanstack/react-router";+import { reportNavigationState } from "@posthog/ui/router/reportNavigation";+import { createFileRoute, redirect } from "@tanstack/react-router";export const Route = createFileRoute("/inbox/pulls/$reportId")({- component: PullRequestDetailRoute,- pendingComponent: () => null,- loader: ({ params }): SignalReport | null =>- getCachedInboxReportDetail(params.reportId) ?? null,+ beforeLoad: ({ params }) => {+ throw redirect({+ to: "/reports/$reportId",+ params: { reportId: params.reportId },+ search: { from: "/inbox/pulls" },+ state: reportNavigationState,+ replace: true,+ });+ },});--function PullRequestDetailRoute() {- const { reportId } = Route.useParams();- const cachedReport = Route.useLoaderData();- return <PullRequestDetail reportId={reportId} cachedReport={cachedReport} />;-}diff --git a/products/desktop/packages/ui/src/router/routes/inbox/reports.$reportId.tsx b/products/desktop/packages/ui/src/router/routes/inbox/reports.$reportId.tsxindex 7aab6bb21355..85da8f5c0f73 100644--- a/products/desktop/packages/ui/src/router/routes/inbox/reports.$reportId.tsx+++ b/products/desktop/packages/ui/src/router/routes/inbox/reports.$reportId.tsx@@ -1,17 +1,14 @@-import type { SignalReport } from "@posthog/shared/types";-import { ReportDetail } from "@posthog/ui/features/inbox/components/ReportDetail";-import { getCachedInboxReportDetail } from "@posthog/ui/features/inbox/inboxQueries";-import { createFileRoute } from "@tanstack/react-router";+import { reportNavigationState } from "@posthog/ui/router/reportNavigation";+import { createFileRoute, redirect } from "@tanstack/react-router";export const Route = createFileRoute("/inbox/reports/$reportId")({- component: ReportDetailRoute,- pendingComponent: () => null,- loader: ({ params }): SignalReport | null =>- getCachedInboxReportDetail(params.reportId) ?? null,+ beforeLoad: ({ params }) => {+ throw redirect({+ to: "/reports/$reportId",+ params: { reportId: params.reportId },+ search: { from: "/inbox/reports" },+ state: reportNavigationState,+ replace: true,+ });+ },});--function ReportDetailRoute() {- const { reportId } = Route.useParams();- const cachedReport = Route.useLoaderData();- return <ReportDetail reportId={reportId} cachedReport={cachedReport} />;-}diff --git a/products/desktop/packages/ui/src/router/routes/reports/$reportId.tsx b/products/desktop/packages/ui/src/router/routes/reports/$reportId.tsxnew file mode 100644index 000000000000..a39a6990a138--- /dev/null+++ b/products/desktop/packages/ui/src/router/routes/reports/$reportId.tsx@@ -0,0 +1,21 @@+import type { SignalReport } from "@posthog/shared/types";+import { ReportPage } from "@posthog/ui/features/inbox/components/ReportPage";+import { getCachedInboxReportDetail } from "@posthog/ui/features/inbox/inboxQueries";+import { validSourceHref } from "@posthog/ui/router/reportNavigation";+import { createFileRoute } from "@tanstack/react-router";++export const Route = createFileRoute("/reports/$reportId")({+ component: ReportRoute,+ validateSearch: (search: Record<string, unknown>): { from?: string } => {+ const from = validSourceHref(search.from);+ return from ? { from } : {};+ },+ loader: ({ params }): SignalReport | null =>+ getCachedInboxReportDetail(params.reportId) ?? null,+});++function ReportRoute() {+ const { reportId } = Route.useParams();+ const cachedReport = Route.useLoaderData();+ return <ReportPage reportId={reportId} cachedReport={cachedReport} />;+}diff --git a/products/desktop/packages/ui/src/router/useAppView.test.ts b/products/desktop/packages/ui/src/router/useAppView.test.tsindex 48fb35c77ed1..83d5e6130523 100644--- a/products/desktop/packages/ui/src/router/useAppView.test.ts+++ b/products/desktop/packages/ui/src/router/useAppView.test.ts@@ -15,6 +15,12 @@ import { getAppViewSnapshot } from "./useAppView";// written in id form silently never matches and settings falls through to the// task-input view.describe("getAppViewSnapshot", () => {+ it("treats the canonical report as its own view, not a task or Inbox", () => {+ mocks.matches = [+ { fullPath: "/reports/$reportId", params: { reportId: "report-1" } },+ ];+ expect(getAppViewSnapshot()).toEqual({ type: "report" });+ });it.each([{ fullPath: "/settings/$category", params: { category: "general" } },{ fullPath: "/settings/", params: {} },diff --git a/products/desktop/packages/ui/src/router/useAppView.ts b/products/desktop/packages/ui/src/router/useAppView.tsindex 01b302d5eb7e..98516485d55e 100644--- a/products/desktop/packages/ui/src/router/useAppView.ts+++ b/products/desktop/packages/ui/src/router/useAppView.ts@@ -3,6 +3,10 @@ import {type TaskInputReportAssociation,useTaskInputPrefillStore,} from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";+import {+ isReportPath,+ reportSourceHrefFromLocation,+} from "@posthog/ui/router/reportNavigation";import { useRouterState } from "@tanstack/react-router";import { useMemo } from "react";import { getCurrentMatches } from "./navigationBridge";@@ -14,6 +18,7 @@ export type AppViewType =| "activity"| "home"| "inbox"+ | "report"// The Agents page moved into Settings, so no route yields this view any// more. It stays for tabs that were opened on the old page.| "agents"@@ -69,6 +74,8 @@ function deriveFromMatches(matches: Match[]): AppView {return { type: "home" };case "/inbox":return { type: "inbox" };+ case "/reports/$reportId":+ return { type: "report" };case "/loops":return { type: "loops" };case "/archived":@@ -157,6 +164,35 @@ export function useAppView(): AppView {}, [fullPath, taskId, pendingKey, folderId, prefill]);}+/**+ * The legacy navigation row a report's source path belongs to. Only the types+ * the legacy sidebar highlights; settings, tasks and other non-row surfaces+ * return null.+ */+export function legacyNavTypeForPath(path: string): AppViewType | null {+ if (/^\/inbox(\/|$)/.test(path)) return "inbox";+ if (/^\/activity(\/|$)/.test(path)) return "activity";+ if (/^\/loops(\/|$)/.test(path)) return "loops";+ if (/^\/command-center(\/|$)/.test(path)) return "command-center";+ return null;+}++/**+ * On a report, the legacy navigation row its source names; null on any other+ * route (or a report with no row-shaped source). Lets the legacy sidebar keep+ * "you are here" while a report is open, matching what the rail does with the+ * same `?from=`.+ */+export function useReportSourceNavType(): AppViewType | null {+ return useRouterState({+ select: (s) => {+ if (!isReportPath(s.location.pathname)) return null;+ const source = reportSourceHrefFromLocation(s.location);+ return source ? legacyNavTypeForPath(source.split(/[?#]/)[0]) : null;+ },+ });+}+/*** Read the current view outside React (event handlers, imperative code).* Components should prefer `useAppView()` for proper subscription.