Skip to content

: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.

fix(desktop): open report references in the app (#97957)

Dylan Martin67df6f0ea88e
diff --git a/products/desktop/apps/code/src/main/quick-ask-trpc.test.ts b/products/desktop/apps/code/src/main/quick-ask-trpc.test.ts
new file mode 100644
index 000000000000..73bf9abfde50
--- /dev/null
+++ b/products/desktop/apps/code/src/main/quick-ask-trpc.test.ts
@@ -0,0 +1,131 @@
+import {
+ createIPCHandler,
+ ELECTRON_TRPC_CHANNEL,
+} from "@posthog/electron-trpc/main";
+import { deepLinkRouter } from "@posthog/host-router/routers/deep-link.router";
+import { publicProcedure, router } from "@posthog/host-trpc/trpc";
+import { DEEP_LINK_SERVICE } from "@posthog/platform/deep-link";
+import type { BrowserWindow } from "electron";
+import { ipcMain } from "electron";
+import { Container } from "inversify";
+import superjson from "superjson";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { QUICK_ASK_TRPC_ROUTES } from "./quick-ask-trpc";
+
+vi.mock("electron", async () => {
+ const { EventEmitter } = await import("node:events");
+ return { ipcMain: new EventEmitter() };
+});
+
+afterEach(() => {
+ ipcMain.removeAllListeners();
+});
+
+describe("Quick Ask IPC boundary", () => {
+ it.each([
+ {
+ path: "deepLink.openInboxReport",
+ input: { reportId: "report-1" },
+ outcome: "opened",
+ },
+ ...[{}, { reportId: " " }, { reportId: "report-1", kind: "compose" }].map(
+ (input) => ({
+ path: "deepLink.openInboxReport",
+ input,
+ outcome: "invalid",
+ }),
+ ),
+ ...[
+ { kind: "compose", prompt: "Example task", repo: "posthog/posthog" },
+ { kind: "open_space", channel_id: "channel-1" },
+ { kind: "open_canvas", channel_id: "channel-1", canvas_id: "canvas-1" },
+ { kind: "open_inbox", report_id: "report-1" },
+ ].map((action) => ({
+ path: "deepLink.openAgentAction",
+ input: { action },
+ outcome: "blocked",
+ })),
+ {
+ path: "deepLink.open",
+ input: { url: "posthog-code://new?prompt=Example" },
+ outcome: "blocked",
+ },
+ { path: "secureStore.set", input: {}, outcome: "blocked" },
+ ])(
+ "gates $path with $input as $outcome",
+ async ({ path, input, outcome }) => {
+ const handleUrl = vi.fn(() => true);
+ const secureStoreSet = vi.fn();
+ const container = new Container();
+ container.bind(DEEP_LINK_SERVICE).toConstantValue({
+ handleUrl,
+ getProtocol: () => "posthog-code-dev",
+ });
+ const testRouter = router({
+ deepLink: deepLinkRouter,
+ secureStore: router({
+ set: publicProcedure.mutation(secureStoreSet),
+ }),
+ });
+ const webContents = {
+ id: 2,
+ isDestroyed: () => false,
+ on: vi.fn(),
+ once: vi.fn(),
+ };
+ const window = {
+ isDestroyed: () => false,
+ webContents,
+ } as unknown as BrowserWindow;
+ const handler = createIPCHandler({
+ router: testRouter,
+ windows: [],
+ createContext: async () => ({ container }),
+ });
+ handler.attachWindow(window, {
+ allowedPaths: (route) => QUICK_ASK_TRPC_ROUTES.has(route),
+ });
+ const event = { sender: webContents, reply: vi.fn() };
+
+ ipcMain.emit(ELECTRON_TRPC_CHANNEL, event, {
+ method: "request",
+ operation: {
+ context: {},
+ id: 1,
+ input: superjson.serialize(input),
+ path,
+ type: "mutation",
+ signal: undefined,
+ },
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(secureStoreSet).not.toHaveBeenCalled();
+ if (outcome === "opened") {
+ expect(handleUrl).toHaveBeenCalledExactlyOnceWith(
+ "posthog-code-dev://inbox/report-1",
+ );
+ expect(event.reply).toHaveBeenCalledExactlyOnceWith(
+ ELECTRON_TRPC_CHANNEL,
+ { id: 1, result: { type: "data", data: superjson.serialize(true) } },
+ );
+ } else {
+ expect(handleUrl).not.toHaveBeenCalled();
+ if (outcome === "blocked") {
+ expect(event.reply).not.toHaveBeenCalled();
+ } else {
+ expect(event.reply).toHaveBeenCalledExactlyOnceWith(
+ ELECTRON_TRPC_CHANNEL,
+ expect.objectContaining({
+ error: expect.objectContaining({
+ json: expect.objectContaining({
+ data: expect.objectContaining({ code: "BAD_REQUEST" }),
+ }),
+ }),
+ }),
+ );
+ }
+ }
+ },
+ );
+});
diff --git a/products/desktop/apps/code/src/main/quick-ask-trpc.ts b/products/desktop/apps/code/src/main/quick-ask-trpc.ts
new file mode 100644
index 000000000000..a334a28bb4d8
--- /dev/null
+++ b/products/desktop/apps/code/src/main/quick-ask-trpc.ts
@@ -0,0 +1,9 @@
+export const QUICK_ASK_TRPC_ROUTES: ReadonlySet<string> = new Set([
+ "auth.getState",
+ "auth.onStateChanged",
+ "auth.getValidAccessToken",
+ "auth.refreshAccessToken",
+ "os.openExternal",
+ "customCloud.get",
+ "deepLink.openInboxReport",
+]);
diff --git a/products/desktop/apps/code/src/main/quick-ask.ts b/products/desktop/apps/code/src/main/quick-ask.ts
index 08365c9f210a..4b927d5ec9e8 100644
--- a/products/desktop/apps/code/src/main/quick-ask.ts
+++ b/products/desktop/apps/code/src/main/quick-ask.ts
@@ -48,6 +48,7 @@ import {
setupQuickAskCapture,
teardownQuickAskCapture,
} from "./quick-ask-capture";
+import { QUICK_ASK_TRPC_ROUTES } from "./quick-ask-trpc";
import { logger } from "./utils/logger";
import { quickAskStore } from "./utils/store";
import { attachWindowToTrpc, focusMainWindow } from "./window";
@@ -219,19 +220,10 @@ let quickAskWindow: BrowserWindow | null = null;
/**
* The only host tRPC routes the panel renderer may call: auth state and
- * tokens for its PostHog API client, and opening vetted external links.
+ * tokens for its PostHog API client, vetted external links, and app navigation.
* Everything else on the router (shell, fs, secureStore, git…) stays
* unreachable from this window even if its renderer is compromised.
*/
-const QUICK_ASK_TRPC_ROUTES = new Set([
- "auth.getState",
- "auth.onStateChanged",
- "auth.getValidAccessToken",
- "auth.refreshAccessToken",
- "os.openExternal",
- "customCloud.get",
-]);
-
function createQuickAskWindow(): BrowserWindow {
const window = new BrowserWindow({
width: PANEL_INITIAL_WIDTH,
@@ -265,7 +257,7 @@ function createQuickAskWindow(): BrowserWindow {
});
// Answer rendering fetches live data over the host tRPC bridge, narrowed
- // to the auth-token and external-link routes the panel actually uses.
+ // to the auth-token, external-link, and app-navigation routes it uses.
attachWindowToTrpc(window, (path) => QUICK_ASK_TRPC_ROUTES.has(path));
// The panel shares the app session and its privileged preload bridges, so
diff --git a/products/desktop/apps/code/src/renderer/quick-ask/main.tsx b/products/desktop/apps/code/src/renderer/quick-ask/main.tsx
index c755b7f03519..a1efa6e17fcb 100644
--- a/products/desktop/apps/code/src/renderer/quick-ask/main.tsx
+++ b/products/desktop/apps/code/src/renderer/quick-ask/main.tsx
@@ -9,7 +9,9 @@ import { HostTRPCProvider } from "@posthog/host-router/react";
import type { HostRouter } from "@posthog/host-router/router";
import { QuickAsk } from "@posthog/quick-ask/panel/QuickAsk";
import { getAuthIdentity, useAuthStore } from "@posthog/ui/features/auth/store";
+import { ReportReferenceNavigationContext } from "@posthog/ui/features/editor/components/EvidenceRefChip";
import { ThemeWrapper } from "@posthog/ui/primitives/ThemeWrapper";
+import { logger } from "@posthog/ui/shell/logger";
import { useThemeStore } from "@posthog/ui/shell/themeStore";
import { hydrateCustomCloud } from "@renderer/custom-cloud";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -26,6 +28,14 @@ const hostTrpcClient = createTRPCClient<HostRouter>({
links: [ipcLink({ transformer: superjson })],
});
+async function openReport(reportId: string): Promise<void> {
+ try {
+ await hostTrpcClient.deepLink.openInboxReport.mutate({ reportId });
+ } catch (error) {
+ logger.scope("quick-ask").error("Failed to open report", error);
+ }
+}
+
// Components outside React's tree (openExternalUrl) resolve the host client
// through the shared service locator.
const container = new Container();
@@ -90,7 +100,9 @@ void hydrateCustomCloud().then(() => {
queryClient={queryClient}
>
<ThemeWrapper>
- <QuickAsk />
+ <ReportReferenceNavigationContext.Provider value={openReport}>
+ <QuickAsk />
+ </ReportReferenceNavigationContext.Provider>
</ThemeWrapper>
</HostTRPCProvider>
</QueryClientProvider>
diff --git a/products/desktop/apps/code/src/renderer/quick-ask/report-navigation.test.tsx b/products/desktop/apps/code/src/renderer/quick-ask/report-navigation.test.tsx
new file mode 100644
index 000000000000..477cdd8306ab
--- /dev/null
+++ b/products/desktop/apps/code/src/renderer/quick-ask/report-navigation.test.tsx
@@ -0,0 +1,90 @@
+import { AnswerCard } from "@posthog/quick-ask/panel/components/AnswerCard";
+import {
+ ANONYMOUS_AUTH_STATE,
+ useAuthStore,
+} from "@posthog/ui/features/auth/store";
+import { ReportReferenceNavigationContext } from "@posthog/ui/features/editor/components/EvidenceRefChip";
+import { ThemeWrapper } from "@posthog/ui/primitives/ThemeWrapper";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@posthog/quill-charts", () => ({
+ BarChart: () => null,
+ LineChart: () => null,
+ TimeSeriesBarChart: () => null,
+ TimeSeriesLineChart: () => null,
+ useChartTheme: () => ({}),
+}));
+vi.mock("@posthog/ui/shell/openExternal", () => ({
+ openExternalUrl: vi.fn(),
+}));
+vi.mock("@posthog/ui/features/editor/useEvidencePreviewPrefetch", () => ({
+ useEvidencePreviewPrefetch: () => {},
+}));
+vi.mock("@posthog/ui/features/auth/authClient", () => ({
+ useOptionalAuthenticatedClient: () => null,
+}));
+vi.mock("@posthog/ui/hooks/useAuthenticatedQuery", () => ({
+ useAuthenticatedQuery: () => ({ isPending: true }),
+}));
+
+afterEach(() => {
+ vi.clearAllMocks();
+ useAuthStore.setState({ authState: ANONYMOUS_AUTH_STATE });
+});
+
+describe("Quick Ask report navigation", () => {
+ it.each([
+ { kind: "report", signedIn: true },
+ { kind: "report", signedIn: false },
+ { kind: "insight", signedIn: true },
+ ] as const)(
+ "handles a $kind click with signedIn=$signedIn",
+ async ({ kind, signedIn }) => {
+ useAuthStore.setState({
+ authState: signedIn
+ ? { ...ANONYMOUS_AUTH_STATE, cloudRegion: "us", currentProjectId: 2 }
+ : ANONYMOUS_AUTH_STATE,
+ });
+ const openReport = vi.fn().mockResolvedValue(undefined);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const { unmount } = render(
+ <QueryClientProvider client={queryClient}>
+ <ThemeWrapper>
+ <ReportReferenceNavigationContext.Provider value={openReport}>
+ <AnswerCard
+ parts={[
+ {
+ id: "answer-1",
+ content: `Open <${kind} id="reference-1">Linked reference</${kind}>.`,
+ complete: true,
+ },
+ ]}
+ streaming={false}
+ statusLabel={null}
+ onOpenInApp={vi.fn()}
+ />
+ </ReportReferenceNavigationContext.Provider>
+ </ThemeWrapper>
+ </QueryClientProvider>,
+ );
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("link", { name: "Linked reference" }));
+ });
+
+ if (kind === "report") {
+ expect(openReport).toHaveBeenCalledExactlyOnceWith("reference-1");
+ } else {
+ expect(openReport).not.toHaveBeenCalled();
+ }
+ expect(openExternalUrl).not.toHaveBeenCalled();
+ unmount();
+ queryClient.clear();
+ },
+ );
+});
diff --git a/products/desktop/biome.jsonc b/products/desktop/biome.jsonc
index 5eaf27cd98a0..c2df521caac9 100644
--- a/products/desktop/biome.jsonc
+++ b/products/desktop/biome.jsonc
@@ -79,6 +79,7 @@
"!apps/code/src/main/index.ts",
"!apps/code/src/main/window.ts",
"!apps/code/src/main/quick-ask.ts",
+ "!apps/code/src/main/quick-ask-trpc.test.ts",
"!apps/code/src/main/quick-ask-capture.ts",
"!apps/code/src/main/external-links.ts",
"!apps/code/src/main/menu.ts",
diff --git a/products/desktop/docs/DEEP-LINKS.md b/products/desktop/docs/DEEP-LINKS.md
index 79fff1104bf7..7903e9ad164e 100644
--- a/products/desktop/docs/DEEP-LINKS.md
+++ b/products/desktop/docs/DEEP-LINKS.md
@@ -16,6 +16,16 @@ If the app is not running, the OS launches it and the link is queued until the r
Links can also be dispatched from inside the app: the `deepLink.open` tRPC route forwards a URL through the same handlers, with no OS hop. Remote announcement CTAs use this — author payloads with the production scheme; dev builds swap in their scheme automatically.
+## Report references in the app
+
+Report references in agent messages open the full report page in the current app, including inside task chats. They do not open a general object preview or an external browser. The hover card's explicit **Open in PostHog** action still opens the web page.
+
+Quick Ask sends report navigation to the main Desktop window through `deepLink.openInboxReport`.
+This route accepts only a non-empty report ID and is included in the Quick Ask IPC allowlist.
+The broader `deepLink.openAgentAction` route remains blocked for Quick Ask.
+Report references bypass the panel's click suppression; other reference kinds keep their preview-only behavior.
+Its separate window does not use the main window's router or tab services.
+
## User-facing links
These are the deep links you would share with someone or wire up from another tool.
diff --git a/products/desktop/packages/host-router/src/routers/deep-link.router.ts b/products/desktop/packages/host-router/src/routers/deep-link.router.ts
index f6f09f59d315..44d5b6b202b1 100644
--- a/products/desktop/packages/host-router/src/routers/deep-link.router.ts
+++ b/products/desktop/packages/host-router/src/routers/deep-link.router.ts
@@ -80,6 +80,18 @@ export const deepLinkRouter = router({
);
}),
+ openInboxReport: publicProcedure
+ .input(z.strictObject({ reportId: z.string().trim().min(1) }))
+ .mutation(({ ctx, input }) => {
+ const deepLinks = ctx.container.get<IDeepLinkRegistry>(DEEP_LINK_SERVICE);
+ return deepLinks.handleUrl(
+ buildActionUrl(
+ { kind: "open_inbox", report_id: input.reportId },
+ deepLinks.getProtocol(),
+ ),
+ );
+ }),
+
onOpenTask: publicProcedure.subscription(async function* (opts) {
const service = opts.ctx.container.get<TaskLinkService>(TASK_LINK_SERVICE);
const iterable = service.toIterable(TaskLinkEvent.OpenTask, {
diff --git a/products/desktop/packages/quick-ask/src/panel/components/AnswerCard.tsx b/products/desktop/packages/quick-ask/src/panel/components/AnswerCard.tsx
index cbc21de0cc46..751f0fd55b16 100644
--- a/products/desktop/packages/quick-ask/src/panel/components/AnswerCard.tsx
+++ b/products/desktop/packages/quick-ask/src/panel/components/AnswerCard.tsx
@@ -22,8 +22,7 @@ const AUTOSCROLL_SLACK_PX = 48;
/**
* The shared reference chip with its live hover preview. The chip's own
- * click-out is suppressed: in the panel the hover card is the destination,
- * and its "open" affordance still links out.
+ * click-out is suppressed except for reports, which open in the main window.
*/
function PanelChip({
target,
@@ -34,8 +33,9 @@ function PanelChip({
}): React.JSX.Element {
return (
<span
- className="qa-ref"
+ className={target.kind === "report" ? undefined : "qa-ref"}
onClickCapture={(event) => {
+ if (target.kind === "report") return;
event.preventDefault();
event.stopPropagation();
}}
diff --git a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.test.tsx b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.test.tsx
index 79806e824a3e..b84ebf50b747 100644
--- a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.test.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.test.tsx
@@ -1,19 +1,35 @@
import { POSTHOG_OBJECT_KINDS } from "@posthog/core/message-editor/content";
+import { ServiceProvider } from "@posthog/di/react";
+import { BROWSER_TABS_CLIENT } from "@posthog/ui/features/browser-tabs/browserTabsClient";
import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";
+import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";
import { SessionTaskIdProvider } from "@posthog/ui/features/sessions/useSessionTaskId";
import { Theme } from "@radix-ui/themes";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { fireEvent, render, screen } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({
+ openReport: vi.fn(),
+ getSignalReport: vi.fn(async (id: string) => ({ id })),
+}));
+
+vi.mock("@posthog/ui/router/navigationBridge", () => ({
+ navigateToReport: mocks.openReport,
+}));
+
vi.mock("../../../shell/openExternal", () => ({
openExternalUrl: vi.fn(),
}));
-// The hover card resolves its preview through the app shell; without it the
-// loader renders the static card, which is all the chip tests need.
+vi.mock("../useEvidencePreviewPrefetch", () => ({
+ useEvidencePreviewPrefetch: () => {},
+}));
+
vi.mock("../../auth/authClient", () => ({
- useOptionalAuthenticatedClient: () => null,
+ useOptionalAuthenticatedClient: () => ({
+ getSignalReport: mocks.getSignalReport,
+ }),
}));
vi.mock("../../../hooks/useAuthenticatedQuery", () => ({
useAuthenticatedQuery: () => ({
@@ -30,17 +46,29 @@ import { ANALYTICS_TRACKER } from "../../../shell/analytics";
import { openExternalUrl } from "../../../shell/openExternal";
import { ANONYMOUS_AUTH_STATE, useAuthStore } from "../../auth/store";
import { evidencePreviewQueryKey } from "../evidencePreview";
-import { EvidenceHoverCard, EvidenceRefChip } from "./EvidenceRefChip";
+import {
+ EvidenceHoverCard,
+ EvidenceRefChip,
+ ReportReferenceNavigationContext,
+} from "./EvidenceRefChip";
import { MarkdownRenderer } from "./MarkdownRenderer";
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
-function renderInTheme(node: React.ReactNode) {
+function renderInTheme(node: React.ReactNode, withServices = true) {
+ const container = new Container();
+ container.bind(BROWSER_TABS_CLIENT).toConstantValue({});
return render(
<QueryClientProvider client={queryClient}>
- <Theme>{node}</Theme>
+ <Theme>
+ {withServices ? (
+ <ServiceProvider container={container}>{node}</ServiceProvider>
+ ) : (
+ node
+ )}
+ </Theme>
</QueryClientProvider>,
);
}
@@ -64,6 +92,8 @@ function bindTracker() {
}
afterEach(() => {
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
useAuthStore.setState({ authState: ANONYMOUS_AUTH_STATE });
queryClient.clear();
const actions = useDraftStore.getState().actions;
@@ -83,18 +113,111 @@ describe("EvidenceRefChip", () => {
expect(screen.queryByRole("link")).toBeNull();
});
- it("derives the PostHog url from the reference and opens it externally", () => {
- signIn();
+ it.each([
+ { kind: "report", taskId: "task-1", destination: "report" },
+ { kind: "report", taskId: null, destination: "report" },
+ { kind: "insight", taskId: "task-1", destination: "tab" },
+ { kind: "insight", taskId: null, destination: "external" },
+ ] as const)(
+ "opens $kind in $destination with task context $taskId",
+ async ({ kind, taskId, destination }) => {
+ signIn();
+ const openObjectTab = vi
+ .spyOn(usePanelLayoutStore.getState(), "openPostHogObjectTab")
+ .mockImplementation(() => {});
+ const reference = (
+ <EvidenceRefChip target={{ kind, id: "reference-1" }}>
+ Linked reference
+ </EvidenceRefChip>
+ );
+ renderInTheme(
+ taskId ? (
+ <SessionTaskIdProvider taskId={taskId}>
+ {reference}
+ </SessionTaskIdProvider>
+ ) : (
+ reference
+ ),
+ );
+
+ fireEvent.click(screen.getByRole("link", { name: "Linked reference" }));
+
+ if (destination === "report") {
+ await waitFor(() =>
+ expect(mocks.openReport).toHaveBeenCalledWith(
+ "reference-1",
+ undefined,
+ ),
+ );
+ expect(mocks.getSignalReport).toHaveBeenCalledWith("reference-1");
+ expect(openObjectTab).not.toHaveBeenCalled();
+ expect(openExternalUrl).not.toHaveBeenCalled();
+ } else if (destination === "tab") {
+ expect(openObjectTab).toHaveBeenCalledWith(taskId, {
+ kind,
+ id: "reference-1",
+ name: "Linked reference",
+ });
+ expect(mocks.openReport).not.toHaveBeenCalled();
+ expect(openExternalUrl).not.toHaveBeenCalled();
+ } else {
+ expect(openExternalUrl).toHaveBeenCalledWith(
+ "https://us.posthog.com/project/2/insights/reference-1",
+ );
+ expect(mocks.openReport).not.toHaveBeenCalled();
+ expect(openObjectTab).not.toHaveBeenCalled();
+ }
+ },
+ );
+
+ it.each(["report", "insight"] as const)(
+ "opens a %s from Quick Ask without main-window services",
+ (kind) => {
+ signIn();
+ const openReport = vi.fn().mockResolvedValue(undefined);
+ renderInTheme(
+ <ReportReferenceNavigationContext.Provider value={openReport}>
+ <MarkdownRenderer
+ content={`Open <${kind} id="reference-1">Linked reference</${kind}>.`}
+ renderObjectTags
+ />
+ </ReportReferenceNavigationContext.Provider>,
+ false,
+ );
+
+ fireEvent.click(screen.getByRole("link", { name: "Linked reference" }));
+
+ if (kind === "report") {
+ expect(openReport).toHaveBeenCalledWith("reference-1");
+ expect(openExternalUrl).not.toHaveBeenCalled();
+ } else {
+ expect(openReport).not.toHaveBeenCalled();
+ expect(openExternalUrl).toHaveBeenCalledWith(
+ "https://us.posthog.com/project/2/insights/reference-1",
+ );
+ }
+ expect(mocks.openReport).not.toHaveBeenCalled();
+ expect(mocks.getSignalReport).not.toHaveBeenCalled();
+ },
+ );
+
+ it("opens a report from Quick Ask before auth state arrives", () => {
+ // No region or project yet, so the chip has no web url to fall back on;
+ // the host route is the only way to the report and must stay clickable.
+ const openReport = vi.fn().mockResolvedValue(undefined);
renderInTheme(
- <EvidenceRefChip target={{ kind: "insight", id: "9pQx3" }}>
- Checkout funnel
- </EvidenceRefChip>,
- );
- const link = screen.getByRole("link", { name: "Checkout funnel" });
- fireEvent.click(link);
- expect(openExternalUrl).toHaveBeenCalledWith(
- "https://us.posthog.com/project/2/insights/9pQx3",
+ <ReportReferenceNavigationContext.Provider value={openReport}>
+ <EvidenceRefChip target={{ kind: "report", id: "reference-1" }}>
+ Linked reference
+ </EvidenceRefChip>
+ </ReportReferenceNavigationContext.Provider>,
+ false,
);
+
+ fireEvent.click(screen.getByRole("link", { name: "Linked reference" }));
+
+ expect(openReport).toHaveBeenCalledWith("reference-1");
+ expect(openExternalUrl).not.toHaveBeenCalled();
});
it("stays plain for a kind with no canonical page even when signed in", () => {
diff --git a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
index cafc5cefe420..dc8994df67c5 100644
--- a/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/EvidenceRefChip.tsx
@@ -3,10 +3,13 @@ import { CheckIcon, CopyIcon } from "@phosphor-icons/react";
import { isPostHogObjectKind } from "@posthog/core/message-editor/content";
import { Button } from "@posthog/quill";
import { getCloudUrlFromRegion } from "@posthog/shared";
+import { useOpenInboxReport } from "@posthog/ui/features/inbox/hooks/useOpenInboxReport";
import { useQueryClient } from "@tanstack/react-query";
import {
+ createContext,
type MouseEvent,
type ReactNode,
+ useContext,
useEffect,
useId,
useRef,
@@ -50,8 +53,8 @@ import { useEvidencePreviewPrefetch } from "../useEvidencePreviewPrefetch";
*
* The reference carries only `kind/id`. Hovering or focusing mounts the card,
* which resolves the object's live name and status through the PostHog API
- * (for `hogql`, runs the query); clicking a linked reference opens the object
- * in PostHog at a URL derived from the reference and the current project.
+ * (for `hogql`, runs the query); report links open the report in the app.
+ * Other links open a task object tab, or PostHog outside a task.
* Nothing about the object is stored in the message itself.
*
* The card is a Base UI popover, not a tooltip: it holds real controls (the
@@ -424,12 +427,40 @@ export function useEvidenceUrl(kind: string, id: string): string | null {
return `${getCloudUrlFromRegion(cloudRegion)}/project/${projectId}${path}`;
}
-export function EvidenceRefChip({
- target,
- children,
-}: {
+interface EvidenceRefChipProps {
target: EvidenceLinkTarget;
children: ReactNode;
+}
+
+export const ReportReferenceNavigationContext = createContext<
+ ((reportId: string) => Promise<void>) | null
+>(null);
+
+export function EvidenceRefChip(props: EvidenceRefChipProps) {
+ const openReport = useContext(ReportReferenceNavigationContext);
+ return props.target.kind === "report" && !openReport ? (
+ <InboxReportRefChip {...props} />
+ ) : (
+ <EvidenceRefChipContent
+ {...props}
+ onOpenReport={
+ props.target.kind === "report" ? (openReport ?? undefined) : undefined
+ }
+ />
+ );
+}
+
+function InboxReportRefChip(props: EvidenceRefChipProps) {
+ const openReport = useOpenInboxReport();
+ return <EvidenceRefChipContent {...props} onOpenReport={openReport} />;
+}
+
+function EvidenceRefChipContent({
+ target,
+ children,
+ onOpenReport,
+}: EvidenceRefChipProps & {
+ onOpenReport?: (reportId: string) => Promise<void>;
}) {
const meta = getObjectKind(target.kind);
const KindIcon = meta.icon;
@@ -464,6 +495,11 @@ export function EvidenceRefChip({
const openReference = (event: MouseEvent<HTMLAnchorElement>) => {
event.preventDefault();
+ if (onOpenReport) {
+ void onOpenReport(target.id);
+ setOpen(false);
+ return;
+ }
if (taskId) {
openPostHogObjectTab(taskId, {
kind: target.kind,
@@ -501,7 +537,7 @@ export function EvidenceRefChip({
// to PostHog instead of toggling the popover.
onFocus={() => setOpen(true)}
render={
- url || taskId ? (
+ url || taskId || onOpenReport ? (
// Keep the truthful role: Enter follows the link (opens the
// object's page in the app, or in PostHog outside a session), it
// does not act as a popover button.