: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): focus the open tab when a notification is clicked (#96118)
Shy Alter8ce7aead6167
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.tsindex fd3bab4b9da5..993039944513 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,6 +1,7 @@import type { TabsSnapshot } from "@posthog/shared";import { beforeEach, describe, expect, it, vi } from "vitest";import {+ focusExistingTab,getCurrentBrowserTabId,navigateBrowserTab,} from "./imperativeTabNavigation";@@ -136,3 +137,62 @@ describe("imperative browser-tab navigation", () => {expect(fallback).toHaveBeenCalledOnce();});});++describe("focusExistingTab", () => {+ const history = { location: { state: { tabId: "tab-b" } }, push: vi.fn() };++ beforeEach(() => {+ vi.clearAllMocks();+ history.location.state.tabId = "tab-b";+ mocks.getRouterOrNull.mockReturnValue({ history });+ mocks.readMirror.mockReturnValue(snapshot());+ });++ it("pushes a tagged history entry for an existing tab on the destination", () => {+ const push = vi.fn();+ mocks.getRouterOrNull.mockReturnValue({ history: { ...history, push } });++ expect(focusExistingTab({ href: "/new" })).toBe(true);+ expect(push).toHaveBeenCalledWith("/new", { tabId: "tab-a" });+ });++ it("reports a match without navigating when the active tab already shows it", () => {+ history.location.state.tabId = "tab-a";++ expect(focusExistingTab({ href: "/new" })).toBe(true);+ });++ it("keeps the active tab when an earlier tab shows the same destination", () => {+ const mirror = snapshot();+ mirror.tabs[0] = { ...mirror.tabs[0], href: "/tasks/task-1" };+ mirror.tabs[1] = { ...mirror.tabs[1], href: "/tasks/task-1" };+ mocks.readMirror.mockReturnValue(mirror);+ const push = vi.fn();+ mocks.getRouterOrNull.mockReturnValue({ history: { ...history, push } });++ expect(focusExistingTab({ href: "/tasks/task-1" })).toBe(true);+ expect(push).not.toHaveBeenCalled();+ });++ it("returns false when no tab shows the destination", () => {+ expect(focusExistingTab({ href: "/tasks/other" })).toBe(false);+ });++ it.each([+ { name: "the channel route form", href: "/spaces/chan-9/tasks/task-9" },+ { name: "a null href", href: null },+ ])("matches a task tab on its id across $name", ({ href }) => {+ const mirror = snapshot();+ mirror.tabs[0] = { ...mirror.tabs[0], href, taskId: "task-9" };+ mocks.readMirror.mockReturnValue(mirror);+ const push = vi.fn();+ mocks.getRouterOrNull.mockReturnValue({ history: { ...history, push } });++ expect(focusExistingTab({ href: "/tasks/task-9", taskId: "task-9" })).toBe(+ true,+ );+ expect(push).toHaveBeenCalledWith(href ?? "/tasks/task-9", {+ tabId: "tab-a",+ });+ });+});diff --git a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.tsindex b56af693b54d..470efb729572 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts+++ b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts@@ -1,8 +1,11 @@import {+ type BrowserTab,+ primaryWindow,setTabTarget as setTabTargetLocal,type TabIdentity,} from "@posthog/shared";import { getRouterOrNull } from "@posthog/ui/router/routerRef";+import { pushTabHistoryEntry } from "./tabHistory";import { applyLocalTransform, persistTabTarget, readMirror } from "./tabsSync";export interface BrowserTabDestination extends Partial<TabIdentity> {@@ -26,6 +29,40 @@ export function isBrowserTabOpen(tabId: string | null): boolean {return readMirror().tabs.some((candidate) => candidate.id === tabId);}+function tabShowsDestination(+ tab: BrowserTab,+ dest: BrowserTabDestination,+): boolean {+ if (dest.taskId) return tab.taskId === dest.taskId;+ if (dest.dashboardId) return tab.dashboardId === dest.dashboardId;+ return tab.href === dest.href;+}++export function focusExistingTab(destination: BrowserTabDestination): boolean {+ const mirror = readMirror();+ const window = primaryWindow(mirror);+ const history = getRouterOrNull()?.history;+ if (!window || !history) return false;++ const matchesDestination = (candidate: BrowserTab) =>+ candidate.windowId === window.id &&+ tabShowsDestination(candidate, destination);++ // Tabs are not deduplicated, so several tabs can show one target. Keep the+ // active tab when it is one of them, instead of a switch to an older twin.+ const activeTabId = history.location.state.tabId;+ const activeTab = mirror.tabs.find(+ (candidate) => candidate.id === activeTabId,+ );+ if (activeTab && matchesDestination(activeTab)) return true;++ const tab = mirror.tabs.find(matchesDestination);+ if (!tab) return false;++ pushTabHistoryEntry(history, tab.href ?? destination.href, tab.id);+ return true;+}+/*** Move one browser tab to a new route without stealing focus from another tab.* Active tabs use router history; background tabs update their durable targetdiff --git a/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.test.tsx b/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.test.tsxindex 0b0352f1fadc..c3aacbf75eba 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,6 +22,23 @@ 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());++vi.mock("@posthog/ui/features/browser-tabs/tabsSync", () => ({+ readMirror,+ reseedMirror,+}));+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/host-router/react", () => ({useHostTRPCClient: () => ({@@ -70,6 +87,11 @@ describe("useOpenTargetDeepLink", () => {beforeEach(() => {vi.clearAllMocks();getPendingOpenTarget.mockResolvedValue(null);+ readMirror.mockReturnValue(seeded());+ reseedMirror.mockResolvedValue(null);+ getRouterOrNull.mockReturnValue({+ history: { location: { state: {} }, push: historyPush },+ });});it("routes a warm-start task target through the open-task saga", async () => {@@ -79,10 +101,15 @@ describe("useOpenTargetDeepLink", () => {expect(routerOpenTask).toHaveBeenCalledWith({ id: "t1" }, undefined);});- it("routes a warm-start canvas target to its dashboard", () => {+ it("routes a warm-start canvas target to its dashboard", async () => {renderHook(() => useOpenTargetDeepLink(), { wrapper });onOpenTarget.mock.calls[0]?.[1]?.onData?.(canvasTarget);- expect(navigateToChannelDashboard).toHaveBeenCalledWith("chan-1", "dash-1");+ await waitFor(() =>+ expect(navigateToChannelDashboard).toHaveBeenCalledWith(+ "chan-1",+ "dash-1",+ ),+ );});it("drains a pending target queued before the listener was live", async () => {@@ -100,4 +127,57 @@ describe("useOpenTargetDeepLink", () => {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],+ });++ 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();+ });++ 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);++ renderHook(() => useOpenTargetDeepLink(), { wrapper });++ await waitFor(() =>+ expect(historyPush).toHaveBeenCalledWith("/tasks/t1", {+ tabId: "tab-9",+ }),+ );+ expect(openTask).not.toHaveBeenCalled();+ });});diff --git a/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.ts b/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.tsindex cf9762c8a502..157431c49103 100644--- a/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.ts+++ b/products/desktop/packages/ui/src/features/deep-links/useOpenTargetDeepLink.ts@@ -1,5 +1,13 @@import { useHostTRPCClient } from "@posthog/host-router/react";import type { NotificationTarget } from "@posthog/platform/notifications";+import {+ type BrowserTabDestination,+ focusExistingTab,+} 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,@@ -10,6 +18,18 @@ import { useCallback, useEffect } from "react";const log = logger.scope("open-target-deep-link");+function targetDestination(target: NotificationTarget): BrowserTabDestination {+ switch (target.kind) {+ case "task":+ return { href: `/tasks/${target.taskId}`, taskId: target.taskId };+ case "canvas":+ return {+ href: `/spaces/${target.channelId}/dashboards/${target.dashboardId}`,+ dashboardId: target.dashboardId,+ };+ }+}+/*** Consumes generic "open this target" intents emitted when a native* notification is clicked (any tier, any producer) and navigates by target@@ -22,14 +42,29 @@ export function useOpenTargetDeepLink() {const handleTarget = useCallback((target: NotificationTarget) => {log.info("Opening notification target", { kind: target.kind });- switch (target.kind) {- case "task":- handleOpenTask(target.taskId, target.taskRunId);- break;- case "canvas":- navigateToChannelDashboard(target.channelId, target.dashboardId);- break;++ const openDirectly = () => {+ switch (target.kind) {+ case "task":+ handleOpenTask(target.taskId, target.taskRunId);+ break;+ case "canvas":+ navigateToChannelDashboard(target.channelId, target.dashboardId);+ break;+ }+ };++ const destination = targetDestination(target);+ if (focusExistingTab(destination)) return;+ if (readMirror().windows.length > 0) {+ openDirectly();+ return;}+ void reseedMirror()+ .then(() => {+ if (!focusExistingTab(destination)) openDirectly();+ })+ .catch(() => openDirectly());},[handleOpenTask],);