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.

feat(desktop): open deep links in a new browser tab (#97663)

Shy Alter7d9c78e1e038
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.test.ts b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.test.ts
index 993039944513..8e84a10bcb01 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.test.ts
+++ b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.test.ts
@@ -1,7 +1,9 @@
import type { TabsSnapshot } from "@posthog/shared";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { BrowserTabsClient } from "./browserTabsClient";
import {
focusExistingTab,
+ focusOrOpenBrowserTab,
getCurrentBrowserTabId,
navigateBrowserTab,
} from "./imperativeTabNavigation";
@@ -12,6 +14,8 @@ const mocks = vi.hoisted(() => ({
persistTabTarget: vi.fn(),
readMirror: vi.fn(),
setTabTarget: vi.fn(),
+ persistWrite: vi.fn(),
+ reseedMirror: vi.fn(),
}));
vi.mock("@posthog/ui/router/routerRef", () => ({
@@ -21,6 +25,8 @@ vi.mock("./tabsSync", () => ({
applyLocalTransform: mocks.applyLocalTransform,
persistTabTarget: mocks.persistTabTarget,
readMirror: mocks.readMirror,
+ persistWrite: mocks.persistWrite,
+ reseedMirror: mocks.reseedMirror,
}));
vi.mock("@posthog/shared", async (importOriginal) => {
const actual = await importOriginal<typeof import("@posthog/shared")>();
@@ -37,6 +43,9 @@ const destination = {
appView: null,
};
+const client = (): BrowserTabsClient =>
+ ({ openTab: vi.fn() }) as unknown as BrowserTabsClient;
+
function snapshot(): TabsSnapshot {
return {
windows: [
@@ -83,7 +92,10 @@ function snapshot(): TabsSnapshot {
}
describe("imperative browser-tab navigation", () => {
- const history = { location: { state: { tabId: "tab-b" } } };
+ const history = {
+ location: { state: { tabId: "tab-b" as string | undefined } },
+ push: vi.fn(),
+ };
beforeEach(() => {
vi.clearAllMocks();
@@ -136,6 +148,34 @@ describe("imperative browser-tab navigation", () => {
expect(navigateBrowserTab(null, destination, fallback)).toBe("active");
expect(fallback).toHaveBeenCalledOnce();
});
+
+ it("opens an inbound destination in its own tab without touching the current one", async () => {
+ const tabId = await focusOrOpenBrowserTab(client(), destination);
+
+ expect(tabId).toBe(true);
+ const mirror = mocks.applyLocalTransform.mock.results[0]
+ ?.value as TabsSnapshot;
+ expect(mirror.tabs).toHaveLength(3);
+ expect(mirror.tabs.find((t) => t.id === "tab-a")?.href).toBe("/new");
+ expect(mirror.tabs.find((t) => t.id === "tab-b")?.href).toBe("/inbox");
+ expect(mirror.windows[0].activeTabId).toEqual(expect.any(String));
+ expect(history.push).toHaveBeenCalledWith(
+ destination.href,
+ expect.objectContaining({ tabId: expect.any(String) }),
+ );
+ expect(mocks.persistWrite).toHaveBeenCalledOnce();
+ });
+
+ it("reports unavailable when there is no window even after a reseed", async () => {
+ mocks.readMirror.mockReturnValue({ windows: [], tabs: [] });
+ mocks.reseedMirror.mockResolvedValue({ windows: [], tabs: [] });
+
+ await expect(focusOrOpenBrowserTab(client(), destination)).resolves.toBe(
+ false,
+ );
+ expect(mocks.applyLocalTransform).not.toHaveBeenCalled();
+ expect(history.push).not.toHaveBeenCalled();
+ });
});
describe("focusExistingTab", () => {
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts
index 470efb729572..201611e839c9 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts
+++ b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts
@@ -1,12 +1,57 @@
import {
type BrowserTab,
+ openTab as openTabLocal,
primaryWindow,
setTabTarget as setTabTargetLocal,
type TabIdentity,
} from "@posthog/shared";
import { getRouterOrNull } from "@posthog/ui/router/routerRef";
+import type { BrowserTabsClient } from "./browserTabsClient";
import { pushTabHistoryEntry } from "./tabHistory";
-import { applyLocalTransform, persistTabTarget, readMirror } from "./tabsSync";
+import {
+ applyLocalTransform,
+ persistTabTarget,
+ persistWrite,
+ readMirror,
+ reseedMirror,
+} from "./tabsSync";
+
+export function openInNewBrowserTabSync(
+ client: BrowserTabsClient,
+ destination: BrowserTabDestination,
+): string | null {
+ const window = primaryWindow(readMirror());
+ const history = getRouterOrNull()?.history;
+ if (!window || !history) return null;
+ const tabId = crypto.randomUUID();
+ const input = {
+ windowId: window.id,
+ href: destination.href,
+ viewState: destination.title ? { title: destination.title } : null,
+ dashboardId: destination.dashboardId ?? null,
+ taskId: destination.taskId ?? null,
+ channelId: destination.channelId ?? null,
+ channelSection: destination.channelSection ?? null,
+ appView: destination.appView ?? null,
+ };
+ applyLocalTransform(
+ (snapshot) =>
+ openTabLocal(snapshot, { ...input, makeId: () => tabId, now: Date.now })
+ .snapshot,
+ );
+ pushTabHistoryEntry(history, destination.href, tabId);
+ void persistWrite(() => client.openTab({ ...input, tabId }));
+ return tabId;
+}
+
+export async function focusOrOpenBrowserTab(
+ client: BrowserTabsClient,
+ destination: BrowserTabDestination,
+): Promise<boolean> {
+ if (readMirror().windows.length === 0) await reseedMirror();
+ if (focusExistingTab(destination)) return true;
+ return openInNewBrowserTabSync(client, destination) !== null;
+}
export interface BrowserTabDestination extends Partial<TabIdentity> {
href: string;
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasDeepLink.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasDeepLink.ts
index c8f5d97b6e10..c38157711b5f 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasDeepLink.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasDeepLink.ts
@@ -1,6 +1,12 @@
+import { useService } from "@posthog/di/react";
import { useHostTRPC } from "@posthog/host-router/react";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "@posthog/ui/features/browser-tabs/browserTabsClient";
+import { focusOrOpenBrowserTab } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
import { navigateToChannelDashboard } from "@posthog/ui/router/navigationBridge";
import { track } from "@posthog/ui/shell/analytics";
import { logger } from "@posthog/ui/shell/logger";
@@ -27,6 +33,7 @@ const log = logger.scope("canvas-deep-link");
*/
export function useCanvasDeepLink() {
const trpcReact = useHostTRPC();
+ const tabsClient = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);
const isAuthenticated = useAuthStateValue(
(s) => s.status === "authenticated",
);
@@ -41,16 +48,25 @@ export function useCanvasDeepLink() {
}),
);
- const openCanvas = useCallback((channelId: string, dashboardId: string) => {
- log.info(
- `Opening canvas from deep link: channelId=${channelId} dashboardId=${dashboardId}`,
- );
- track(ANALYTICS_EVENTS.DEEP_LINK_CANVAS, {
- channel_id: channelId,
- dashboard_id: dashboardId,
- });
- navigateToChannelDashboard(channelId, dashboardId);
- }, []);
+ const openCanvas = useCallback(
+ (channelId: string, dashboardId: string) => {
+ log.info(
+ `Opening canvas from deep link: channelId=${channelId} dashboardId=${dashboardId}`,
+ );
+ track(ANALYTICS_EVENTS.DEEP_LINK_CANVAS, {
+ channel_id: channelId,
+ dashboard_id: dashboardId,
+ });
+ void focusOrOpenBrowserTab(tabsClient, {
+ href: `/spaces/${channelId}/dashboards/${dashboardId}`,
+ dashboardId,
+ }).then((handled) => {
+ if (handled) return;
+ navigateToChannelDashboard(channelId, dashboardId);
+ });
+ },
+ [tabsClient],
+ );
useEffect(() => {
const pending = pendingDeepLink.data;
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelDeepLink.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelDeepLink.ts
index 0235c24e7dac..be148742f32b 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelDeepLink.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelDeepLink.ts
@@ -1,6 +1,12 @@
+import { useService } from "@posthog/di/react";
import { useHostTRPC } from "@posthog/host-router/react";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "@posthog/ui/features/browser-tabs/browserTabsClient";
+import { focusOrOpenBrowserTab } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
import {
navigateToChannel,
navigateToChannelTask,
@@ -32,6 +38,7 @@ const log = logger.scope("channel-deep-link");
*/
export function useChannelDeepLink() {
const trpcReact = useHostTRPC();
+ const tabsClient = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);
const isAuthenticated = useAuthStateValue(
(s) => s.status === "authenticated",
);
@@ -46,20 +53,35 @@ export function useChannelDeepLink() {
}),
);
- const openChannel = useCallback((channelId: string, taskId?: string) => {
- log.info(
- `Opening channel from deep link: channelId=${channelId} taskId=${taskId ?? "-"}`,
- );
- track(ANALYTICS_EVENTS.DEEP_LINK_CHANNEL, {
- channel_id: channelId,
- task_id: taskId,
- });
- if (taskId) {
- navigateToChannelTask(channelId, taskId);
- } else {
- navigateToChannel(channelId);
- }
- }, []);
+ const openChannel = useCallback(
+ (channelId: string, taskId?: string) => {
+ log.info(
+ `Opening channel from deep link: channelId=${channelId} taskId=${taskId ?? "-"}`,
+ );
+ track(ANALYTICS_EVENTS.DEEP_LINK_CHANNEL, {
+ channel_id: channelId,
+ task_id: taskId,
+ });
+ void focusOrOpenBrowserTab(
+ tabsClient,
+ taskId
+ ? {
+ href: `/spaces/${channelId}/tasks/${taskId}`,
+ channelId,
+ taskId,
+ }
+ : { href: `/spaces/${channelId}`, channelId },
+ ).then((handled) => {
+ if (handled) return;
+ if (taskId) {
+ navigateToChannelTask(channelId, taskId);
+ } else {
+ navigateToChannel(channelId);
+ }
+ });
+ },
+ [tabsClient],
+ );
useEffect(() => {
const pending = pendingDeepLink.data;
diff --git a/products/desktop/packages/ui/src/features/deep-links/useHandleOpenTask.ts b/products/desktop/packages/ui/src/features/deep-links/useHandleOpenTask.ts
index b2238ffc5759..bb7fb47ba03d 100644
--- a/products/desktop/packages/ui/src/features/deep-links/useHandleOpenTask.ts
+++ b/products/desktop/packages/ui/src/features/deep-links/useHandleOpenTask.ts
@@ -91,8 +91,8 @@ export function useHandleOpenTask(): (
markAsViewed(taskId);
const channelTarget =
bluebirdEnabled && task.channel
- ? { channelId: task.channel }
- : undefined;
+ ? { channelId: task.channel, newTab: true }
+ : { newTab: true };
void openTaskHelper(task, channelTarget);
if (comment) {
useCommentNavigationStore
diff --git a/products/desktop/packages/ui/src/features/deep-links/useNewTaskDeepLink.ts b/products/desktop/packages/ui/src/features/deep-links/useNewTaskDeepLink.ts
index 3cd4ea143751..22bd29912b76 100644
--- a/products/desktop/packages/ui/src/features/deep-links/useNewTaskDeepLink.ts
+++ b/products/desktop/packages/ui/src/features/deep-links/useNewTaskDeepLink.ts
@@ -47,7 +47,7 @@ export function useNewTaskDeepLink() {
trackResolution(result.analytics);
if (result.kind === "navigate") {
- openTaskInput(result.navigation);
+ openTaskInput({ ...result.navigation, newTab: true });
return;
}
diff --git a/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.test.tsx b/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.test.tsx
index c3aacbf75eba..a2a9194e31b2 100644
--- a/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.test.tsx
+++ b/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.test.tsx
@@ -22,23 +22,14 @@ const onOpenTarget = vi.hoisted(() =>
const routerOpenTask = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
const navigateToChannelDashboard = vi.hoisted(() => vi.fn());
const markAsViewed = vi.hoisted(() => vi.fn());
-const readMirror = vi.hoisted(() => vi.fn());
-const reseedMirror = vi.hoisted(() => vi.fn());
-const historyPush = vi.hoisted(() => vi.fn());
-const getRouterOrNull = vi.hoisted(() => vi.fn());
+const focusOrOpenBrowserTab = vi.hoisted(() =>
+ vi.fn().mockResolvedValue("opened"),
+);
-vi.mock("@posthog/ui/features/browser-tabs/tabsSync", () => ({
- readMirror,
- reseedMirror,
+vi.mock("@posthog/ui/features/browser-tabs/imperativeTabNavigation", () => ({
+ focusOrOpenBrowserTab,
}));
-vi.mock("@posthog/ui/router/routerRef", () => ({ getRouterOrNull }));
-
-const seeded = (): { windows: unknown[]; tabs: unknown[] } => ({
- windows: [
- { id: "window-1", isPrimary: true, bounds: null, activeTabId: "tab-1" },
- ],
- tabs: [],
-});
+vi.mock("@posthog/di/react", () => ({ useService: () => ({ openTask }) }));
vi.mock("@posthog/host-router/react", () => ({
useHostTRPCClient: () => ({
@@ -56,7 +47,6 @@ vi.mock("@posthog/ui/router/useOpenTask", () => ({ openTask: routerOpenTask }));
vi.mock("@posthog/ui/features/sidebar/useTaskViewed", () => ({
useTaskViewed: () => ({ markAsViewed }),
}));
-vi.mock("@posthog/di/react", () => ({ useService: () => ({ openTask }) }));
vi.mock("@posthog/ui/shell/logger", () => ({
logger: { scope: () => ({ info: vi.fn(), error: vi.fn(), warn: vi.fn() }) },
}));
@@ -87,34 +77,31 @@ describe("useOpenTargetDeepLink", () => {
beforeEach(() => {
vi.clearAllMocks();
getPendingOpenTarget.mockResolvedValue(null);
- readMirror.mockReturnValue(seeded());
- reseedMirror.mockResolvedValue(null);
- getRouterOrNull.mockReturnValue({
- history: { location: { state: {} }, push: historyPush },
- });
+ focusOrOpenBrowserTab.mockResolvedValue(true);
});
it("routes a warm-start task target through the open-task saga", async () => {
renderHook(() => useOpenTargetDeepLink(), { wrapper });
onOpenTarget.mock.calls[0]?.[1]?.onData?.(taskTarget);
await waitFor(() => expect(openTask).toHaveBeenCalledWith("t1", undefined));
- expect(routerOpenTask).toHaveBeenCalledWith({ id: "t1" }, undefined);
+ expect(routerOpenTask).toHaveBeenCalledWith({ id: "t1" }, { newTab: true });
});
- it("routes a warm-start canvas target to its dashboard", async () => {
+ it("routes a warm-start canvas target to its own tab", async () => {
renderHook(() => useOpenTargetDeepLink(), { wrapper });
onOpenTarget.mock.calls[0]?.[1]?.onData?.(canvasTarget);
await waitFor(() =>
- expect(navigateToChannelDashboard).toHaveBeenCalledWith(
- "chan-1",
- "dash-1",
- ),
+ expect(focusOrOpenBrowserTab).toHaveBeenCalledWith(expect.anything(), {
+ href: "/spaces/chan-1/dashboards/dash-1",
+ dashboardId: "dash-1",
+ }),
);
});
- it("drains a pending target queued before the listener was live", async () => {
- getPendingOpenTarget.mockResolvedValue(canvasTarget);
+ it("falls back to in-tab navigation when browser tabs are unavailable", async () => {
+ focusOrOpenBrowserTab.mockResolvedValue(false);
renderHook(() => useOpenTargetDeepLink(), { wrapper });
+ onOpenTarget.mock.calls[0]?.[1]?.onData?.(canvasTarget);
await waitFor(() =>
expect(navigateToChannelDashboard).toHaveBeenCalledWith(
"chan-1",
@@ -123,61 +110,14 @@ describe("useOpenTargetDeepLink", () => {
);
});
- it("subscribes once to warm-start open-target events", () => {
- renderHook(() => useOpenTargetDeepLink(), { wrapper });
- expect(onOpenTarget).toHaveBeenCalledTimes(1);
- });
-
- const targetTab = {
- id: "tab-9",
- windowId: "window-1",
- href: "/tasks/t1",
- viewState: { title: "Task t1" },
- dashboardId: null,
- taskId: "t1",
- channelId: null,
- channelSection: null,
- appView: null,
- position: 1000,
- scrollState: null,
- createdAt: 1,
- lastActiveAt: 1,
- };
-
- it("focuses the tab that already shows the target instead of opening a copy", () => {
- readMirror.mockReturnValue({
- windows: seeded().windows,
- tabs: [targetTab],
- });
-
+ it("drains a pending target queued before the listener was live", async () => {
+ getPendingOpenTarget.mockResolvedValue(canvasTarget);
renderHook(() => useOpenTargetDeepLink(), { wrapper });
- onOpenTarget.mock.calls[0]?.[1]?.onData?.(taskTarget);
-
- expect(historyPush).toHaveBeenCalledWith("/tasks/t1", { tabId: "tab-9" });
- expect(openTask).not.toHaveBeenCalled();
- expect(routerOpenTask).not.toHaveBeenCalled();
+ await waitFor(() => expect(focusOrOpenBrowserTab).toHaveBeenCalled());
});
- it("focuses the target's tab after a cold-start mirror reseed", async () => {
- let reseeded = false;
- readMirror.mockImplementation(() =>
- reseeded
- ? { windows: seeded().windows, tabs: [targetTab] }
- : { windows: [], tabs: [] },
- );
- reseedMirror.mockImplementation(async () => {
- reseeded = true;
- return { windows: seeded().windows, tabs: [targetTab] };
- });
- getPendingOpenTarget.mockResolvedValue(taskTarget);
-
+ it("subscribes once to warm-start open-target events", () => {
renderHook(() => useOpenTargetDeepLink(), { wrapper });
-
- await waitFor(() =>
- expect(historyPush).toHaveBeenCalledWith("/tasks/t1", {
- tabId: "tab-9",
- }),
- );
- expect(openTask).not.toHaveBeenCalled();
+ expect(onOpenTarget).toHaveBeenCalledTimes(1);
});
});
diff --git a/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.ts b/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.ts
index 157431c49103..ee912442d868 100644
--- a/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.ts
+++ b/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.ts
@@ -1,13 +1,14 @@
+import { useService } from "@posthog/di/react";
import { useHostTRPCClient } from "@posthog/host-router/react";
import type { NotificationTarget } from "@posthog/platform/notifications";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "@posthog/ui/features/browser-tabs/browserTabsClient";
import {
type BrowserTabDestination,
- focusExistingTab,
+ focusOrOpenBrowserTab,
} from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
-import {
- readMirror,
- reseedMirror,
-} from "@posthog/ui/features/browser-tabs/tabsSync";
import { useHandleOpenTask } from "@posthog/ui/features/deep-links/useHandleOpenTask";
import {
navigateToChannelDashboard,
@@ -37,36 +38,29 @@ function targetDestination(target: NotificationTarget): BrowserTabDestination {
*/
export function useOpenTargetDeepLink() {
const client = useHostTRPCClient();
+ const tabsClient = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);
const handleOpenTask = useHandleOpenTask();
const handleTarget = useCallback(
(target: NotificationTarget) => {
log.info("Opening notification target", { kind: target.kind });
- const openDirectly = () => {
- switch (target.kind) {
- case "task":
- handleOpenTask(target.taskId, target.taskRunId);
- break;
- case "canvas":
+ switch (target.kind) {
+ case "task":
+ void handleOpenTask(target.taskId, target.taskRunId);
+ break;
+ case "canvas":
+ void focusOrOpenBrowserTab(
+ tabsClient,
+ targetDestination(target),
+ ).then((handled) => {
+ if (handled) return;
navigateToChannelDashboard(target.channelId, target.dashboardId);
- break;
- }
- };
-
- const destination = targetDestination(target);
- if (focusExistingTab(destination)) return;
- if (readMirror().windows.length > 0) {
- openDirectly();
- return;
+ });
+ break;
}
- void reseedMirror()
- .then(() => {
- if (!focusExistingTab(destination)) openDirectly();
- })
- .catch(() => openDirectly());
},
- [handleOpenTask],
+ [handleOpenTask, tabsClient],
);
// Expose the same channel-aware routing to imperative, non-React callers (the
diff --git a/products/desktop/packages/ui/src/features/deep-links/useTaskDeepLink.test.tsx b/products/desktop/packages/ui/src/features/deep-links/useTaskDeepLink.test.tsx
index 0f1b8ea4ae2e..4b5cb36198b2 100644
--- a/products/desktop/packages/ui/src/features/deep-links/useTaskDeepLink.test.tsx
+++ b/products/desktop/packages/ui/src/features/deep-links/useTaskDeepLink.test.tsx
@@ -88,28 +88,28 @@ describe("useTaskDeepLink", () => {
trigger: "pending" as const,
enabled: true,
channel: null,
- expected: undefined,
+ expected: { newTab: true },
},
{
name: "cold-start channel-filed task → its channel view",
trigger: "pending" as const,
enabled: true,
channel: "chan-1",
- expected: { channelId: "chan-1" },
+ expected: { channelId: "chan-1", newTab: true },
},
{
name: "cold-start filed task with flag off → /code",
trigger: "pending" as const,
enabled: false,
channel: "chan-1",
- expected: undefined,
+ expected: { newTab: true },
},
{
name: "warm-start channel-filed task → its channel view",
trigger: "warm" as const,
enabled: true,
channel: "chan-1",
- expected: { channelId: "chan-1" },
+ expected: { channelId: "chan-1", newTab: true },
},
])("$name", async ({ trigger, enabled, channel, expected }) => {
bluebirdState.enabled = enabled;
diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxDeepLink.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxDeepLink.ts
index c2914715db65..f767f418a967 100644
--- a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxDeepLink.ts
+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxDeepLink.ts
@@ -1,6 +1,12 @@
+import { useService } from "@posthog/di/react";
import { useHostTRPC } from "@posthog/host-router/react";
import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "@posthog/ui/features/browser-tabs/browserTabsClient";
+import { focusOrOpenBrowserTab } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
import { useOpenInboxReport } from "@posthog/ui/features/inbox/hooks/useOpenInboxReport";
import { navigateToInbox } from "@posthog/ui/router/navigationBridge";
import { useQuery } from "@tanstack/react-query";
@@ -22,6 +28,7 @@ import { useCallback, useEffect } from "react";
export function useInboxDeepLink() {
const trpcReact = useHostTRPC();
const client = useOptionalAuthenticatedClient();
+ const tabsClient = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);
const isAuthenticated = useAuthStateValue(
(s) => s.status === "authenticated",
);
@@ -30,12 +37,17 @@ export function useInboxDeepLink() {
const open = useCallback(
(reportId: string | null): void => {
if (reportId) {
- void openReport(reportId, { preserveSource: false });
+ void openReport(reportId, { preserveSource: false, newTab: true });
} else {
- navigateToInbox();
+ void focusOrOpenBrowserTab(tabsClient, { href: "/inbox" }).then(
+ (handled) => {
+ if (handled) return;
+ navigateToInbox();
+ },
+ );
}
},
- [openReport],
+ [openReport, tabsClient],
);
const pendingDeepLink = useQuery(
diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.ts
index e4dc4a5f9726..592cf5d1eeb5 100644
--- a/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.ts
+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useOpenInboxReport.ts
@@ -1,5 +1,11 @@
+import { useService } from "@posthog/di/react";
import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "@posthog/ui/features/browser-tabs/browserTabsClient";
+import { focusOrOpenBrowserTab } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
import { reportKeys } from "@posthog/ui/features/inbox/hooks/useInboxReports";
import { toast } from "@posthog/ui/primitives/toast";
import { navigateToReport } from "@posthog/ui/router/navigationBridge";
@@ -13,9 +19,13 @@ const log = logger.scope("open-inbox-report");
export function useOpenInboxReport() {
const queryClient = useQueryClient();
const client = useOptionalAuthenticatedClient();
+ const tabsClient = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);
return useCallback(
- async (reportId: string, options?: { preserveSource?: boolean }) => {
+ async (
+ reportId: string,
+ options?: { preserveSource?: boolean; newTab?: boolean },
+ ) => {
const sourceKey = getRouterOrNull()?.history.location.state.__TSR_key;
if (!client) {
log.warn("Ignoring open-report request – not authenticated");
@@ -39,6 +49,16 @@ export function useOpenInboxReport() {
if (getRouterOrNull()?.history.location.state.__TSR_key !== sourceKey)
return;
+ if (options?.newTab) {
+ const handled = await focusOrOpenBrowserTab(tabsClient, {
+ href: `/reports/${report.id}`,
+ appView: "report",
+ });
+ if (handled) {
+ log.info(`Successfully opened report: ${report.id}`);
+ return;
+ }
+ }
navigateToReport(report.id, options);
log.info(`Successfully opened report: ${report.id}`);
} catch (error) {
@@ -46,6 +66,6 @@ export function useOpenInboxReport() {
toast.error("Failed to open report");
}
},
- [client, queryClient],
+ [client, queryClient, tabsClient],
);
}
diff --git a/products/desktop/packages/ui/src/features/loops/hooks/useLoopDeepLink.ts b/products/desktop/packages/ui/src/features/loops/hooks/useLoopDeepLink.ts
index f79ca9235de6..2fa9a46f84c9 100644
--- a/products/desktop/packages/ui/src/features/loops/hooks/useLoopDeepLink.ts
+++ b/products/desktop/packages/ui/src/features/loops/hooks/useLoopDeepLink.ts
@@ -1,12 +1,19 @@
+import { useService } from "@posthog/di/react";
import { useHostTRPC } from "@posthog/host-router/react";
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "@posthog/ui/features/browser-tabs/browserTabsClient";
+import { focusOrOpenBrowserTab } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
import { navigateToLoopDetail } from "@posthog/ui/router/navigationBridge";
import { useQuery } from "@tanstack/react-query";
import { useSubscription } from "@trpc/tanstack-react-query";
-import { useEffect } from "react";
+import { useCallback, useEffect } from "react";
export function useLoopDeepLink() {
const trpcReact = useHostTRPC();
+ const tabsClient = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);
const isAuthenticated = useAuthStateValue(
(s) => s.status === "authenticated",
);
@@ -20,16 +27,29 @@ export function useLoopDeepLink() {
}),
);
+ const openLoop = useCallback(
+ (loopId: string): void => {
+ void focusOrOpenBrowserTab(tabsClient, {
+ href: `/loops/${loopId}`,
+ appView: "loops",
+ }).then((handled) => {
+ if (handled) return;
+ navigateToLoopDetail(loopId);
+ });
+ },
+ [tabsClient],
+ );
+
useEffect(() => {
if (pendingDeepLink.data?.loopId) {
- navigateToLoopDetail(pendingDeepLink.data.loopId);
+ openLoop(pendingDeepLink.data.loopId);
}
- }, [pendingDeepLink.data]);
+ }, [pendingDeepLink.data, openLoop]);
useSubscription(
trpcReact.deepLink.onOpenLoop.subscriptionOptions(undefined, {
onData: (data) => {
- if (data?.loopId) navigateToLoopDetail(data.loopId);
+ if (data?.loopId) openLoop(data.loopId);
},
}),
);
diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.ts
index 8169f32e69bf..ba67d0aef0bd 100644
--- a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.ts
+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.ts
@@ -1,7 +1,16 @@
+import { useService } from "@posthog/di/react";
import { useHostTRPC } from "@posthog/host-router/react";
import { agentsPageActions } from "@posthog/ui/features/agents/agentsPageStore";
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
-import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "@posthog/ui/features/browser-tabs/browserTabsClient";
+import { focusOrOpenBrowserTab } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
+import {
+ openSettings,
+ prepareSettingsPage,
+} from "@posthog/ui/features/settings/hooks/useOpenSettings";
import { logger } from "@posthog/ui/shell/logger";
import { useQuery } from "@tanstack/react-query";
import { useSubscription } from "@trpc/tanstack-react-query";
@@ -20,6 +29,7 @@ const log = logger.scope("scout-deep-link");
*/
export function useScoutDeepLink() {
const trpcReact = useHostTRPC();
+ const tabsClient = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);
const isAuthenticated = useAuthStateValue(
(s) => s.status === "authenticated",
);
@@ -34,16 +44,26 @@ export function useScoutDeepLink() {
}),
);
- const openScout = useCallback((skillSlug: string, findingId?: string) => {
- log.info(
- `Opening scout from deep link: skillSlug=${skillSlug} findingId=${findingId ?? "(none)"}`,
- );
- // 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 });
- }, []);
+ const openScout = useCallback(
+ (skillSlug: string, findingId?: string) => {
+ log.info(
+ `Opening scout from deep link: skillSlug=${skillSlug} findingId=${findingId ?? "(none)"}`,
+ );
+ const destination = {
+ href: "/settings/agents",
+ appView: "settings" as const,
+ };
+ void focusOrOpenBrowserTab(tabsClient, destination).then((handled) => {
+ if (!handled) {
+ openSettings("agents");
+ } else {
+ prepareSettingsPage();
+ }
+ agentsPageActions().openAgent(skillSlug, { findingId });
+ });
+ },
+ [tabsClient],
+ );
useEffect(() => {
if (pendingDeepLink.data?.skillSlug) {
diff --git a/products/desktop/packages/ui/src/router/useOpenTask.ts b/products/desktop/packages/ui/src/router/useOpenTask.ts
index ca1f2b400962..1f8bc88b7e24 100644
--- a/products/desktop/packages/ui/src/router/useOpenTask.ts
+++ b/products/desktop/packages/ui/src/router/useOpenTask.ts
@@ -2,7 +2,15 @@ import type { EditorContent } from "@posthog/core/message-editor/content";
import { resolveService, resolveServiceOptional } from "@posthog/di/container";
import { ANALYTICS_EVENTS } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
-import { navigateBrowserTab } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "@posthog/ui/features/browser-tabs/browserTabsClient";
+import {
+ focusOrOpenBrowserTab,
+ navigateBrowserTab,
+ openInNewBrowserTabSync,
+} from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";
import {
NAVIGATION_TASK_BINDER,
@@ -34,7 +42,11 @@ import * as nav from "./navigationBridge";
*/
export async function openTask(
task: Task,
- opts?: { channelId?: string; tabId?: string | null },
+ opts?: {
+ channelId?: string;
+ tabId?: string | null;
+ newTab?: boolean;
+ },
): Promise<void> {
// Seed the detail cache so the route loader resolves from cache and never
// fetches — critical for optimistic/local/cloud-pending tasks that the API
@@ -46,14 +58,28 @@ export async function openTask(
const href = opts?.channelId
? `/spaces/${opts.channelId}/tasks/${task.id}`
: `/tasks/${task.id}`;
+ const destination = {
+ href,
+ title: task.title,
+ taskId: task.id,
+ channelId: opts?.channelId ?? null,
+ };
+
+ if (opts?.newTab) {
+ const tabsClient =
+ resolveServiceOptional<BrowserTabsClient>(BROWSER_TABS_CLIENT);
+ if (tabsClient) {
+ const handled = await focusOrOpenBrowserTab(tabsClient, destination);
+ if (handled) {
+ await bindTaskWorkspace(task, opts);
+ return;
+ }
+ }
+ }
+
const navigationResult = navigateBrowserTab(
opts?.tabId ?? null,
- {
- href,
- title: task.title,
- taskId: task.id,
- channelId: opts?.channelId ?? null,
- },
+ destination,
() => {
if (opts?.channelId) {
nav.navigateToChannelTask(opts.channelId, task.id);
@@ -67,6 +93,13 @@ export async function openTask(
track(ANALYTICS_EVENTS.TASK_VIEWED, { task_id: task.id });
}
+ await bindTaskWorkspace(task, opts);
+}
+
+async function bindTaskWorkspace(
+ task: Task,
+ opts?: { tabId?: string | null },
+): Promise<void> {
const result = await resolveServiceOptional<NavigationTaskBinder>(
NAVIGATION_TASK_BINDER,
)?.ensureWorkspaceForTask(task);
@@ -122,6 +155,7 @@ export interface TaskInputNavigationOptions {
* routing through here is what clears any stale prefill.
*/
channelId?: string;
+ newTab?: boolean;
}
/**
@@ -136,7 +170,6 @@ export function openTaskInput(
typeof folderIdOrOptions === "string"
? { folderId: folderIdOrOptions }
: (folderIdOrOptions ?? {});
-
// The folder prefill counts as transient state: each "+" click must get a
// fresh requestId so re-picking the same group re-applies the prefill.
const hasTransientState =
@@ -177,6 +210,12 @@ export function openTaskInput(
(options.unscoped
? null
: useCurrentChannelStore.getState().currentChannelId);
+ if (options.newTab) {
+ const tabsClient =
+ resolveServiceOptional<BrowserTabsClient>(BROWSER_TABS_CLIENT);
+ const href = channelId ? `/spaces/${channelId}/new` : "/new";
+ if (tabsClient && openInNewBrowserTabSync(tabsClient, { href })) return;
+ }
if (channelId) nav.navigateToChannelNewTask(channelId);
else nav.navigateToNewTask();
}