:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): tile browser tabs side by side or in a grid (#102062)
Shy Alter67528e1af08c
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex b3c7fbe3e68f..ddf78ed3da5f 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -346,6 +346,16 @@ export interface TaskListGroupingChangedProperties {surface: TaskListSurface;}+export interface BrowserTabTiledProperties {+ edge: "left" | "right" | "top" | "bottom";+ source: "strip" | "tile" | "sidebar";+ tile_count: number;+}++export interface BrowserTabTileCountProperties {+ tile_count: number;+}+export interface TaskListAppearanceChangedProperties {secondary_fields: ("repository" | "branch" | "creator" | "activity")[];secondary_field_count: number;@@ -1615,6 +1625,10 @@ export const ANALYTICS_EVENTS = {SIDEBAR_NAV_ITEM_CLICKED: "Sidebar nav item clicked",TASK_LIST_GROUPING_CHANGED: "Task list grouping changed",TASK_LIST_APPEARANCE_CHANGED: "Task list appearance changed",+ BROWSER_TAB_TILED: "Browser tab tiled",+ BROWSER_TAB_UNTILED: "Browser tab untiled",+ BROWSER_TAB_TILE_FOCUSED: "Browser tab tile focused",+ BROWSER_TAB_SPLIT_RENAMED: "Browser tab split renamed",// Permission eventsPERMISSION_RESPONDED: "Permission responded",@@ -1828,6 +1842,10 @@ export type EventPropertyMap = {[ANALYTICS_EVENTS.SIDEBAR_NAV_ITEM_CLICKED]: SidebarNavItemClickedProperties;[ANALYTICS_EVENTS.TASK_LIST_GROUPING_CHANGED]: TaskListGroupingChangedProperties;[ANALYTICS_EVENTS.TASK_LIST_APPEARANCE_CHANGED]: TaskListAppearanceChangedProperties;+ [ANALYTICS_EVENTS.BROWSER_TAB_TILED]: BrowserTabTiledProperties;+ [ANALYTICS_EVENTS.BROWSER_TAB_UNTILED]: BrowserTabTileCountProperties;+ [ANALYTICS_EVENTS.BROWSER_TAB_TILE_FOCUSED]: BrowserTabTileCountProperties;+ [ANALYTICS_EVENTS.BROWSER_TAB_SPLIT_RENAMED]: BrowserTabTileCountProperties;// Permission events[ANALYTICS_EVENTS.PERMISSION_RESPONDED]: PermissionRespondedProperties;diff --git a/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.md b/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.mdindex 8f164894c46d..94bdc544ee21 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.md+++ b/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.md@@ -153,8 +153,15 @@ differ. Desktop ships first.partition.### Drag to reorder-- Pills are `@dnd-kit/react` sortables (x-axis–locked, full-opacity preview),- split into two sortable groups so a drag can't cross the pinned boundary.+- Pills are `@dnd-kit/react` sortables (full-opacity preview), split into two+ sortable groups so a drag can't cross the pinned boundary. The `DetachFromStrip`+ modifier (`tabDetach.ts`) holds the pill in the row until the pointer has+ moved `DETACH_DISTANCE` (one pill height, as Chrome does) up or down; then+ the pill follows the pointer in both axes and snaps back into the row if the+ pointer returns. `BrowserTabsDndProvider` mirrors that threshold into+ `tabReorderStore.detached` on `dragmove` (measured from the pointer at+ dragstart, because dnd-kit's event snapshot has no `position.delta`), and+ `dragover` skips the reorder while detached.- The in-flight preview lives in a **transient view store** (`tabReorderStore`),never in the domain snapshot mirror: `dragover` reorders the previewed*stored* order **within the dragged tab's pin group only** (`reorderWithinGroup`@@ -304,44 +311,36 @@ retarget its originating background tab as described below. `railHistoryStore`- Full back/forward integration across the real router belongs in an E2E(Playwright) spec, not a unit test.-## Split view (parked — how to approach it)--A working prototype (July 2026, since removed — recoverable from git history)-let a pill be dragged off the strip onto right/bottom drop zones over the-content area, splitting the scene into a resizable two-pane-`react-resizable-panels` group. What we learned, for whoever picks it up:--- **The constraint:** one TanStack Router = one location = one `<Outlet>`.- Two panes can't both be routes. Three ways out, in order of preference:- 1. **Router-less target pane** (what the prototype did): the secondary pane- renders the tab's target directly by id. `WebsiteDashboard` already takes- `dashboardId` as a prop and `TaskDetail` takes a `task` (replicate the- cache-first fetch from `routes/_shell/spaces/$channelId/tasks/$taskId.tsx`) —- both mount standalone today. **Channel views (inbox/artifacts/…) are the- blocker**: they read route params/loaders throughout, so they need a- props-parameterization pass before they can render in a pane. That- refactor is most of the remaining work.- 2. **Second router over memory history** — renders any route, but needs a- chrome-less root and confuses the tab-strip navigation effect- (`decideTabNavigation` assumes one router).- 3. **Tear-off to a second OS window** — the tabs data model already supports- it (`browser_windows`, secondary-window close semantics in- `closeTab`/`closeTabs`); Electron-only.-- **Wiring that already exists and stays:** `BrowserTabsDndProvider` wraps the- channels chrome, so drop zones over the content area just register- `useDroppable` targets in the same scope; pill drag data is- `{ type: "browser-tab", tabId }`. The prototype's pieces were a persisted- `splitViewStore` (identity + direction + transient `isDraggingTab`), a- `TabSplitLayout` wrapper around the outlet box in `__root.tsx`, and a- split-zone branch in the provider's `dragend`.-- **UX decisions already settled:** zones are right 35% / bottom 35%- (non-overlapping), a second drop replaces the split, a blank tab is- rejected, the split persists across relaunch, and a header X closes it.-- **Open questions for the real version:** should the split pane get its own- tab strip (it probably wants the panels feature's tree model instead of a- single-pane store); how does the active-tab highlight relate to the- secondary pane; and whether in-pane navigation should be possible at all- without a router.+## Tiled tabs (split view)++Tabs can share the content pane side by side or in a grid.+The feature lives in `features/tab-tiling/`; this section keeps the model and the UX in step with the code.++### The model (`tileTree.ts`)+- A **group** is a tree. Leaves are tab ids; inner nodes split their children along one axis (`horizontal` = side by side, `vertical` = stacked) and carry optional `sizes` in percent.+- `tileTab` places a tab on an edge of the tile that shows another tab. A drop on the axis the parent already splits on adds a sibling, so three tabs in a row stay one flat split. A tab that was tiled elsewhere leaves its old group first. A group stops accepting drops at `MAX_TILES_PER_GROUP` (4).+- `untileTab` removes a leaf, collapses a split left with one child, and dissolves a group left with one tile. `pruneGroups` applies that to every tab missing from the live snapshot.+- Groups, the focused tile per group (`activeByGroup`) and the split names are **view state** in `tileLayoutStore` (zustand `persist` to localStorage). Every group has a name: `Split N` until someone renames it. The tree transforms are unit-tested in `tileTree.test.ts`.++### Rendering (`TileLayout.tsx`)+- Every tile renders its tab through `TileTabContent`, and stays mounted whichever tile is focused. A task tab mounts `TaskDetail`, a canvas tab mounts `WebsiteDashboard`, and any other tab mounts its page in its own TanStack router over a memory history seeded at the tab's href (`TileRouter`). The root route renders only its outlet inside a tile (`useInTile`), and a navigation inside a tile writes the new href back onto the tab.+- **Focusing a tile is not a navigation.** The route, the history and the side nav stay where they are; `useFocusTab` records the tile in `activeByGroup`, and `useActiveTabId` resolves the focused member of the route's group. A tab switch into another group still navigates.+- A plain navigation made while a split is on screen lands in the focused tile, not in the tab that owns the route (`navigationOwner` in `BrowserTabStrip`).+- Each tile has a `ChromeBar` header: the tab's grip, icon and title, an X that removes the tile from the split, and on a task its `TaskHeaderActions`. The header is plain until dragged; only the drag ghost takes the pill styling.+- `useSetHeaderContent` writes nothing from inside a tile, so the pane-wide header never names one tile's page above several tiles. `TaskDetail` keeps its hotkeys only in the focused tile (`useInUnfocusedTile`).++### Moving tiles+- The tile header is a `@dnd-kit/react` draggable (`tile-tab`). Dropping it on another tile's edge moves it there. Dropping it on the strip pulls it out as its own tab; while the ghost is over the strip, the tab previews as a pill in the slot it would take (`tabReorderStore.previewOrder` while `dragSource` is `tile`).+- Session and canvas rows in the sidebar are native HTML5 drags (they already drop onto Command Center). `TileDropZones` accept them too: the drop opens the task or canvas as a background tab and tiles it beside the target (`tileDrop.ts`).+- The dragged tile shows no zones on itself, and a full group disables its zones.++### The split in the strip+- `collapseSplits` (`displayOrder.ts`) keeps one pill per group in the slot of its first member (the **anchor**); the other members leave the strip.+- The pill is a normal pill: a split icon, the group's name, the hover close. Its tooltip lists the name and the tabs inside, the one on screen in full color. Click it to return to the split on the focused tile. `Rename split` in its menu edits the name inline; `Separate all tabs` dissolves the group.+- The X, middle-click and `Close split` close every tab of the split. Cmd/Ctrl+W closes the focused tile only.++### Analytics+- `Browser tab tiled` (`edge`, `source`: strip, tile or sidebar, `tile_count`), `Browser tab untiled` (`tile_count`), `Browser tab tile focused` (`tile_count`), `Browser tab split renamed` (`tile_count`).## Known rough edges / follow-upsdiff --git a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsxindex ed31c9c9b494..93adf98a0f67 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx+++ b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx@@ -2,6 +2,7 @@ import { MagnifyingGlassIcon } from "@phosphor-icons/react";import { humanizeReportTitle } from "@posthog/core/inbox/reportPresentation";import { useService } from "@posthog/di/react";import {+ type BrowserTab,closeTab as closeTabLocal,closeTabs as closeTabsLocal,DEFAULT_TAB_HREF,@@ -15,6 +16,7 @@ import {type TabsSnapshot,type TabViewState,} from "@posthog/shared";+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import { channelSectionFor } from "@posthog/ui/features/canvas/channelSections";import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";import { channelGlyph } from "@posthog/ui/features/canvas/components/channelGlyph";@@ -38,17 +40,26 @@ import {import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";import { feedIdFromHref } from "@posthog/ui/features/canvas/stores/taskFeedSelectionStore";import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";-import { useChannelReportsEnabled } from "@posthog/ui/features/feature-flags/useChannelReportsEnabled";import { useInboxReportById } from "@posthog/ui/features/inbox/hooks/useInboxReports";import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";import { useTabSession } from "@posthog/ui/features/navigation/useActiveSession";import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";import { getLeafPanel } from "@posthog/ui/features/panels/panelStoreHelpers";+import { useTileLayoutStore } from "@posthog/ui/features/tab-tiling/tileLayoutStore";+import {+ focusedTabIn,+ groupForTab,+ lastActiveIn,+ tabIdsIn,+ untileTab,+} from "@posthog/ui/features/tab-tiling/tileTree";+import { useFocusTab } from "@posthog/ui/features/tab-tiling/useFocusTab";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 { track } from "@posthog/ui/shell/analytics";import { isMac } from "@posthog/ui/utils/platform";import { useQuery } from "@tanstack/react-query";import {@@ -65,6 +76,7 @@ import {type BrowserTabsClient,} from "./browserTabsClient";import {+ collapseSplits,frontOfUnpinnedOrder,partitionPinnedFirst,storedOrderIds,@@ -79,10 +91,11 @@ import {TAB_APP_VIEW_META,type TabAppView,} from "./tabAppViews";-import { pushTabHistoryEntry } from "./tabHistory";import { useTabReorderStore } from "./tabReorderStore";import { applyLocalTransform, persistWrite, readMirror } from "./tabsSync";+import { useActiveTabId } from "./useActiveTabId";import { useTabsSnapshot } from "./useBrowserTabs";+import { useGoToTab } from "./useGoToTab";import { useOpenBrowserTab } from "./useOpenBrowserTab";/**@@ -121,16 +134,17 @@ function taskHasCloseableEditorTab(taskId: string | undefined): boolean {return !!activeTab && activeTab.closeable !== false;}-type TabRef = {- id: string;- /** Where the tab is. Null only for tabs persisted before hrefs were stored. */- href: string | null;- dashboardId: string | null;- taskId: string | null;- channelId: string | null;- channelSection: string | null;- appView: string | null;-};+function navigationOwner(+ settledTabId: string | null,+ windowActive: { id: string; href: string | null } | null,+ href: string,+): string | null {+ if (!windowActive) return null;+ const isSwitch = settledTabId !== null && settledTabId !== windowActive.id;+ if (isSwitch || windowActive.href === href) return windowActive.id;+ const { groups, activeByGroup } = useTileLayoutStore.getState();+ return focusedTabIn(groups, activeByGroup, windowActive.id);+}function BrowserTabStripImpl() {const spacesLayout = useChannelsLayout();@@ -147,12 +161,6 @@ function BrowserTabStripImpl() {reportId?: string;};const routeFeedId = params.feedId ?? null;- // The in-flight tag: flips the instant you navigate, so the strip's highlight- // and the active tab's name don't lag a navigation behind. Rendering only —- // the effect below must not write from it (see settledLocation).- const historyTabId = useRouterState({- select: (s) => s.location.state.tabId,- });const pathname = useRouterState({ select: (s) => s.location.pathname });// What the effect reconciles against: the settled href and the tab that entry// belongs to, read from one snapshot (see settledLocation for why that@@ -196,7 +204,7 @@ function BrowserTabStripImpl() {scopedSpaceId === null && channelsLoading ? undefined : scopedSpaceId;// With channel reports on, a restored inbox tab lands on the spaces index// (the inbox is gone as a destination).- const channelReportsEnabled = useChannelReportsEnabled();+ const goToTab = useGoToTab();// The active channel sub-section (artifacts/history/context) is the// route segment after the channelId. Null when on the channel home or a@@ -220,6 +228,14 @@ function BrowserTabStripImpl() {// Transient reorder preview (set while a pill is dragged); overrides the// strip's order without touching the domain snapshot mirror.const previewOrder = useTabReorderStore((s) => s.previewOrder);+ const tileGroups = useTileLayoutStore((s) => s.groups);+ const activeByGroup = useTileLayoutStore((s) => s.activeByGroup);+ const groupNames = useTileLayoutStore((s) => s.names);+ const stripPreviewTabId = useTabReorderStore((s) =>+ s.dragSource === "tile" && s.previewOrder ? s.draggingTabId : null,+ );+ const separateGroup = useTileLayoutStore((s) => s.separate);+ const renameGroup = useTileLayoutStore((s) => s.renameGroup);// Drop pins for tabs that no longer exist (closed here or in another// window). Skip the pre-seed empty snapshot so a slow boot doesn't wipe pins.useEffect(() => {@@ -229,16 +245,8 @@ function BrowserTabStripImpl() {const win = primaryWindow(snapshot);const windowId = win?.id;- // The history state flips the instant you navigate, while the server snapshot- // round-trips — so prefer it for "which tab is active" to avoid a one-step lag- // in the highlight and the name. Validate it against the live tab list first:- // back/forward can replay an entry tagged with a since-closed tab, and a dead- // id here would blank the strip highlight and point Cmd+W at a tab that no- // longer exists (the navigation effect heals the tag, but asynchronously).- const historyTabIsLive =- !!historyTabId && snapshot.tabs.some((t) => t.id === historyTabId);- const activeTabId =- (historyTabIsLive ? historyTabId : null) ?? win?.activeTabId ?? null;+ const activeTabId = useActiveTabId();+ const focusTab = useFocusTab(activeTabId);const feeds = useProjectTaskFeeds();const feedName = useMemo(() => {@@ -373,8 +381,12 @@ function BrowserTabStripImpl() {const mirror = readMirror();const mirrorWin = primaryWindow(mirror);const mirrorTabs = mirror.tabs.filter((t) => t.windowId === windowId);- const mirrorActive = mirrorWin?.activeTabId- ? mirrorTabs.find((t) => t.id === mirrorWin.activeTabId)+ const windowActive = mirrorWin?.activeTabId+ ? (mirrorTabs.find((t) => t.id === mirrorWin.activeTabId) ?? null)+ : null;+ const ownerId = navigationOwner(settledTabId, windowActive, locationHref);+ const mirrorActive = ownerId+ ? mirrorTabs.find((t) => t.id === ownerId): undefined;// The label/icon cache written alongside the location. Never the thing the// decision is made on: it is all-null outside its vocabulary, so two@@ -413,12 +425,13 @@ function BrowserTabStripImpl() {// The SETTLED tag, not the in-flight one. Pairing the in-flight tag with// the settled href tells the effect "tab B is on tab A's href", and it// dutifully writes A's href onto B.- historyTabId: settledTabId,+ historyTabId:+ ownerId && ownerId !== mirrorWin?.activeTabId ? ownerId : settledTabId,// Validates history tags: back/forward can replay an entry tagged with a// closed tab; activating that dead id would persist a dangling// activeTabId, after which every nav "opens" (no active tab found).windowTabIds: mirrorTabs.map((t) => t.id),- serverActiveTabId: mirrorWin?.activeTabId ?? null,+ serverActiveTabId: ownerId,activeTab: mirrorActive? {id: mirrorActive.id,@@ -551,123 +564,145 @@ function BrowserTabStripImpl() {...stored.filter((id) => !seen.has(id)),];}- return partitionPinnedFirst(base, pinnedTabIds)- .map((id) => byId.get(id))- .filter((t) => t !== undefined)- .map((t): TabView => {- const pinned = pinnedSet.has(t.id);- // The active tab shows the current route's target, so resolve from the- // route (instant) rather than its stored ids (which lag a navigation).- const isActive = t.id === activeTabId;- const taskId = isActive ? (activeSession.taskId ?? null) : t.taskId;- const dashId = isActive ? (params.dashboardId ?? null) : t.dashboardId;- const channelId = isActive- ? (params.channelId ?? activeSession.channelId ?? null)- : t.channelId;- const section = isActive ? routeChannelSection : t.channelSection;- const appView = isActive ? routeAppView : t.appView;- const channel = channelName(channelId);- const feedId = isActive ? routeFeedId : feedIdFromHref(t.href);- if (feedId) {- return {- id: t.id,- label: feedName(feedId) ?? t.viewState?.title ?? "Saved search",- icon: <MagnifyingGlassIcon size={14} />,- channelName: null,- pinned,- };- }- if (taskId) {- const task = findTask(taskId);- return {- id: t.id,- label:- task?.title ??- taskInfo.get(taskId) ??- t.viewState?.title ??- "Task",- // The session list's status dot, so a tab and its row never say- // different things about the same session.- icon: <TaskTabDot task={task} />,- channelName: channel,- pinned,- };- }- if (dashId) {- const info = resolveCanvas(dashId);- return {- id: t.id,- label: info?.name ?? t.viewState?.title ?? "Canvas",- icon: iconForTemplate(info?.templateId ?? "freeform", {- size: 14,- }),- channelName: channel,- pinned,- };- }- // A top-level app page (Inbox, Agents, Skills, …).- // Resolve this before channel state: when navigation crosses from a- // space to Activity, persisted channel context must not turn the new- // top-level tab into a space tab.- if (appView && isTabAppView(appView)) {- 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, reportTab);- return {- id: t.id,- ...display,- channelName: null,- pinned,- };- }- // A channel tab: a sub-section (Recents/CONTEXT.md/…) or the channel home.- // The section drives the label; the channel name carries the space- // context. Home has no section, so it labels by the channel name.- if (channelId) {- const meta = channelSectionFor(section);- return {- id: t.id,- label:- meta?.label ??- channel ??- t.viewState?.title ??- (spacesLayout ? "Space" : "Channel"),- icon: channelGlyph(channel ?? undefined, {- size: 14,- space: spacesLayout,- }),- channelName: channel,- // No section meta → the channel's index page.- isChannelHome: !meta,- pinned,- };- }+ const viewFor = (t: BrowserTab): TabView => {+ const pinned = pinnedSet.has(t.id);+ const isActive = t.id === (settledTabId ?? activeTabId);+ const taskId = isActive ? (activeSession.taskId ?? null) : t.taskId;+ const dashId = isActive ? (params.dashboardId ?? null) : t.dashboardId;+ const channelId = isActive+ ? (params.channelId ?? activeSession.channelId ?? null)+ : t.channelId;+ const section = isActive ? routeChannelSection : t.channelSection;+ const appView = isActive ? routeAppView : t.appView;+ const channel = channelName(channelId);+ const feedId = isActive ? routeFeedId : feedIdFromHref(t.href);+ if (feedId) {return {id: t.id,- label: t.viewState?.title ?? "New tab",+ label: feedName(feedId) ?? t.viewState?.title ?? "Saved search",+ icon: <MagnifyingGlassIcon size={14} />,channelName: null,pinned,};- });+ }+ if (taskId) {+ const task = findTask(taskId);+ return {+ id: t.id,+ label:+ task?.title ?? taskInfo.get(taskId) ?? t.viewState?.title ?? "Task",+ icon: <TaskTabDot task={task} />,+ channelName: channel,+ pinned,+ };+ }+ if (dashId) {+ const info = resolveCanvas(dashId);+ return {+ id: t.id,+ label: info?.name ?? t.viewState?.title ?? "Canvas",+ icon: iconForTemplate(info?.templateId ?? "freeform", {+ size: 14,+ }),+ channelName: channel,+ pinned,+ };+ }+ if (appView && isTabAppView(appView)) {+ 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, reportTab);+ return {+ id: t.id,+ ...display,+ channelName: null,+ pinned,+ };+ }+ if (channelId) {+ const meta = channelSectionFor(section);+ return {+ id: t.id,+ label:+ meta?.label ??+ channel ??+ t.viewState?.title ??+ (spacesLayout ? "Space" : "Channel"),+ icon: channelGlyph(channel ?? undefined, {+ size: 14,+ space: spacesLayout,+ }),+ channelName: channel,+ isChannelHome: !meta,+ pinned,+ };+ }+ return {+ id: t.id,+ label: t.viewState?.title ?? "New tab",+ channelName: null,+ pinned,+ };+ };++ const previewGroups = stripPreviewTabId+ ? untileTab(tileGroups, stripPreviewTabId)+ : tileGroups;+ const { ids, groupByAnchor } = collapseSplits(+ partitionPinnedFirst(base, pinnedTabIds),+ previewGroups,+ );+ return ids.flatMap((id): TabView[] => {+ const anchor = byId.get(id);+ if (!anchor) return [];+ const group = groupByAnchor.get(id);+ if (!group) return [viewFor(anchor)];+ const members = tabIdsIn(group.root)+ .map((memberId) => byId.get(memberId))+ .filter((t) => t !== undefined)+ .map(viewFor);+ const activeId =+ activeTabId && members.some((m) => m.id === activeTabId)+ ? activeTabId+ : lastActiveIn(group, activeByGroup);+ const face = members.find((m) => m.id === activeId) ?? members[0];+ return [+ {+ ...face,+ id: anchor.id,+ pinned: false,+ split: {+ members,+ activeId: face.id,+ name: groupNames[group.id],+ },+ },+ ];+ });}, [snapshot,windowId,pinnedTabIds,previewOrder,+ tileGroups,+ stripPreviewTabId,+ activeByGroup,+ groupNames,channelName,dashboards,activeRecord,allTasks,activeTaskRecord,activeTabId,+ settledTabId,params.channelId,params.dashboardId,activeSession.taskId,@@ -692,115 +727,16 @@ function BrowserTabStripImpl() {//// The reconstruction survives underneath for tabs persisted before hrefs were// stored, whose `href` is null until their next navigation.- const goToTab = useCallback(- (tab: TabRef) => {- const state = (prev: object) => ({ ...prev, tabId: tab.id });- if (tab.href) {- pushTabHistoryEntry(router.history, tab.href, tab.id);- return;- }- if (tab.taskId && tab.channelId) {- navigate({- to: "/spaces/$channelId/tasks/$taskId",- params: { channelId: tab.channelId, taskId: tab.taskId },- state,- });- } else if (tab.taskId) {- // A channel-less task tab — the Code task detail route.- navigate({- to: "/tasks/$taskId",- params: { taskId: tab.taskId },- state,- });- } else if (tab.dashboardId && tab.channelId) {- navigate({- to: "/spaces/$channelId/dashboards/$dashboardId",- params: { channelId: tab.channelId, dashboardId: tab.dashboardId },- state,- });- } else if (tab.channelId) {- const params = { channelId: tab.channelId };- // Section keys are the route segments; unknown/stale sections (e.g. from- // a since-removed tab type) fall back to the channel home.- const section = channelSectionFor(tab.channelSection);- if (section) {- navigate({- to: `/spaces/$channelId/${section.key}` as const,- params,- state,- });- } else {- navigate({ to: "/spaces/$channelId", params, state });- }- } else if (tab.appView && isTabAppView(tab.appView)) {- // A top-level app page — back to its canonical route (literal `to` per- // case so the router types stay checked).- switch (tab.appView) {- case "activity":- navigate({ to: "/activity", state });- break;- case "home":- case "report":- navigate({ to: "/", state });- break;- case "inbox":- navigate({- to: channelReportsEnabled ? "/spaces" : "/inbox",- state,- });- break;- case "agents":- navigate({- to: "/settings/$category",- params: { category: "agents" },- state,- });- break;- case "loops":- navigate({ to: "/loops", state });- break;- case "archived":- navigate({ to: "/archived", state });- break;- case "skills":- navigate({ to: "/skills", state });- break;- case "mcp-servers":- navigate({ to: "/mcp-servers", state });- break;- case "command-center":- navigate({ to: "/command-center", state });- break;- case "context":- navigate({ to: "/context", search: { path: undefined }, state });- break;- case "settings":- navigate({ to: "/settings", state });- break;- default: {- // Exhaustiveness guard: a new AppView value fails to compile here- // until its canonical route is wired above — so the tab-target set- // (union + APP_VIEW_META) and this navigation can't drift apart.- const _exhaustive: never = tab.appView;- return _exhaustive;- }- }- } else {- navigate({ to: DEFAULT_TAB_HREF, state });- }- },- [channelReportsEnabled, navigate, router.history],- );-const handleSelect = useCallback((tabId: string) => {if (!windowId) return;+ const targetId = focusedTabIn(tileGroups, activeByGroup, tabId);const target = readMirror().tabs.find(- (tab) => tab.windowId === windowId && tab.id === tabId,+ (tab) => tab.windowId === windowId && tab.id === targetId,);- if (target) goToTab(target);+ if (target) focusTab(target);},- [goToTab, windowId],+ [focusTab, windowId, tileGroups, activeByGroup],);// Navigate to the close's survivor, or — when the last tab was closed — to the@@ -819,6 +755,12 @@ function BrowserTabStripImpl() {// /website index therefore always renders against the post-close snapshot// and can't redirect (re-opening a tab) mid-flight.const handleClose = (tabId: string) => {+ const group = groupForTab(tileGroups, tabId);+ if (group) {+ const sibling = tabIdsIn(group.root).find((id) => id !== tabId);+ handleCloseMany([tabId], sibling);+ return;+ }useDraftStore.getState().actions.setDraft(getTaskInputSessionId(tabId), null);@@ -850,7 +792,7 @@ function BrowserTabStripImpl() {// Bulk closes operate on the strip's *displayed* order (pinned-first) and// never take pinned tabs with them. The anchor (the right-clicked tab, which// always survives) takes focus if the active tab was among those closed.- const handleCloseMany = (tabIds: string[], anchorTabId: string) => {+ const handleCloseMany = (tabIds: string[], anchorTabId?: string) => {if (tabIds.length === 0) return;const draftActions = useDraftStore.getState().actions;for (const tabId of tabIds) {@@ -875,9 +817,18 @@ function BrowserTabStripImpl() {);};+ const tabIdsOf = (view: TabView): string[] =>+ view.split ? view.split.members.map((m) => m.id) : [view.id];++ const handleClosePill = (tabId: string) => {+ const group = groupForTab(tileGroups, tabId);+ if (group) handleCloseMany(tabIdsIn(group.root));+ else handleClose(tabId);+ };+const handleCloseOthers = (tabId: string) => {handleCloseMany(- tabs.filter((t) => t.id !== tabId && !t.pinned).map((t) => t.id),+ tabs.filter((t) => t.id !== tabId && !t.pinned).flatMap(tabIdsOf),tabId,);};@@ -889,7 +840,7 @@ function BrowserTabStripImpl() {tabs.slice(idx + 1).filter((t) => !t.pinned)- .map((t) => t.id),+ .flatMap(tabIdsOf),tabId,);};@@ -901,11 +852,27 @@ function BrowserTabStripImpl() {tabs.slice(0, idx).filter((t) => !t.pinned)- .map((t) => t.id),+ .flatMap(tabIdsOf),tabId,);};+ const handleRenameSplit = (tabId: string, name: string) => {+ const group = groupForTab(tileGroups, tabId);+ if (!group) return;+ renameGroup(group.id, name);+ track(ANALYTICS_EVENTS.BROWSER_TAB_SPLIT_RENAMED, {+ tile_count: tabIdsIn(group.root).length,+ });+ };++ const handleSeparate = (tabId: string) => {+ const group = groupForTab(tileGroups, tabId);+ if (!group) return;+ separateGroup(group.id);+ track(ANALYTICS_EVENTS.BROWSER_TAB_UNTILED, { tile_count: 0 });+ };+const landOnDefault = (tabId?: string): void => {const state = tabId ? (prev: object) => ({ ...prev, tabId }) : undefined;navigate({ to: DEFAULT_TAB_HREF, state });@@ -969,11 +936,13 @@ function BrowserTabStripImpl() {tabs={tabs}activeTabId={activeTabId}onSelect={handleSelect}- onClose={handleClose}+ onClose={handleClosePill}onTogglePin={handleTogglePin}onCloseOthers={handleCloseOthers}onCloseToRight={handleCloseToRight}onCloseToLeft={handleCloseToLeft}+ onSeparate={handleSeparate}+ onRenameSplit={handleRenameSplit}onNewTab={handleNewTab}/>);diff --git a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabsDnd.tsx b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabsDnd.tsxindex a014e5d39a2a..94f708092fc5 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabsDnd.tsx+++ b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabsDnd.tsx@@ -2,15 +2,29 @@ import { type DragDropEvents, DragDropProvider } from "@dnd-kit/react";import { browserTabsStore } from "@posthog/core/browser-tabs/browserTabsStore";import { useService } from "@posthog/di/react";import { primaryWindow, setTabOrder } from "@posthog/shared";+import { isTileDropData } from "@posthog/ui/features/tab-tiling/TileDropZones";+import {+ tileBeside,+ untileTracked,+} from "@posthog/ui/features/tab-tiling/tileActions";+import { isTileTabDragData } from "@posthog/ui/features/tab-tiling/tileDrag";+import { useTileLayoutStore } from "@posthog/ui/features/tab-tiling/tileLayoutStore";import { type ReactNode, useRef } from "react";import {BROWSER_TABS_CLIENT,type BrowserTabsClient,} from "./browserTabsClient";-import { reorderWithinGroup, storedOrderIds } from "./displayOrder";+import {+ keepGroupTogether,+ reorderWithinGroup,+ storedOrderIds,+} from "./displayOrder";import { usePinnedTabsStore } from "./pinnedTabsStore";+import { isBrowserTabDragData, stripTarget } from "./stripDrop";+import { exceedsDetachDistance } from "./tabDetach";import { useTabReorderStore } from "./tabReorderStore";-import { applyLocalTransform, persistWrite } from "./tabsSync";+import { applyLocalTransform, persistWrite, readMirror } from "./tabsSync";+import { useGoToTab } from "./useGoToTab";function sameOrder(a: string[], b: string[]): boolean {return a.length === b.length && a.every((id, i) => id === b[i]);@@ -32,76 +46,165 @@ function sameOrder(a: string[], b: string[]): boolean {*/export function BrowserTabsDndProvider({ children }: { children: ReactNode }) {const client = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);+ const goToTab = useGoToTab();/** Stored order captured at dragstart — used to skip a no-op persist. */const initialOrder = useRef<string[] | null>(null);+ const dragStart = useRef<{ x: number; y: number } | null>(null);++ const currentOrder = () => {+ const snapshot = browserTabsStore.getState().snapshot;+ const win = primaryWindow(snapshot);+ return win ? storedOrderIds(snapshot, win.id) : null;+ };const onDragStart: DragDropEvents["dragstart"] = (event) => {- if (event.operation.source?.data?.type !== "browser-tab") return;+ const data = event.operation.source?.data;+ const store = useTabReorderStore.getState();+ if (isTileTabDragData(data)) {+ store.beginDrag({+ draggingTabId: data.tabId,+ dragSource: "tile",+ detached: true,+ });+ return;+ }+ if (!isBrowserTabDragData(data)) return;+ const order = currentOrder();+ if (!order) return;+ initialOrder.current = order;+ dragStart.current = event.operation.position.current;+ store.beginDrag({+ draggingTabId: data.tabId,+ dragSource: "strip",+ previewOrder: order,+ });+ };++ const onDragMove: DragDropEvents["dragmove"] = (event) => {+ const start = dragStart.current;+ if (!start || !event.to) return;+ const store = useTabReorderStore.getState();+ if (store.dragSource !== "strip") return;+ const detached = exceedsDetachDistance(event.to.y - start.y);+ if (detached !== store.detached) store.setDetached(detached);+ };++ const persistOrder = (order: string[]) => {const snapshot = browserTabsStore.getState().snapshot;const win = primaryWindow(snapshot);if (!win) return;- const order = storedOrderIds(snapshot, win.id);- initialOrder.current = order;- useTabReorderStore.getState().setPreviewOrder(order);+ applyLocalTransform((s) => setTabOrder(s, win.id, order));+ void persistWrite(() =>+ client.setOrder({ windowId: win.id, tabIds: order }),+ );+ };++ const dropTileOnStrip = (tabId: string, previewed: string[] | null) => {+ untileTracked(tabId);+ const order = currentOrder();+ if (previewed && order && !sameOrder(previewed, order)) {+ persistOrder(previewed);+ }+ const tab = readMirror().tabs.find((t) => t.id === tabId);+ if (tab) goToTab(tab);+ };++ const dropTile = (+ tabId: string,+ target: unknown,+ previewed: string[] | null,+ ) => {+ if (isTileDropData(target)) {+ if (target.tabId !== tabId) {+ tileBeside(tabId, target.tabId, target.edge, "tile");+ }+ return;+ }+ if (stripTarget(target)) dropTileOnStrip(tabId, previewed);+ };++ const previewTileOverStrip = (tabId: string, target: unknown) => {+ const store = useTabReorderStore.getState();+ const strip = stripTarget(target);+ if (!strip) {+ if (store.previewOrder) store.setPreviewOrder(null);+ return;+ }+ const cur = store.previewOrder ?? currentOrder();+ if (!cur) return;+ if (!strip.pillId || strip.pillId === tabId) {+ if (!store.previewOrder) store.setPreviewOrder(cur);+ return;+ }+ const pinnedTabIds = usePinnedTabsStore.getState().pinnedTabIds;+ const next = reorderWithinGroup(cur, pinnedTabIds, tabId, strip.pillId);+ if (!sameOrder(next, cur) || !store.previewOrder) {+ store.setPreviewOrder(next);+ }};const onDragOver: DragDropEvents["dragover"] = (event) => {const src = event.operation.source?.data;const tgt = event.operation.target?.data;+ if (isTileTabDragData(src)) {+ previewTileOverStrip(src.tabId, tgt);+ return;+ }+ const store = useTabReorderStore.getState();if (- src?.type !== "browser-tab" ||- tgt?.type !== "browser-tab" ||- !src.tabId ||- !tgt.tabId ||+ store.detached ||+ !isBrowserTabDragData(src) ||+ !isBrowserTabDragData(tgt) ||src.tabId === tgt.tabId) {return;}- const store = useTabReorderStore.getState();- const snapshot = browserTabsStore.getState().snapshot;- const win = primaryWindow(snapshot);- if (!win) return;- const cur = store.previewOrder ?? storedOrderIds(snapshot, win.id);+ const cur = store.previewOrder ?? currentOrder();+ if (!cur) return;const pinnedTabIds = usePinnedTabsStore.getState().pinnedTabIds;// Reorder within the dragged tab's pin group only; cross-group drags are// rejected (pinned pills can't land among unpinned tabs, or vice versa).- const next = reorderWithinGroup(cur, pinnedTabIds, src.tabId, tgt.tabId);+ const next = keepGroupTogether(+ reorderWithinGroup(cur, pinnedTabIds, src.tabId, tgt.tabId),+ useTileLayoutStore.getState().groups,+ src.tabId,+ );if (!sameOrder(next, cur)) store.setPreviewOrder(next);};const onDragEnd: DragDropEvents["dragend"] = (event) => {const src = event.operation.source?.data;+ const tgt = event.operation.target?.data;const order = useTabReorderStore.getState().previewOrder;const initial = initialOrder.current;initialOrder.current = null;+ dragStart.current = null;// Defer clearing the preview + persisting a frame so @dnd-kit finishes its// DOM cleanup first (same gotcha as the panels feature).requestAnimationFrame(() => {- useTabReorderStore.getState().setPreviewOrder(null);- if (- event.canceled ||- src?.type !== "browser-tab" ||- !order ||- (initial && sameOrder(order, initial))- ) {+ useTabReorderStore.getState().endDrag();+ if (event.canceled) return;+ if (isTileTabDragData(src)) {+ dropTile(src.tabId, tgt, order);+ return;+ }+ if (!isBrowserTabDragData(src)) return;+ if (isTileDropData(tgt)) {+ tileBeside(src.tabId, tgt.tabId, tgt.edge, "strip");return;}- const snapshot = browserTabsStore.getState().snapshot;- const win = primaryWindow(snapshot);- if (!win) return;+ if (!order || (initial && sameOrder(order, initial))) return;// Apply locally so the strip doesn't flit back to the mirror's pre-drop// order for a frame; persist through the tabsSync gate so the echo can't// rewind a newer write.- applyLocalTransform((s) => setTabOrder(s, win.id, order));- void persistWrite(() =>- client.setOrder({ windowId: win.id, tabIds: order }),- );+ persistOrder(order);});};return (<DragDropProvideronDragStart={onDragStart}+ onDragMove={onDragMove}onDragOver={onDragOver}onDragEnd={onDragEnd}>diff --git a/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.test.tsx b/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.test.tsxindex b3797097147f..3e12a66de01d 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.test.tsx+++ b/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.test.tsx@@ -20,6 +20,8 @@ function setup(overrides?: Partial<Parameters<typeof TabStrip>[0]>) {onCloseOthers: vi.fn(),onCloseToRight: vi.fn(),onCloseToLeft: vi.fn(),+ onSeparate: vi.fn(),+ onRenameSplit: vi.fn(),...overrides,};// Pills call useSortable, which needs an ancestor DnD provider (the app@@ -100,6 +102,37 @@ describe("TabStrip", () => {expect(screen.getByLabelText("Close Funnels")).toBeTruthy();});+ it("shows a split as one pill that closes and separates as a whole", async () => {+ const props = setup({+ activeTabId: "t2",+ tabs: [+ {+ id: "t1",+ label: "Funnels",+ channelName: null,+ split: {+ members: [+ { id: "t1", label: "Overview" },+ { id: "t2", label: "Funnels" },+ ],+ activeId: "t2",+ },+ },+ ],+ });+ expect(screen.getAllByRole("tab")).toHaveLength(1);+ expect(screen.getByLabelText("Funnels (split, 2 tabs)")).toBeTruthy();+ expect(screen.getByRole("tab")).toHaveAttribute("aria-selected", "true");++ await userEvent.click(screen.getByLabelText("Close split (2 tabs)"));+ expect(props.onClose).toHaveBeenCalledWith("t1");++ fireEvent.contextMenu(screen.getByLabelText("Funnels (split, 2 tabs)"));+ expect(screen.queryByText("Pin tab")).toBeNull();+ await userEvent.click(await screen.findByText("Separate all tabs"));+ expect(props.onSeparate).toHaveBeenCalledWith("t1");+ });+it("pins from the context menu", async () => {const props = setup();openMenuOn("Overview");diff --git a/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.tsx b/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.tsxindex 599be5458acb..63058df9e188 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.tsx+++ b/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.tsx@@ -1,6 +1,13 @@-import { RestrictToHorizontalAxis } from "@dnd-kit/abstract/modifiers";+import { useDroppable } from "@dnd-kit/react";import { useSortable } from "@dnd-kit/react/sortable";-import { PlusIcon, PushPinIcon, XIcon } from "@phosphor-icons/react";+import {+ PencilSimpleIcon,+ PlusIcon,+ PushPinIcon,+ SplitHorizontalIcon,+ SquareSplitHorizontalIcon,+ XIcon,+} from "@phosphor-icons/react";import {Button,ContextMenu,@@ -8,13 +15,17 @@ import {ContextMenuItem,ContextMenuSeparator,ContextMenuTrigger,+ cn,Tooltip,TooltipContent,TooltipProvider,TooltipTrigger,} from "@posthog/quill";import { Flex } from "@radix-ui/themes";-import type { ReactNode } from "react";+import { type ReactNode, useState } from "react";+import { STRIP_DROP_TYPE, type StripDropData } from "./stripDrop";+import { DetachFromStrip } from "./tabDetach";+import { useTabReorderStore } from "./tabReorderStore";export interface TabView {id: string;@@ -28,6 +39,13 @@ export interface TabView {isChannelHome?: boolean;/** Pinned tabs collapse to icon-only, sort first, and survive bulk closes. */pinned?: boolean;+ split?: SplitView;+}++export interface SplitView {+ members: Pick<TabView, "id" | "label" | "icon">[];+ activeId: string;+ name?: string;}/** Which bulk-close actions would close at least one (unpinned) tab. */@@ -50,6 +68,8 @@ export interface TabStripProps {onCloseOthers: (tabId: string) => void;onCloseToRight: (tabId: string) => void;onCloseToLeft: (tabId: string) => void;+ onSeparate: (tabId: string) => void;+ onRenameSplit: (tabId: string, name: string) => void;}/**@@ -69,6 +89,8 @@ export function TabStrip({onCloseOthers,onCloseToRight,onCloseToLeft,+ onSeparate,+ onRenameSplit,}: TabStripProps) {// Which bulk closes are live per pill, in a single pass over the strip// (each closes only *unpinned* tabs in its range).@@ -85,6 +107,14 @@ export function TabStrip({return c;});+ const tileDragActive = useTabReorderStore((s) => s.dragSource === "tile");+ const stripDropData: StripDropData = { type: STRIP_DROP_TYPE };+ const { ref: stripRef, isDropTarget } = useDroppable({+ id: "browser-tab-strip",+ data: stripDropData,+ disabled: !tileDragActive,+ });+return (<TooltipProvider delay={400}>{/* overflow-hidden: incompressible pinned pills must clip within the@@ -93,9 +123,13 @@ export function TabStrip({space right of the pills moves the window; each interactive childopts out with `no-drag` individually. */}<Flex+ ref={stripRef}align="center"gap="1"- className="h-6 min-w-0 flex-1 overflow-hidden pt-px pr-2"+ className={cn(+ "h-6 min-w-0 flex-1 overflow-hidden pt-px pr-2",+ isDropTarget && "rounded-md ring-1 ring-accent-8",+ )}role="tablist">{tabs.map((tab, index) => (@@ -103,7 +137,7 @@ export function TabStrip({key={tab.id}tab={tab}index={index}- isActive={tab.id === activeTabId}+ isActive={(tab.split?.activeId ?? tab.id) === activeTabId}closable={closable[index]}onSelect={onSelect}onClose={onClose}@@ -111,6 +145,8 @@ export function TabStrip({onCloseOthers={onCloseOthers}onCloseToRight={onCloseToRight}onCloseToLeft={onCloseToLeft}+ onSeparate={onSeparate}+ onRenameSplit={onRenameSplit}/>))}{onNewTab && (@@ -146,6 +182,8 @@ function SortableTabPill({onCloseOthers,onCloseToRight,onCloseToLeft,+ onSeparate,+ onRenameSplit,}: {tab: TabView;index: number;@@ -159,18 +197,32 @@ function SortableTabPill({| "onCloseOthers"| "onCloseToRight"| "onCloseToLeft"+ | "onSeparate"+ | "onRenameSplit">) {// Pinned and unpinned pills sort in separate groups so a drag can't preview// an insertion across the pin boundary (the drop handler rejects it too).- // Drags ride the x-axis only — the pill stays in the strip's row.- const { ref } = useSortable({+ const { ref, isDragSource } = useSortable({id: tab.id,index,group: tab.pinned ? "browser-tab-strip-pinned" : "browser-tab-strip",- modifiers: [RestrictToHorizontalAxis],+ modifiers: [DetachFromStrip],transition: { duration: 200, easing: "ease" },data: { type: "browser-tab", tabId: tab.id },});+ const detached = useTabReorderStore((s) => isDragSource && s.detached);+ const [renaming, setRenaming] = useState(false);+ const commitRename = (value: string | null) => {+ if (!renaming) return;+ setRenaming(false);+ if (value !== null) onRenameSplit(tab.id, value);+ };++ const split = tab.split;+ const label = split ? (split.name ?? tab.label) : tab.label;+ const closeLabel = split+ ? `Close split (${split.members.length} tabs)`+ : `Close ${tab.label}`;// A pinned pill collapses to icon + padding (browser-style); its label lives// in the tooltip. Unpinned pills keep the fading label and hover close.@@ -183,43 +235,68 @@ function SortableTabPill({event.stopPropagation();onClose(tab.id);}}- className={+ className={cn(tab.pinned? "no-drag flex shrink-0 items-center"- : "no-drag group relative flex min-w-0 max-w-[200px] flex-1 basis-[200px] items-center overflow-hidden"- }+ : "no-drag group relative flex min-w-0 max-w-[200px] flex-1 basis-[200px] items-center overflow-hidden",+ detached && "rounded-md bg-background shadow-lg ring-1 ring-border",+ )}>- <Button- variant="default"- size="sm"- role="tab"- aria-selected={isActive}- aria-label={tab.pinned ? `${tab.label} (pinned)` : undefined}- onClick={() => onSelect(tab.id)}- className={`h-6 px-2 ${- tab.pinned- ? "w-auto justify-center"- : "w-full justify-start gap-1 transition-[padding] group-hover:pr-6"- } ${isActive ? "" : "opacity-60 hover:opacity-100"}`}- >- {tab.icon || tab.pinned ? (- <span className="flex shrink-0 items-center [&>svg]:size-3.5">- {tab.icon ?? <PushPinIcon size={14} weight="fill" />}- </span>- ) : null}- {/* Fade the right edge instead of an ellipsis; the label shrinks on- hover (button gets pr) so the fade follows, clearing room for the- close button. */}- {tab.pinned ? null : (- <span className="min-w-0 flex-1 overflow-hidden whitespace-nowrap text-left [-webkit-mask-image:linear-gradient(to_right,#000,#000_calc(100%-0.75rem),#0000)] [mask-image:linear-gradient(to_right,#000,#000_calc(100%-0.75rem),#0000)]">- {tab.label}- </span>- )}- </Button>+ {renaming && split ? (+ <input+ // biome-ignore lint/a11y/noAutofocus: the field opens from an explicit menu action+ autoFocus+ defaultValue={split.name ?? ""}+ placeholder="Name this split"+ aria-label="Split name"+ onFocus={(event) => event.currentTarget.select()}+ className="h-6 w-full min-w-0 rounded-md bg-background px-2 text-xs outline-none ring-1 ring-accent-8"+ onKeyDown={(event) => {+ if (event.key === "Enter") commitRename(event.currentTarget.value);+ if (event.key === "Escape") commitRename(null);+ }}+ onBlur={(event) => commitRename(event.currentTarget.value)}+ />+ ) : (+ <Button+ variant="default"+ size="sm"+ role="tab"+ aria-selected={isActive}+ aria-label={+ tab.pinned+ ? `${tab.label} (pinned)`+ : split+ ? `${label} (split, ${split.members.length} tabs)`+ : undefined+ }+ onClick={() => onSelect(tab.id)}+ className={`h-6 px-2 ${+ tab.pinned+ ? "w-auto justify-center"+ : "w-full justify-start gap-1 transition-[padding] group-hover:pr-6"+ } ${isActive ? "" : "opacity-60 hover:opacity-100"}`}+ >+ {split ? (+ <span className="flex shrink-0 items-center [&>svg]:size-3.5">+ <SquareSplitHorizontalIcon size={14} />+ </span>+ ) : tab.icon || tab.pinned ? (+ <span className="flex shrink-0 items-center [&>svg]:size-3.5">+ {tab.icon ?? <PushPinIcon size={14} weight="fill" />}+ </span>+ ) : null}+ {tab.pinned ? null : (+ <span className="min-w-0 flex-1 overflow-hidden whitespace-nowrap text-left [-webkit-mask-image:linear-gradient(to_right,#000,#000_calc(100%-0.75rem),#0000)] [mask-image:linear-gradient(to_right,#000,#000_calc(100%-0.75rem),#0000)]">+ {label}+ </span>+ )}+ </Button>+ )}{tab.pinned ? null : (<buttontype="button"- aria-label={`Close ${tab.label}`}+ aria-label={closeLabel}onClick={(e) => {e.stopPropagation();onClose(tab.id);@@ -247,29 +324,61 @@ function SortableTabPill({{/* Channel context first (always `#`-prefixed); the channel-home tabreads `#channel / home`. Then the page name, unless it would justrepeat the channel-home name already shown above. */}- {tab.channelName ? (- <div className="text-muted">- {tab.channelName}- {tab.isChannelHome ? " / home" : null}- </div>- ) : null}- {tab.label && !(tab.isChannelHome && tab.channelName) ? (- <div className="font-medium">{tab.label}</div>- ) : null}+ {split ? (+ <>+ <div className="font-medium">{label}</div>+ {split.members.map((member) => (+ <div+ key={member.id}+ className={cn(+ "mt-0.5",+ member.id !== split.activeId && "text-muted",+ )}+ >+ {member.label}+ </div>+ ))}+ </>+ ) : (+ <>+ {tab.channelName ? (+ <div className="text-muted">+ {tab.channelName}+ {tab.isChannelHome ? " / home" : null}+ </div>+ ) : null}+ {tab.label && !(tab.isChannelHome && tab.channelName) ? (+ <div className="font-medium">{tab.label}</div>+ ) : null}+ </>+ )}</TooltipContent></Tooltip>{/* no-drag: the menu opens under the title bar's drag region, andElectron drag regions swallow clicks on anything visuallyoverlapping them — even a portalled popup on top. */}<ContextMenuContent className="no-drag">- <ContextMenuItem onClick={() => onTogglePin(tab.id)}>- <PushPinIcon size={14} />- {tab.pinned ? "Unpin tab" : "Pin tab"}- </ContextMenuItem>+ {split ? (+ <>+ <ContextMenuItem onClick={() => setRenaming(true)}>+ <PencilSimpleIcon size={14} />+ Rename split+ </ContextMenuItem>+ <ContextMenuItem onClick={() => onSeparate(tab.id)}>+ <SplitHorizontalIcon size={14} />+ Separate all tabs+ </ContextMenuItem>+ </>+ ) : (+ <ContextMenuItem onClick={() => onTogglePin(tab.id)}>+ <PushPinIcon size={14} />+ {tab.pinned ? "Unpin tab" : "Pin tab"}+ </ContextMenuItem>+ )}<ContextMenuSeparator /><ContextMenuItem onClick={() => onClose(tab.id)}><XIcon size={14} />- Close tab+ {split ? "Close split" : "Close tab"}</ContextMenuItem><ContextMenuIteminsetdiff --git a/products/desktop/packages/ui/src/features/browser-tabs/displayOrder.test.ts b/products/desktop/packages/ui/src/features/browser-tabs/displayOrder.test.tsindex 436efa42e9a9..992def3350bc 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/displayOrder.test.ts+++ b/products/desktop/packages/ui/src/features/browser-tabs/displayOrder.test.ts@@ -1,8 +1,10 @@import type { BrowserTab, TabsSnapshot } from "@posthog/shared";import { describe, expect, it } from "vitest";import {+ collapseSplits,displayedTabIds,frontOfUnpinnedOrder,+ keepGroupTogether,partitionPinnedFirst,reorderWithinGroup,storedOrderIds,@@ -112,3 +114,42 @@ describe("frontOfUnpinnedOrder", () => {expect(order).toEqual(["p", "c"]);});});++describe("collapseSplits", () => {+ const group = {+ id: "g1",+ root: {+ type: "split" as const,+ id: "g1",+ direction: "horizontal" as const,+ children: [+ { type: "tab" as const, tabId: "c" },+ { type: "tab" as const, tabId: "a" },+ ],+ },+ };++ it("keeps one pill per split in the first member's slot", () => {+ const { ids, groupByAnchor } = collapseSplits(+ ["a", "b", "c", "d"],+ [group],+ );+ expect(ids).toEqual(["a", "b", "d"]);+ expect(groupByAnchor.get("a")).toBe(group);+ });++ it("moves a split's other members along with its dragged anchor", () => {+ expect(keepGroupTogether(["b", "d", "a", "c"], [group], "a")).toEqual([+ "b",+ "d",+ "a",+ "c",+ ]);+ expect(keepGroupTogether(["c", "b", "d", "a"], [group], "a")).toEqual([+ "b",+ "d",+ "a",+ "c",+ ]);+ });+});diff --git a/products/desktop/packages/ui/src/features/browser-tabs/displayOrder.ts b/products/desktop/packages/ui/src/features/browser-tabs/displayOrder.tsindex 4b1b5add5584..bc088cb53a83 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/displayOrder.ts+++ b/products/desktop/packages/ui/src/features/browser-tabs/displayOrder.ts@@ -1,4 +1,30 @@import type { TabsSnapshot } from "@posthog/shared";+import {+ groupForTab,+ type TileGroup,+ tabIdsIn,+} from "@posthog/ui/features/tab-tiling/tileTree";++export function collapseSplits(+ displayIds: string[],+ groups: readonly TileGroup[],+): { ids: string[]; groupByAnchor: Map<string, TileGroup> } {+ const groupByAnchor = new Map<string, TileGroup>();+ const hidden = new Set<string>();+ const ids: string[] = [];+ for (const id of displayIds) {+ if (hidden.has(id)) continue;+ const group = groupForTab(groups, id);+ if (group) {+ groupByAnchor.set(id, group);+ for (const member of tabIdsIn(group.root)) {+ if (member !== id) hidden.add(member);+ }+ }+ ids.push(id);+ }+ return { ids, groupByAnchor };+}/** A window's tab ids in stored order (by position), pin-agnostic. */export function storedOrderIds(@@ -71,6 +97,20 @@ export function reorderWithinGroup();}+export function keepGroupTogether(+ storedIds: string[],+ groups: readonly TileGroup[],+ anchorId: string,+): string[] {+ const group = groupForTab(groups, anchorId);+ if (!group) return storedIds;+ const members = tabIdsIn(group.root).filter((id) => id !== anchorId);+ const rest = storedIds.filter((id) => !members.includes(id));+ const at = rest.indexOf(anchorId);+ if (at === -1) return storedIds;+ return [...rest.slice(0, at + 1), ...members, ...rest.slice(at + 1)];+}+/*** Stored order that puts `tabId` just before the first tab still in the* unpinned block (i.e. front of the unpinned block once it is unpinned),diff --git a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.tsindex 201611e839c9..6b6cd6b42a8e 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts+++ b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts@@ -3,6 +3,7 @@ import {openTab as openTabLocal,primaryWindow,setTabTarget as setTabTargetLocal,+ setWindowActiveTab,type TabIdentity,} from "@posthog/shared";import { getRouterOrNull } from "@posthog/ui/router/routerRef";@@ -19,11 +20,13 @@ import {export function openInNewBrowserTabSync(client: BrowserTabsClient,destination: BrowserTabDestination,+ options: { focus?: boolean } = {},): string | null {const window = primaryWindow(readMirror());const history = getRouterOrNull()?.history;if (!window || !history) return null;const tabId = crypto.randomUUID();+ const keepActiveTabId = options.focus === false ? window.activeTabId : null;const input = {windowId: window.id,href: destination.href,@@ -34,13 +37,22 @@ export function openInNewBrowserTabSync(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 }));+ applyLocalTransform((snapshot) => {+ const opened = openTabLocal(snapshot, {+ ...input,+ makeId: () => tabId,+ now: Date.now,+ }).snapshot;+ return keepActiveTabId+ ? setWindowActiveTab(opened, window.id, keepActiveTabId)+ : opened;+ });+ if (!keepActiveTabId) pushTabHistoryEntry(history, destination.href, tabId);+ void persistWrite(async () => {+ const opened = await client.openTab({ ...input, tabId });+ if (!keepActiveTabId) return opened;+ return client.setActiveTab({ windowId: window.id, tabId: keepActiveTabId });+ });return tabId;}@@ -83,6 +95,44 @@ function tabShowsDestination(return tab.href === dest.href;}+export function findTabForDestination(+ destination: BrowserTabDestination,+): BrowserTab | null {+ const mirror = readMirror();+ const window = primaryWindow(mirror);+ if (!window) return null;+ return (+ mirror.tabs.find(+ (tab) =>+ tab.windowId === window.id && tabShowsDestination(tab, destination),+ ) ?? null+ );+}++export function writeBackgroundTabTarget(+ tab: BrowserTab,+ destination: BrowserTabDestination,+): void {+ const target = {+ tabId: tab.id,+ href: destination.href,+ viewState: {+ ...(tab.viewState ?? {}),+ ...(destination.title ? { title: destination.title } : {}),+ },+ dashboardId: destination.dashboardId ?? null,+ taskId: destination.taskId ?? null,+ channelId: destination.channelId ?? null,+ channelSection: destination.channelSection ?? null,+ appView: destination.appView ?? null,+ activate: false,+ };+ applyLocalTransform((snapshot) =>+ setTabTargetLocal(snapshot, { ...target, now: Date.now }),+ );+ persistTabTarget(target);+}+export function focusExistingTab(destination: BrowserTabDestination): boolean {const mirror = readMirror();const window = primaryWindow(mirror);@@ -132,24 +182,6 @@ export function navigateBrowserTab(const tab = readMirror().tabs.find((candidate) => candidate.id === tabId);if (!tab) return "closed";- const target = {- tabId,- href: destination.href,- viewState: {- ...(tab.viewState ?? {}),- ...(destination.title ? { title: destination.title } : {}),- },- dashboardId: destination.dashboardId ?? null,- taskId: destination.taskId ?? null,- channelId: destination.channelId ?? null,- channelSection: destination.channelSection ?? null,- appView: destination.appView ?? null,- activate: false,- };-- applyLocalTransform((snapshot) =>- setTabTargetLocal(snapshot, { ...target, now: Date.now }),- );- persistTabTarget(target);+ writeBackgroundTabTarget(tab, destination);return "background";}diff --git a/products/desktop/packages/ui/src/features/browser-tabs/stripDrop.ts b/products/desktop/packages/ui/src/features/browser-tabs/stripDrop.tsnew file mode 100644index 000000000000..e4ae9b857a35--- /dev/null+++ b/products/desktop/packages/ui/src/features/browser-tabs/stripDrop.ts@@ -0,0 +1,35 @@+export const STRIP_DROP_TYPE = "tab-strip";++export interface StripDropData {+ type: typeof STRIP_DROP_TYPE;+}++export interface BrowserTabDragData {+ type: "browser-tab";+ tabId: string;+}++export function isStripDropData(data: unknown): data is StripDropData {+ return (+ typeof data === "object" &&+ data !== null &&+ (data as { type?: unknown }).type === STRIP_DROP_TYPE+ );+}++export function isBrowserTabDragData(+ data: unknown,+): data is BrowserTabDragData {+ return (+ typeof data === "object" &&+ data !== null &&+ (data as { type?: unknown }).type === "browser-tab" &&+ typeof (data as { tabId?: unknown }).tabId === "string"+ );+}++export function stripTarget(target: unknown): { pillId: string | null } | null {+ if (isBrowserTabDragData(target)) return { pillId: target.tabId };+ if (isStripDropData(target)) return { pillId: null };+ return null;+}diff --git a/products/desktop/packages/ui/src/features/browser-tabs/tabDetach.test.ts b/products/desktop/packages/ui/src/features/browser-tabs/tabDetach.test.tsnew file mode 100644index 000000000000..3f71f59fd914--- /dev/null+++ b/products/desktop/packages/ui/src/features/browser-tabs/tabDetach.test.ts@@ -0,0 +1,21 @@+import type { DragOperation } from "@dnd-kit/abstract";+import { describe, expect, it } from "vitest";+import { DETACH_DISTANCE, DetachFromStrip } from "./tabDetach";++function apply(transform: { x: number; y: number }): { x: number; y: number } {+ const modifier = new DetachFromStrip({} as never);+ return modifier.apply({ transform } as DragOperation);+}++describe("DetachFromStrip", () => {+ it.each([+ { y: 0, expected: 0 },+ { y: DETACH_DISTANCE - 1, expected: 0 },+ { y: -(DETACH_DISTANCE - 1), expected: 0 },+ { y: DETACH_DISTANCE, expected: DETACH_DISTANCE },+ { y: -DETACH_DISTANCE, expected: -DETACH_DISTANCE },+ { y: 120, expected: 120 },+ ])("keeps x and maps y=$y to $expected", ({ y, expected }) => {+ expect(apply({ x: 37, y })).toEqual({ x: 37, y: expected });+ });+});diff --git a/products/desktop/packages/ui/src/features/browser-tabs/tabDetach.ts b/products/desktop/packages/ui/src/features/browser-tabs/tabDetach.tsnew file mode 100644index 000000000000..f6b8feb0a856--- /dev/null+++ b/products/desktop/packages/ui/src/features/browser-tabs/tabDetach.ts@@ -0,0 +1,15 @@+import { type DragOperation, Modifier } from "@dnd-kit/abstract";++export const DETACH_DISTANCE = 24;++export function exceedsDetachDistance(dy: number): boolean {+ return Math.abs(dy) >= DETACH_DISTANCE;+}++export class DetachFromStrip extends Modifier {+ apply({ transform }: DragOperation) {+ return exceedsDetachDistance(transform.y)+ ? transform+ : { ...transform, y: 0 };+ }+}diff --git a/products/desktop/packages/ui/src/features/browser-tabs/tabReorderStore.ts b/products/desktop/packages/ui/src/features/browser-tabs/tabReorderStore.tsindex ad0deea5cea1..786c31ccfefe 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/tabReorderStore.ts+++ b/products/desktop/packages/ui/src/features/browser-tabs/tabReorderStore.ts@@ -1,17 +1,34 @@import { create } from "zustand";-/**- * Transient view state for an in-flight tab drag-reorder. Holds the previewed- * *stored* order (pin-agnostic ids) so the strip can shift pills aside under- * the cursor without touching the domain snapshot mirror — the drop is what- * finally persists. Not persisted; cleared the moment the drag ends or cancels.- */-interface TabReorderStore {+export type TabDragSource = "strip" | "tile";++interface TabDrag {previewOrder: string[] | null;+ draggingTabId: string | null;+ dragSource: TabDragSource | null;+ detached: boolean;+}++interface TabReorderStore extends TabDrag {+ beginDrag: (+ drag: Omit<TabDrag, "previewOrder" | "detached"> & Partial<TabDrag>,+ ) => void;+ endDrag: () => void;setPreviewOrder: (order: string[] | null) => void;+ setDetached: (detached: boolean) => void;}-export const useTabReorderStore = create<TabReorderStore>((set) => ({+const idle: TabDrag = {previewOrder: null,+ draggingTabId: null,+ dragSource: null,+ detached: false,+};++export const useTabReorderStore = create<TabReorderStore>((set) => ({+ ...idle,+ beginDrag: (drag) => set({ ...idle, ...drag }),+ endDrag: () => set(idle),setPreviewOrder: (previewOrder) => set({ previewOrder }),+ setDetached: (detached) => set({ detached }),}));diff --git a/products/desktop/packages/ui/src/features/browser-tabs/useActiveTabId.ts b/products/desktop/packages/ui/src/features/browser-tabs/useActiveTabId.tsnew file mode 100644index 000000000000..7460cabbfc16--- /dev/null+++ b/products/desktop/packages/ui/src/features/browser-tabs/useActiveTabId.ts@@ -0,0 +1,20 @@+import { primaryWindow } from "@posthog/shared";+import { useTileLayoutStore } from "@posthog/ui/features/tab-tiling/tileLayoutStore";+import { focusedTabIn } from "@posthog/ui/features/tab-tiling/tileTree";+import { useRouterState } from "@tanstack/react-router";+import { useTabsSnapshot } from "./useBrowserTabs";++export function useActiveTabId(): string | null {+ const snapshot = useTabsSnapshot();+ const historyTabId = useRouterState({+ select: (s) => s.location.state.tabId ?? null,+ });+ const groups = useTileLayoutStore((s) => s.groups);+ const activeByGroup = useTileLayoutStore((s) => s.activeByGroup);+ const isLive = (tabId: string | null): tabId is string =>+ tabId !== null && snapshot.tabs.some((t) => t.id === tabId);+ const tabId = isLive(historyTabId)+ ? historyTabId+ : (primaryWindow(snapshot)?.activeTabId ?? null);+ return isLive(tabId) ? focusedTabIn(groups, activeByGroup, tabId) : null;+}diff --git a/products/desktop/packages/ui/src/features/browser-tabs/useGoToTab.ts b/products/desktop/packages/ui/src/features/browser-tabs/useGoToTab.tsnew file mode 100644index 000000000000..061994c7145f--- /dev/null+++ b/products/desktop/packages/ui/src/features/browser-tabs/useGoToTab.ts@@ -0,0 +1,106 @@+import { DEFAULT_TAB_HREF, type TabIdentity } from "@posthog/shared";+import { channelSectionFor } from "@posthog/ui/features/canvas/channelSections";+import { useChannelReportsEnabled } from "@posthog/ui/features/feature-flags/useChannelReportsEnabled";+import { useNavigate, useRouter } from "@tanstack/react-router";+import { useCallback } from "react";+import { isTabAppView } from "./tabAppViews";+import { pushTabHistoryEntry } from "./tabHistory";++export type TabRef = { id: string; href: string | null } & TabIdentity;++export function useGoToTab(): (tab: TabRef) => void {+ const navigate = useNavigate();+ const router = useRouter();+ const channelReportsEnabled = useChannelReportsEnabled();+ return useCallback(+ (tab: TabRef) => {+ const state = (prev: object) => ({ ...prev, tabId: tab.id });+ if (tab.href) {+ pushTabHistoryEntry(router.history, tab.href, tab.id);+ return;+ }+ if (tab.taskId && tab.channelId) {+ navigate({+ to: "/spaces/$channelId/tasks/$taskId",+ params: { channelId: tab.channelId, taskId: tab.taskId },+ state,+ });+ } else if (tab.taskId) {+ navigate({+ to: "/tasks/$taskId",+ params: { taskId: tab.taskId },+ state,+ });+ } else if (tab.dashboardId && tab.channelId) {+ navigate({+ to: "/spaces/$channelId/dashboards/$dashboardId",+ params: { channelId: tab.channelId, dashboardId: tab.dashboardId },+ state,+ });+ } else if (tab.channelId) {+ const params = { channelId: tab.channelId };+ const section = channelSectionFor(tab.channelSection);+ if (section) {+ navigate({+ to: `/spaces/$channelId/${section.key}` as const,+ params,+ state,+ });+ } else {+ navigate({ to: "/spaces/$channelId", params, state });+ }+ } else if (tab.appView && isTabAppView(tab.appView)) {+ switch (tab.appView) {+ case "activity":+ navigate({ to: "/activity", state });+ break;+ case "home":+ case "report":+ navigate({ to: "/", state });+ break;+ case "inbox":+ navigate({+ to: channelReportsEnabled ? "/spaces" : "/inbox",+ state,+ });+ break;+ case "agents":+ navigate({+ to: "/settings/$category",+ params: { category: "agents" },+ state,+ });+ break;+ case "loops":+ navigate({ to: "/loops", state });+ break;+ case "archived":+ navigate({ to: "/archived", state });+ break;+ case "skills":+ navigate({ to: "/skills", state });+ break;+ case "mcp-servers":+ navigate({ to: "/mcp-servers", state });+ break;+ case "command-center":+ navigate({ to: "/command-center", state });+ break;+ case "context":+ navigate({ to: "/context", search: { path: undefined }, state });+ break;+ case "settings":+ navigate({ to: "/settings", state });+ break;+ default: {+ const _exhaustive: never = tab.appView;+ return _exhaustive;+ }+ }+ } else {+ navigate({ to: DEFAULT_TAB_HREF, state });+ }+ },+ [channelReportsEnabled, navigate, router.history],+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/canvasDrag.ts b/products/desktop/packages/ui/src/features/canvas/canvasDrag.tsindex 52d42b81010a..bbebcea24d6d 100644--- a/products/desktop/packages/ui/src/features/canvas/canvasDrag.ts+++ b/products/desktop/packages/ui/src/features/canvas/canvasDrag.ts@@ -1,10 +1,26 @@+import { z } from "zod";+export const CANVAS_DRAG_TYPE = "application/x-posthog-canvas-id";+export const CANVAS_DRAG_DETAIL_TYPE = "application/x-posthog-canvas";++const canvasDragDetailSchema = z.object({+ id: z.string(),+ name: z.string().catch(""),+ channelId: z.string().nullable().catch(null),+});++export type CanvasDragDetail = z.infer<typeof canvasDragDetailSchema>;export function writeCanvasDragData(dataTransfer: Pick<DataTransfer, "setData">,canvasId: string,+ detail?: Omit<CanvasDragDetail, "id">,): void {dataTransfer.setData(CANVAS_DRAG_TYPE, canvasId);+ if (detail) {+ const payload: CanvasDragDetail = { id: canvasId, ...detail };+ dataTransfer.setData(CANVAS_DRAG_DETAIL_TYPE, JSON.stringify(payload));+ }}export function readCanvasDragData(@@ -12,3 +28,21 @@ export function readCanvasDragData(): string | null {return dataTransfer.getData(CANVAS_DRAG_TYPE) || null;}++export function readCanvasDragDetail(+ dataTransfer: Pick<DataTransfer, "getData">,+): CanvasDragDetail | null {+ const id = readCanvasDragData(dataTransfer);+ if (!id) return null;+ let parsed: unknown = null;+ try {+ parsed = JSON.parse(dataTransfer.getData(CANVAS_DRAG_DETAIL_TYPE) || "{}");+ } catch {+ parsed = null;+ }+ const detail = canvasDragDetailSchema.safeParse({+ id,+ ...(parsed as object),+ });+ return detail.success ? detail.data : { id, name: "", channelId: null };+}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsxindex 6ff9dedc08c3..10f002b161e3 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx@@ -450,7 +450,10 @@ export function ChannelItemRow({const handleDragStart = useCallback((event: DragEvent) => {if (item.kind === "canvas") {- writeCanvasDragData(event.dataTransfer, item.id);+ writeCanvasDragData(event.dataTransfer, item.id, {+ name: item.title,+ channelId: channelId ?? null,+ });event.dataTransfer.effectAllowed = "copy";return;}@@ -462,7 +465,7 @@ export function ChannelItemRow({event.dataTransfer.effectAllowed = "copyMove";onDragStart?.(event);},- [item.id, item.kind, onDragStart],+ [item.id, item.kind, item.title, channelId, onDragStart],);// A canvas gets the same menu with the items it actually has: command-centrediff --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 1f2016230a85..4cbf19f2ba6d 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@@ -41,13 +41,13 @@ vi.mock("@tanstack/react-router", () => ({select,}: {select: (s: {- location: { pathname: string; href: string };+ location: { pathname: string; href: string; state: object };matches: { routeId: string }[];}) => unknown;}) => {const pathname = usePathname();return select({- location: { pathname, href: pathname },+ location: { pathname, href: pathname, state: {} },matches: [{ routeId: "/spaces/$channelId/tasks/$taskId" }],});},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 d1324e76e092..dd148e474cc8 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@@ -56,7 +56,7 @@ vi.mock("@tanstack/react-router", () => ({select,}: {select: (s: {- location: { pathname: string; href: string };+ location: { pathname: string; href: string; state: object };matches: {routeId: string;fullPath: string;@@ -68,6 +68,7 @@ vi.mock("@tanstack/react-router", () => ({location: {pathname: "/spaces/chan-1/tasks/task-1",href: "/spaces/chan-1/tasks/task-1",+ state: {},},matches: [{diff --git a/products/desktop/packages/ui/src/features/canvas/components/SpaceHeaderRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/SpaceHeaderRow.tsxindex 9d55cb585aec..c9fa22fab189 100644--- a/products/desktop/packages/ui/src/features/canvas/components/SpaceHeaderRow.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/SpaceHeaderRow.tsx@@ -1,6 +1,7 @@import type { Task } from "@posthog/shared/domain-types";import { ActivityDetailCloseButton } from "@posthog/ui/features/canvas/components/ActivityDetailCloseButton";import { useActivitySelection } from "@posthog/ui/features/canvas/stores/activityDetailStore";+import { useActiveTabTiled } from "@posthog/ui/features/tab-tiling/useActiveTabTiled";import { TaskHeaderActions } from "@posthog/ui/features/task-detail/components/TaskHeaderActions";import { ChromeBar } from "@posthog/ui/primitives/ChromeBar";import { useHeaderStore } from "@posthog/ui/shell/headerStore";@@ -13,8 +14,9 @@ import { useHeaderStore } from "@posthog/ui/shell/headerStore";export function SpaceHeaderRow({ task }: { task?: Task }) {const content = useHeaderStore((s) => s.content);const activitySelection = useActivitySelection();+ const tiled = useActiveTabTiled();const showsActivitySession = activitySelection?.kind === "task";- if (!content && !task && !showsActivitySession) return null;+ if (tiled || (!content && !task && !showsActivitySession)) return null;return (<ChromeBar inset="control">diff --git a/products/desktop/packages/ui/src/features/tab-tiling/TabTile.tsx b/products/desktop/packages/ui/src/features/tab-tiling/TabTile.tsxnew file mode 100644index 000000000000..2c87af315d7a--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/TabTile.tsx@@ -0,0 +1,156 @@+import { useDraggable } from "@dnd-kit/react";+import { DotsSixVerticalIcon, XIcon } from "@phosphor-icons/react";+import { Button, cn, Text } from "@posthog/quill";+import type { BrowserTab } from "@posthog/shared";+import {+ isTabAppView,+ resolveTabAppViewDisplay,+} from "@posthog/ui/features/browser-tabs/tabAppViews";+import { ActivityDetailCloseButton } from "@posthog/ui/features/canvas/components/ActivityDetailCloseButton";+import { useActivitySelection } from "@posthog/ui/features/canvas/stores/activityDetailStore";+import { TaskHeaderActions } from "@posthog/ui/features/task-detail/components/TaskHeaderActions";+import { useTasks } from "@posthog/ui/features/tasks/useTasks";+import { ChromeBar } from "@posthog/ui/primitives/ChromeBar";+import type { ReactNode } from "react";+import { TileDropZones } from "./TileDropZones";+import { TileTabContent } from "./TileTabContent";+import { TileProvider } from "./tileContext";+import { TILE_TAB_DRAG_TYPE, type TileTabDragData } from "./tileDrag";++function tileDisplay(tab: BrowserTab): { label: string; icon: ReactNode } {+ const appView =+ tab.appView && isTabAppView(tab.appView)+ ? resolveTabAppViewDisplay(tab.appView, null)+ : null;+ return {+ label: tab.viewState?.title ?? appView?.label ?? "New tab",+ icon: appView?.icon ?? null,+ };+}++function TilePill({+ tab,+ isActive,+ onActivate,+}: {+ tab: BrowserTab;+ isActive: boolean;+ onActivate: (tab: BrowserTab) => void;+}) {+ const { label, icon } = tileDisplay(tab);+ const data: TileTabDragData = { type: TILE_TAB_DRAG_TYPE, tabId: tab.id };+ const { ref } = useDraggable({+ id: `tile-tab-${tab.id}`,+ data,+ feedback: "clone",+ });+ return (+ <button+ ref={ref}+ type="button"+ title={label}+ onClick={() => {+ if (!isActive) onActivate(tab);+ }}+ className={cn(+ "flex h-6 min-w-0 max-w-[280px] cursor-grab items-center gap-1.5 rounded-md px-1.5 text-left",+ isActive+ ? "font-medium"+ : "text-muted-foreground hover:text-foreground",+ "data-[dnd-dragging]:bg-background data-[dnd-dragging]:shadow-lg data-[dnd-dragging]:ring-1 data-[dnd-dragging]:ring-border",+ )}+ >+ <DotsSixVerticalIcon+ size={12}+ className="shrink-0 text-muted-foreground opacity-70"+ />+ {icon && <span className="flex shrink-0 items-center">{icon}</span>}+ <Text className="truncate text-xs">{label}</Text>+ </button>+ );+}++function TileHeader({+ tab,+ isActive,+ onActivate,+ onUntile,+}: {+ tab: BrowserTab;+ isActive: boolean;+ onActivate: (tab: BrowserTab) => void;+ onUntile: (tab: BrowserTab) => void;+}) {+ const activitySelection = useActivitySelection();+ const { data: tasks } = useTasks();+ const task =+ isActive && tab.taskId+ ? tasks?.find((t) => t.id === tab.taskId)+ : undefined;+ return (+ <ChromeBar+ inset="control"+ className={isActive ? "bg-background" : "bg-muted"}+ actions={+ <>+ {task && <TaskHeaderActions task={task} />}+ {isActive && activitySelection?.kind === "task" && (+ <ActivityDetailCloseButton />+ )}+ <Button+ size="icon-sm"+ aria-label="Remove from split"+ className="shrink-0"+ onClick={() => onUntile(tab)}+ >+ <XIcon size={12} />+ </Button>+ </>+ }+ >+ <TilePill tab={tab} isActive={isActive} onActivate={onActivate} />+ </ChromeBar>+ );+}++interface TabTileProps {+ tab: BrowserTab;+ isActive: boolean;+ dropTarget: boolean;+ groupFull: boolean;+ onActivate: (tab: BrowserTab) => void;+ onUntile: (tab: BrowserTab) => void;+}++export function TabTile({+ tab,+ isActive,+ dropTarget,+ groupFull,+ onActivate,+ onUntile,+}: TabTileProps) {+ return (+ <div+ className={cn(+ "relative flex h-full min-h-0 flex-col overflow-hidden",+ !isActive && "opacity-90",+ )}+ data-tile={tab.id}+ data-active={isActive || undefined}+ >+ <TileHeader+ tab={tab}+ isActive={isActive}+ onActivate={onActivate}+ onUntile={onUntile}+ />+ <div className="relative min-h-0 flex-1 overflow-hidden">+ <TileProvider value={{ focused: isActive }}>+ <TileTabContent tab={tab} onActivate={onActivate} />+ </TileProvider>+ </div>+ {dropTarget && <TileDropZones tabId={tab.id} disabled={groupFull} />}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/tab-tiling/TileDropZones.tsx b/products/desktop/packages/ui/src/features/tab-tiling/TileDropZones.tsxnew file mode 100644index 000000000000..b24105821179--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/TileDropZones.tsx@@ -0,0 +1,115 @@+import { useDroppable } from "@dnd-kit/react";+import { useService } from "@posthog/di/react";+import { cn } from "@posthog/quill";+import {+ BROWSER_TABS_CLIENT,+ type BrowserTabsClient,+} from "@posthog/ui/features/browser-tabs/browserTabsClient";+import { type CSSProperties, type DragEvent, useState } from "react";+import { nativeDragKindOf } from "./nativeDrag";+import { dropIntoTile } from "./tileDrop";+import type { TileEdge } from "./tileTree";++export const TILE_DROP_TYPE = "tile-drop";++export interface TileDropData {+ type: typeof TILE_DROP_TYPE;+ tabId: string;+ edge: TileEdge;+}++export function isTileDropData(data: unknown): data is TileDropData {+ return (+ typeof data === "object" &&+ data !== null &&+ (data as { type?: unknown }).type === TILE_DROP_TYPE+ );+}++const BAND = "30%";++const HIT_AREAS: Record<TileEdge, CSSProperties> = {+ left: { top: 0, bottom: 0, left: 0, width: BAND },+ right: { top: 0, bottom: 0, right: 0, width: BAND },+ top: { top: 0, left: BAND, right: BAND, height: BAND },+ bottom: { bottom: 0, left: BAND, right: BAND, height: BAND },+};++const PREVIEWS: Record<TileEdge, string> = {+ left: "inset-y-0 left-0 w-1/2",+ right: "inset-y-0 right-0 w-1/2",+ top: "inset-x-0 top-0 h-1/2",+ bottom: "inset-x-0 bottom-0 h-1/2",+};++function EdgeZone({+ tabId,+ edge,+ disabled,+}: {+ tabId: string;+ edge: TileEdge;+ disabled: boolean;+}) {+ const data: TileDropData = { type: TILE_DROP_TYPE, tabId, edge };+ const { ref, isDropTarget } = useDroppable({+ id: `tile-drop-${tabId}-${edge}`,+ data,+ disabled,+ });+ const client = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);+ const [nativeOver, setNativeOver] = useState(false);+ const acceptsNative = (event: DragEvent) =>+ !disabled && nativeDragKindOf(event.dataTransfer) !== null;+ const onDragOver = (event: DragEvent) => {+ if (!acceptsNative(event)) return;+ event.preventDefault();+ event.dataTransfer.dropEffect = "copy";+ setNativeOver(true);+ };+ const onDrop = (event: DragEvent) => {+ setNativeOver(false);+ if (!acceptsNative(event)) return;+ event.preventDefault();+ event.stopPropagation();+ dropIntoTile(client, event.dataTransfer, tabId, edge);+ };+ return (+ <>+ {/* biome-ignore lint/a11y/noStaticElementInteractions: a pointer-only drop target; the keyboard path to tiling is the tab menu */}+ <div+ ref={ref}+ className="pointer-events-auto absolute"+ style={HIT_AREAS[edge]}+ onDragOver={onDragOver}+ onDragLeave={() => setNativeOver(false)}+ onDrop={onDrop}+ />+ {(isDropTarget || nativeOver) && (+ <div+ aria-hidden+ className={cn(+ "pointer-events-none absolute rounded-sm border-2 border-accent-8 bg-(--accent-a4)",+ PREVIEWS[edge],+ )}+ />+ )}+ </>+ );+}++export function TileDropZones({+ tabId,+ disabled = false,+}: {+ tabId: string;+ disabled?: boolean;+}) {+ return (+ <div className="pointer-events-none absolute inset-0 z-50">+ {(Object.keys(HIT_AREAS) as TileEdge[]).map((edge) => (+ <EdgeZone key={edge} tabId={tabId} edge={edge} disabled={disabled} />+ ))}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/tab-tiling/TileLayout.tsx b/products/desktop/packages/ui/src/features/tab-tiling/TileLayout.tsxnew file mode 100644index 000000000000..2d0213f6b3c4--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/TileLayout.tsx@@ -0,0 +1,188 @@+import { cn } from "@posthog/quill";+import type { BrowserTab } from "@posthog/shared";+import { usePinnedTabsStore } from "@posthog/ui/features/browser-tabs/pinnedTabsStore";+import { useTabReorderStore } from "@posthog/ui/features/browser-tabs/tabReorderStore";+import { useActiveTabId } from "@posthog/ui/features/browser-tabs/useActiveTabId";+import { useTabsSnapshot } from "@posthog/ui/features/browser-tabs/useBrowserTabs";+import { useGoToTab } from "@posthog/ui/features/browser-tabs/useGoToTab";+import {+ Fragment,+ type ReactNode,+ useCallback,+ useEffect,+ useMemo,+ useRef,+} from "react";+import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";+import { useNativeDragKind } from "./nativeDrag";+import { TabTile } from "./TabTile";+import { TileDropZones } from "./TileDropZones";+import { untileTracked } from "./tileActions";+import { useTileLayoutStore } from "./tileLayoutStore";+import {+ groupForTab,+ MAX_TILES_PER_GROUP,+ nodeId,+ type TileNode,+ tabIdsIn,+} from "./tileTree";+import { useFocusTab } from "./useFocusTab";++const MIN_TILE_PERCENT = 15;++interface TileTreeProps {+ node: TileNode;+ tabsById: Map<string, BrowserTab>;+ activeTabId: string;+ draggingTabId: string | null;+ nativeDragActive: boolean;+ groupFull: boolean;+ onActivate: (tab: BrowserTab) => void;+ onUntile: (tab: BrowserTab) => void;+}++function TileTree(props: TileTreeProps) {+ const { node, tabsById, activeTabId } = props;+ const setSplitSizes = useTileLayoutStore((s) => s.setSplitSizes);+ const liveSizes = useRef<number[] | null>(null);+ if (node.type === "tab") {+ const tab = tabsById.get(node.tabId);+ if (!tab) return null;+ return (+ <TabTile+ tab={tab}+ isActive={tab.id === activeTabId}+ dropTarget={+ props.nativeDragActive ||+ (props.draggingTabId !== null && props.draggingTabId !== tab.id)+ }+ groupFull={props.groupFull}+ onActivate={props.onActivate}+ onUntile={props.onUntile}+ />+ );+ }+ const equalShare = 100 / node.children.length;+ return (+ <PanelGroup+ direction={node.direction}+ onLayout={(sizes) => {+ liveSizes.current = sizes;+ }}+ >+ {node.children.map((child, index) => (+ <Fragment key={nodeId(child)}>+ {index > 0 && (+ <PanelResizeHandle+ onDragging={(dragging) => {+ if (!dragging && liveSizes.current) {+ setSplitSizes(node.id, liveSizes.current);+ }+ }}+ className={cn(+ "relative z-10 bg-border transition-colors hover:bg-accent-8 data-[resize-handle-active]:bg-accent-8",+ node.direction === "horizontal" ? "w-px" : "h-px",+ )}+ />+ )}+ <Panel+ id={nodeId(child)}+ order={index}+ defaultSize={node.sizes?.[index] ?? equalShare}+ minSize={MIN_TILE_PERCENT}+ >+ <TileTree {...props} node={child} />+ </Panel>+ </Fragment>+ ))}+ </PanelGroup>+ );+}++export function TileLayout({ children }: { children: ReactNode }) {+ const goToTab = useGoToTab();+ const snapshot = useTabsSnapshot();+ const groups = useTileLayoutStore((s) => s.groups);+ const prune = useTileLayoutStore((s) => s.prune);+ const noteActive = useTileLayoutStore((s) => s.noteActive);+ const pinnedTabIds = usePinnedTabsStore((s) => s.pinnedTabIds);+ const rawDraggingTabId = useTabReorderStore((s) =>+ s.detached ? s.draggingTabId : null,+ );+ const dragSource = useTabReorderStore((s) => s.dragSource);+ const draggingTabId = useMemo(() => {+ if (!rawDraggingTabId) return null;+ if (dragSource === "tile") return rawDraggingTabId;+ const loose =+ !groupForTab(groups, rawDraggingTabId) &&+ !pinnedTabIds.includes(rawDraggingTabId);+ return loose ? rawDraggingTabId : null;+ }, [rawDraggingTabId, dragSource, groups, pinnedTabIds]);+ const activeTabId = useActiveTabId();+ const focusTab = useFocusTab(activeTabId);+ const nativeDragActive = useNativeDragKind() !== null;++ useEffect(() => {+ if (snapshot.windows.length === 0) return;+ prune(snapshot.tabs.map((t) => t.id));+ }, [snapshot, prune]);++ const tabsById = useMemo(+ () => new Map(snapshot.tabs.map((t) => [t.id, t])),+ [snapshot.tabs],+ );++ const onUntile = useCallback(+ (tab: BrowserTab) => {+ const group = groupForTab(groups, tab.id);+ const remaining = group+ ? tabIdsIn(group.root).filter((id) => id !== tab.id)+ : [];+ untileTracked(tab.id);+ if (tab.id === activeTabId && remaining.length > 1) {+ const next = tabsById.get(remaining[0]);+ if (next) goToTab(next);+ }+ },+ [groups, activeTabId, tabsById, goToTab],+ );++ const group = activeTabId ? groupForTab(groups, activeTabId) : null;++ useEffect(() => {+ if (activeTabId) noteActive(activeTabId);+ }, [activeTabId, noteActive]);++ if (!group || !activeTabId) {+ return (+ <div className="relative h-full">+ {children}+ {activeTabId &&+ (nativeDragActive ||+ (draggingTabId && draggingTabId !== activeTabId)) && (+ <TileDropZones tabId={activeTabId} />+ )}+ </div>+ );+ }++ const groupTabIds = tabIdsIn(group.root);+ const groupFull =+ groupTabIds.length >= MAX_TILES_PER_GROUP &&+ !(draggingTabId && groupTabIds.includes(draggingTabId));++ return (+ <div className="h-full" data-testid="tile-layout">+ <TileTree+ node={group.root}+ tabsById={tabsById}+ activeTabId={activeTabId}+ draggingTabId={draggingTabId}+ nativeDragActive={nativeDragActive}+ groupFull={groupFull}+ onActivate={focusTab}+ onUntile={onUntile}+ />+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/tab-tiling/TileRouter.tsx b/products/desktop/packages/ui/src/features/tab-tiling/TileRouter.tsxnew file mode 100644index 000000000000..81471626c1f7--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/TileRouter.tsx@@ -0,0 +1,36 @@+import type { BrowserTab } from "@posthog/shared";+import { writeBackgroundTabTarget } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";+import {+ createMemoryHistory,+ createRouter,+ RouterProvider,+ useRouter,+} from "@tanstack/react-router";+import { useEffect, useState } from "react";++export function TileRouter({ tab, href }: { tab: BrowserTab; href: string }) {+ const outer = useRouter();+ const [inner] = useState(() =>+ createRouter({+ ...outer.options,+ history: createMemoryHistory({ initialEntries: [href] }),+ scrollRestoration: false,+ }),+ );++ useEffect(() => {+ return inner.subscribe("onResolved", ({ toLocation }) => {+ if (toLocation.href === tab.href) return;+ writeBackgroundTabTarget(tab, {+ href: toLocation.href,+ dashboardId: tab.dashboardId,+ taskId: tab.taskId,+ channelId: tab.channelId,+ channelSection: tab.channelSection,+ appView: tab.appView,+ });+ });+ }, [inner, tab]);++ return <RouterProvider router={inner} />;+}diff --git a/products/desktop/packages/ui/src/features/tab-tiling/TileTabContent.tsx b/products/desktop/packages/ui/src/features/tab-tiling/TileTabContent.tsxnew file mode 100644index 000000000000..3905dc121383--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/TileTabContent.tsx@@ -0,0 +1,89 @@+import { Button, Text } from "@posthog/quill";+import type { BrowserTab } from "@posthog/shared";+import { WebsiteDashboard } from "@posthog/ui/features/canvas/components/WebsiteDashboard";+import { TaskDetail } from "@posthog/ui/features/task-detail/components/TaskDetail";+import {+ getCachedTask,+ getCachedTaskDetail,+ taskDetailQuery,+} from "@posthog/ui/features/tasks/queries";+import { pickFreshestTask } from "@posthog/ui/features/tasks/taskFreshness";+import { TaskDetailSkeleton } from "@posthog/ui/router/routeSkeletons";+import { useQuery } from "@tanstack/react-query";+import { memo } from "react";+import { TileRouter } from "./TileRouter";++function TiledTask({+ taskId,+ channelId,+}: {+ taskId: string;+ channelId: string | null;+}) {+ const cached = getCachedTaskDetail(taskId) ?? getCachedTask(taskId) ?? null;+ const { data: fetched, isError } = useQuery(taskDetailQuery(taskId));+ const task = pickFreshestTask(fetched, cached);+ if (task)+ return <TaskDetail task={task} channelId={channelId ?? undefined} />;+ if (isError) {+ return (+ <Notice>Couldn't load this task. Refresh the app to try again.</Notice>+ );+ }+ return <TaskDetailSkeleton />;+}++function Notice({+ children,+ action,+}: {+ children: string;+ action?: { label: string; onClick: () => void };+}) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center">+ <Text className="text-muted-foreground text-sm">{children}</Text>+ {action && (+ <Button variant="outline" size="sm" onClick={action.onClick}>+ {action.label}+ </Button>+ )}+ </div>+ );+}++function TileTabContentView({+ tab,+ onActivate,+}: {+ tab: BrowserTab;+ onActivate: (tab: BrowserTab) => void;+}) {+ if (tab.taskId) {+ return <TiledTask taskId={tab.taskId} channelId={tab.channelId} />;+ }+ if (tab.dashboardId)+ return <WebsiteDashboard dashboardId={tab.dashboardId} />;+ if (tab.href) return <TileRouter key={tab.id} tab={tab} href={tab.href} />;+ return (+ <Notice action={{ label: "Show this tab", onClick: () => onActivate(tab) }}>+ This page only shows in the active tile.+ </Notice>+ );+}++function sameContent(a: BrowserTab, b: BrowserTab): boolean {+ return (+ a.id === b.id &&+ a.href === b.href &&+ a.taskId === b.taskId &&+ a.channelId === b.channelId &&+ a.dashboardId === b.dashboardId+ );+}++export const TileTabContent = memo(+ TileTabContentView,+ (prev, next) =>+ sameContent(prev.tab, next.tab) && prev.onActivate === next.onActivate,+);diff --git a/products/desktop/packages/ui/src/features/tab-tiling/nativeDrag.ts b/products/desktop/packages/ui/src/features/tab-tiling/nativeDrag.tsnew file mode 100644index 000000000000..1374f8051881--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/nativeDrag.ts@@ -0,0 +1,38 @@+import { CANVAS_DRAG_TYPE } from "@posthog/ui/features/canvas/canvasDrag";+import { TASK_DRAG_TYPE } from "@posthog/ui/features/sidebar/taskDrag";+import { useEffect, useState } from "react";++export type NativeDragKind = "task" | "canvas";++export function nativeDragKindOf(+ dataTransfer: Pick<DataTransfer, "types"> | null,+): NativeDragKind | null {+ const types = dataTransfer?.types;+ if (!types) return null;+ if (types.includes(TASK_DRAG_TYPE)) return "task";+ if (types.includes(CANVAS_DRAG_TYPE)) return "canvas";+ return null;+}++export function useNativeDragKind(): NativeDragKind | null {+ const [kind, setKind] = useState<NativeDragKind | null>(null);+ useEffect(() => {+ const onEnter = (event: DragEvent) =>+ setKind(nativeDragKindOf(event.dataTransfer));+ const onLeaveWindow = (event: DragEvent) => {+ if (event.relatedTarget === null) setKind(null);+ };+ const clear = () => setKind(null);+ window.addEventListener("dragenter", onEnter);+ window.addEventListener("dragleave", onLeaveWindow);+ window.addEventListener("drop", clear);+ window.addEventListener("dragend", clear);+ return () => {+ window.removeEventListener("dragenter", onEnter);+ window.removeEventListener("dragleave", onLeaveWindow);+ window.removeEventListener("drop", clear);+ window.removeEventListener("dragend", clear);+ };+ }, []);+ return kind;+}diff --git a/products/desktop/packages/ui/src/features/tab-tiling/tileActions.ts b/products/desktop/packages/ui/src/features/tab-tiling/tileActions.tsnew file mode 100644index 000000000000..5c05e883f8e5--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/tileActions.ts@@ -0,0 +1,32 @@+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import { track } from "@posthog/ui/shell/analytics";+import { useTileLayoutStore } from "./tileLayoutStore";+import { groupForTab, type TileEdge, tabIdsIn } from "./tileTree";++export type TileSource = "strip" | "tile" | "sidebar";++export function tileBeside(+ tabId: string,+ targetTabId: string,+ edge: TileEdge,+ source: TileSource,+): void {+ const store = useTileLayoutStore.getState();+ store.tileTab(tabId, targetTabId, edge);+ const group = groupForTab(store.groups, tabId);+ track(ANALYTICS_EVENTS.BROWSER_TAB_TILED, {+ edge,+ source,+ tile_count: group ? tabIdsIn(group.root).length : 0,+ });+}++export function untileTracked(tabId: string): void {+ const store = useTileLayoutStore.getState();+ const group = groupForTab(store.groups, tabId);+ const remaining = group ? tabIdsIn(group.root).length - 1 : 0;+ store.untileTab(tabId);+ track(ANALYTICS_EVENTS.BROWSER_TAB_UNTILED, {+ tile_count: remaining > 1 ? remaining : 0,+ });+}diff --git a/products/desktop/packages/ui/src/features/tab-tiling/tileContext.ts b/products/desktop/packages/ui/src/features/tab-tiling/tileContext.tsnew file mode 100644index 000000000000..babf8950e847--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/tileContext.ts@@ -0,0 +1,14 @@+import { createContext, useContext } from "react";++const TileContext = createContext<{ focused: boolean } | null>(null);++export const TileProvider = TileContext.Provider;++export function useInTile(): boolean {+ return useContext(TileContext) !== null;+}++export function useInUnfocusedTile(): boolean {+ const tile = useContext(TileContext);+ return tile !== null && !tile.focused;+}diff --git a/products/desktop/packages/ui/src/features/tab-tiling/tileDrag.ts b/products/desktop/packages/ui/src/features/tab-tiling/tileDrag.tsnew file mode 100644index 000000000000..bdc7ac7c5b9d--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/tileDrag.ts@@ -0,0 +1,15 @@+export const TILE_TAB_DRAG_TYPE = "tile-tab";++export interface TileTabDragData {+ type: typeof TILE_TAB_DRAG_TYPE;+ tabId: string;+}++export function isTileTabDragData(data: unknown): data is TileTabDragData {+ return (+ typeof data === "object" &&+ data !== null &&+ (data as { type?: unknown }).type === TILE_TAB_DRAG_TYPE &&+ typeof (data as { tabId?: unknown }).tabId === "string"+ );+}diff --git a/products/desktop/packages/ui/src/features/tab-tiling/tileDrop.ts b/products/desktop/packages/ui/src/features/tab-tiling/tileDrop.tsnew file mode 100644index 000000000000..0be40e4283b7--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/tileDrop.ts@@ -0,0 +1,100 @@+import type { BrowserTabsClient } from "@posthog/ui/features/browser-tabs/browserTabsClient";+import {+ type BrowserTabDestination,+ findTabForDestination,+ openInNewBrowserTabSync,+} from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";+import { readMirror } from "@posthog/ui/features/browser-tabs/tabsSync";+import { readCanvasDragDetail } from "@posthog/ui/features/canvas/canvasDrag";+import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";+import {+ consumeTaskDrop,+ readTaskDragData,+} from "@posthog/ui/features/sidebar/taskDrag";+import { getCachedTask } from "@posthog/ui/features/tasks/queries";+import { tileBeside } from "./tileActions";+import { useTileLayoutStore } from "./tileLayoutStore";+import {+ groupForTab,+ MAX_TILES_PER_GROUP,+ type TileEdge,+ tabIdsIn,+} from "./tileTree";++function channelFor(+ targetTabId: string,+ explicit: string | null,+): string | null {+ if (explicit) return explicit;+ const target = readMirror().tabs.find((t) => t.id === targetTabId);+ return (+ useCurrentChannelStore.getState().currentChannelId ??+ target?.channelId ??+ null+ );+}++function taskDestination(+ taskId: string,+ targetTabId: string,+): BrowserTabDestination {+ const channelId = channelFor(targetTabId, null);+ return {+ href: channelId+ ? `/spaces/${channelId}/tasks/${taskId}`+ : `/tasks/${taskId}`,+ title: getCachedTask(taskId)?.title,+ taskId,+ channelId,+ };+}++function canvasDestination(+ canvas: { id: string; name: string; channelId: string | null },+ targetTabId: string,+): BrowserTabDestination | null {+ const channelId = channelFor(targetTabId, canvas.channelId);+ if (!channelId) return null;+ return {+ href: `/spaces/${channelId}/dashboards/${canvas.id}`,+ title: canvas.name || undefined,+ dashboardId: canvas.id,+ channelId,+ };+}++export function destinationsFromDrop(+ dataTransfer: Pick<DataTransfer, "getData">,+ targetTabId: string,+): BrowserTabDestination[] {+ const taskIds = readTaskDragData(dataTransfer);+ if (taskIds.length > 0) {+ consumeTaskDrop();+ return taskIds.map((taskId) => taskDestination(taskId, targetTabId));+ }+ const canvas = readCanvasDragDetail(dataTransfer);+ if (!canvas) return [];+ const destination = canvasDestination(canvas, targetTabId);+ return destination ? [destination] : [];+}++export function dropIntoTile(+ client: BrowserTabsClient,+ dataTransfer: Pick<DataTransfer, "getData">,+ targetTabId: string,+ edge: TileEdge,+): void {+ const destinations = destinationsFromDrop(dataTransfer, targetTabId);+ for (const destination of destinations) {+ const target = groupForTab(+ useTileLayoutStore.getState().groups,+ targetTabId,+ );+ if (target && tabIdsIn(target.root).length >= MAX_TILES_PER_GROUP) break;+ const tabId =+ findTabForDestination(destination)?.id ??+ openInNewBrowserTabSync(client, destination, { focus: false });+ if (!tabId || tabId === targetTabId) continue;+ tileBeside(tabId, targetTabId, edge, "sidebar");+ }+}diff --git a/products/desktop/packages/ui/src/features/tab-tiling/tileLayoutStore.ts b/products/desktop/packages/ui/src/features/tab-tiling/tileLayoutStore.tsnew file mode 100644index 000000000000..0136290e759d--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/tileLayoutStore.ts@@ -0,0 +1,127 @@+import { create } from "zustand";+import { persist } from "zustand/middleware";+import {+ groupForTab,+ pruneActiveByGroup,+ pruneGroups,+ setSplitSizes,+ type TileEdge,+ type TileGroup,+ tileTab,+ untileTab,+} from "./tileTree";++const STORAGE_KEY = "browser-tabs-tiling-storage";++interface TileLayoutStore {+ groups: TileGroup[];+ activeByGroup: Record<string, string>;+ names: Record<string, string>;+ nextSplitNumber: number;+ tileTab: (tabId: string, targetTabId: string, edge: TileEdge) => void;+ renameGroup: (groupId: string, name: string) => void;+ untileTab: (tabId: string) => void;+ separate: (groupId: string) => void;+ noteActive: (tabId: string) => void;+ setSplitSizes: (splitId: string, sizes: number[]) => void;+ prune: (liveTabIds: string[]) => void;+}++function withGroups(+ state: TileLayoutStore,+ groups: TileGroup[],+): Partial<TileLayoutStore> {+ if (groups === state.groups) return state;+ const named = nameNewGroups(+ groups,+ pruneNames(groups, state.names),+ state.nextSplitNumber,+ );+ return {+ groups,+ activeByGroup: pruneActiveByGroup(groups, state.activeByGroup),+ names: named.names,+ nextSplitNumber: named.next,+ };+}++function nameNewGroups(+ groups: TileGroup[],+ names: Record<string, string>,+ next: number,+): { names: Record<string, string>; next: number } {+ const unnamed = groups.filter((g) => !names[g.id]);+ if (unnamed.length === 0) return { names, next };+ const out = { ...names };+ let n = next;+ for (const g of unnamed) out[g.id] = `Split ${n++}`;+ return { names: out, next: n };+}++function pruneNames(+ groups: TileGroup[],+ names: Record<string, string>,+): Record<string, string> {+ const live = groups.filter((g) => names[g.id]);+ if (live.length === Object.keys(names).length) return names;+ return Object.fromEntries(live.map((g) => [g.id, names[g.id]]));+}++export const useTileLayoutStore = create<TileLayoutStore>()(+ persist(+ (set, get) => {+ const update = (+ next: (state: TileLayoutStore) => Partial<TileLayoutStore>,+ ) => {+ const state = get();+ const partial = next(state);+ if (partial !== state) set(partial);+ };+ const updateGroups = (next: (state: TileLayoutStore) => TileGroup[]) =>+ update((state) => withGroups(state, next(state)));+ return {+ groups: [],+ activeByGroup: {},+ names: {},+ nextSplitNumber: 1,+ renameGroup: (groupId, name) =>+ update((state) => {+ const trimmed = name.trim();+ if (trimmed) {+ return { names: { ...state.names, [groupId]: trimmed } };+ }+ return {+ names: {+ ...state.names,+ [groupId]: `Split ${state.nextSplitNumber}`,+ },+ nextSplitNumber: state.nextSplitNumber + 1,+ };+ }),+ tileTab: (tabId, targetTabId, edge) =>+ updateGroups((state) =>+ tileTab(state.groups, tabId, targetTabId, edge, () =>+ crypto.randomUUID(),+ ),+ ),+ untileTab: (tabId) =>+ updateGroups((state) => untileTab(state.groups, tabId)),+ separate: (groupId) =>+ updateGroups((state) => state.groups.filter((g) => g.id !== groupId)),+ noteActive: (tabId) =>+ update((state) => {+ const group = groupForTab(state.groups, tabId);+ if (!group || state.activeByGroup[group.id] === tabId) return state;+ return {+ activeByGroup: { ...state.activeByGroup, [group.id]: tabId },+ };+ }),+ setSplitSizes: (splitId, sizes) =>+ updateGroups((state) => setSplitSizes(state.groups, splitId, sizes)),+ prune: (liveTabIds) =>+ updateGroups((state) => pruneGroups(state.groups, liveTabIds)),+ };+ },+ { name: STORAGE_KEY },+ ),+);diff --git a/products/desktop/packages/ui/src/features/tab-tiling/tileTree.test.ts b/products/desktop/packages/ui/src/features/tab-tiling/tileTree.test.tsnew file mode 100644index 000000000000..f7044f36a704--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/tileTree.test.ts@@ -0,0 +1,166 @@+import { describe, expect, it } from "vitest";+import {+ groupForTab,+ lastActiveIn,+ MAX_TILES_PER_GROUP,+ pruneActiveByGroup,+ pruneGroups,+ setSplitSizes,+ type TileEdge,+ type TileGroup,+ type TileNode,+ tileTab,+ untileTab,+} from "./tileTree";++function ids(): () => string {+ let n = 0;+ return () => `s${++n}`;+}++function leaf(tabId: string): TileNode {+ return { type: "tab", tabId };+}++function split(+ id: string,+ direction: "horizontal" | "vertical",+ children: TileNode[],+): TileNode {+ return { type: "split", id, direction, children };+}++function build(steps: [string, string, TileEdge][]): TileGroup[] {+ const makeId = ids();+ return steps.reduce<TileGroup[]>(+ (groups, [tabId, target, edge]) =>+ tileTab(groups, tabId, target, edge, makeId),+ [],+ );+}++describe("tileTree", () => {+ it.each<{ edge: TileEdge; expected: TileNode }>([+ {+ edge: "right",+ expected: split("s1", "horizontal", [leaf("a"), leaf("b")]),+ },+ {+ edge: "left",+ expected: split("s1", "horizontal", [leaf("b"), leaf("a")]),+ },+ {+ edge: "bottom",+ expected: split("s1", "vertical", [leaf("a"), leaf("b")]),+ },+ { edge: "top", expected: split("s1", "vertical", [leaf("b"), leaf("a")]) },+ ])(+ "dropping on the $edge edge creates a split in that order",+ ({ edge, expected }) => {+ const groups = build([["b", "a", edge]]);+ expect(groups).toEqual([{ id: "s1", root: expected }]);+ },+ );++ it("keeps three tabs on one axis as one flat split", () => {+ const groups = build([+ ["b", "a", "right"],+ ["c", "b", "right"],+ ]);+ expect(groups[0].root).toEqual(+ split("s1", "horizontal", [leaf("a"), leaf("b"), leaf("c")]),+ );+ });++ it("nests a split on the other axis to form a grid", () => {+ const groups = build([+ ["b", "a", "right"],+ ["c", "a", "bottom"],+ ["d", "b", "bottom"],+ ]);+ expect(groups[0].root).toEqual(+ split("s1", "horizontal", [+ split("s2", "vertical", [leaf("a"), leaf("c")]),+ split("s3", "vertical", [leaf("b"), leaf("d")]),+ ]),+ );+ });++ it("moves a tiled tab into another group when dropped there", () => {+ const groups = build([+ ["b", "a", "right"],+ ["d", "c", "right"],+ ["b", "d", "bottom"],+ ]);+ expect(groupForTab(groups, "a")).toBeNull();+ expect(groups).toEqual([+ {+ id: "s2",+ root: split("s2", "horizontal", [+ leaf("c"),+ split("s3", "vertical", [leaf("d"), leaf("b")]),+ ]),+ },+ ]);+ });++ it("refuses a drop when the target group is full", () => {+ const steps: [string, string, TileEdge][] = [];+ for (let i = 1; i < MAX_TILES_PER_GROUP; i++) {+ steps.push([`t${i}`, "a", "right"]);+ }+ const full = build(steps);+ expect(tileTab(full, "extra", "a", "bottom", ids())).toBe(full);+ });++ it("ignores a drop of a tab onto its own tile", () => {+ const groups = build([["b", "a", "right"]]);+ expect(tileTab(groups, "a", "a", "left", ids())).toBe(groups);+ });++ it("collapses the parent split when a tile leaves a grid", () => {+ const groups = build([+ ["b", "a", "right"],+ ["c", "a", "bottom"],+ ]);+ expect(untileTab(groups, "c")[0].root).toEqual(+ split("s1", "horizontal", [leaf("a"), leaf("b")]),+ );+ });++ it("dissolves the group when only one tile remains", () => {+ const groups = build([["b", "a", "right"]]);+ expect(untileTab(groups, "b")).toEqual([]);+ });++ it("records sizes and returns the same array for an unchanged layout", () => {+ const groups = build([["b", "a", "right"]]);+ const sized = setSplitSizes(groups, "s1", [30, 70]);+ expect(sized[0].root).toMatchObject({ sizes: [30, 70] });+ expect(setSplitSizes(sized, "s1", [30, 70])).toBe(sized);+ });++ it("prunes closed tabs and keeps the array when nothing closed", () => {+ const groups = build([+ ["b", "a", "right"],+ ["c", "a", "bottom"],+ ]);+ expect(pruneGroups(groups, ["a", "b", "c"])).toBe(groups);+ expect(pruneGroups(groups, ["a", "b"])[0].root).toEqual(+ split("s1", "horizontal", [leaf("a"), leaf("b")]),+ );+ expect(pruneGroups(groups, ["c"])).toEqual([]);+ });++ it("reopens a split on its first tile once the remembered tile left", () => {+ const groups = tileTab([], "b", "a", "right", ids());+ const group = groups[0];+ expect(lastActiveIn(group, { [group.id]: "b" })).toBe("b");+ const next = tileTab(groups, "c", "a", "right", ids());+ const remembered = pruneActiveByGroup(untileTab(next, "b"), {+ [group.id]: "b",+ });+ expect(remembered).toEqual({});+ expect(lastActiveIn(untileTab(next, "b")[0], remembered)).toBe("a");+ });+});diff --git a/products/desktop/packages/ui/src/features/tab-tiling/tileTree.ts b/products/desktop/packages/ui/src/features/tab-tiling/tileTree.tsnew file mode 100644index 000000000000..9c433ad61d49--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/tileTree.ts@@ -0,0 +1,203 @@+export type TileEdge = "left" | "right" | "top" | "bottom";+export type TileDirection = "horizontal" | "vertical";++export interface TileLeaf {+ type: "tab";+ tabId: string;+}++export interface TileSplit {+ type: "split";+ id: string;+ direction: TileDirection;+ children: TileNode[];+ sizes?: number[];+}++export type TileNode = TileLeaf | TileSplit;++export interface TileGroup {+ id: string;+ root: TileNode;+}++export const MAX_TILES_PER_GROUP = 4;++export function tabIdsIn(node: TileNode): string[] {+ return node.type === "tab"+ ? [node.tabId]+ : node.children.flatMap((child) => tabIdsIn(child));+}++export function groupForTab(+ groups: readonly TileGroup[],+ tabId: string,+): TileGroup | null {+ return groups.find((g) => tabIdsIn(g.root).includes(tabId)) ?? null;+}++export function nodeId(node: TileNode): string {+ return node.type === "tab" ? node.tabId : node.id;+}++function directionForEdge(edge: TileEdge): TileDirection {+ return edge === "left" || edge === "right" ? "horizontal" : "vertical";+}++function removeLeaf(node: TileNode, tabId: string): TileNode | null {+ if (node.type === "tab") return node.tabId === tabId ? null : node;+ const children = node.children+ .map((child) => removeLeaf(child, tabId))+ .filter((child): child is TileNode => child !== null);+ const unchanged =+ children.length === node.children.length &&+ children.every((child, i) => child === node.children[i]);+ if (unchanged) return node;+ if (children.length === 0) return null;+ if (children.length === 1) return children[0];+ if (children.length === node.children.length) return { ...node, children };+ return { type: "split", id: node.id, direction: node.direction, children };+}++function insertBeside(+ node: TileNode,+ targetTabId: string,+ leaf: TileLeaf,+ edge: TileEdge,+ makeId: () => string,+): TileNode {+ const direction = directionForEdge(edge);+ const before = edge === "left" || edge === "top";+ if (node.type === "tab") {+ if (node.tabId !== targetTabId) return node;+ return {+ type: "split",+ id: makeId(),+ direction,+ children: before ? [leaf, node] : [node, leaf],+ };+ }+ const index = node.children.findIndex(+ (child) => child.type === "tab" && child.tabId === targetTabId,+ );+ if (index !== -1 && node.direction === direction) {+ const children = [...node.children];+ children.splice(before ? index : index + 1, 0, leaf);+ return { type: "split", id: node.id, direction, children };+ }+ return {+ ...node,+ children: node.children.map((child) =>+ insertBeside(child, targetTabId, leaf, edge, makeId),+ ),+ };+}++export function untileTab(groups: TileGroup[], tabId: string): TileGroup[] {+ const group = groupForTab(groups, tabId);+ if (!group) return groups;+ const root = removeLeaf(group.root, tabId);+ return groups.flatMap((g) => {+ if (g.id !== group.id) return [g];+ return root && root.type === "split" ? [{ id: g.id, root }] : [];+ });+}++export function tileTab(+ groups: TileGroup[],+ tabId: string,+ targetTabId: string,+ edge: TileEdge,+ makeId: () => string,+): TileGroup[] {+ if (tabId === targetTabId) return groups;+ const without = untileTab(groups, tabId);+ const existing = groupForTab(without, targetTabId);+ const targetRoot: TileNode = existing?.root ?? {+ type: "tab",+ tabId: targetTabId,+ };+ if (tabIdsIn(targetRoot).length >= MAX_TILES_PER_GROUP) return groups;+ const leaf: TileLeaf = { type: "tab", tabId };+ const root = insertBeside(targetRoot, targetTabId, leaf, edge, makeId);+ const next: TileGroup = { id: existing?.id ?? nodeId(root), root };+ return existing+ ? without.map((g) => (g.id === next.id ? next : g))+ : [...without, next];+}++export function lastActiveIn(+ group: TileGroup,+ activeByGroup: Readonly<Record<string, string>>,+): string {+ const ids = tabIdsIn(group.root);+ const remembered = activeByGroup[group.id];+ return remembered && ids.includes(remembered) ? remembered : ids[0];+}++export function focusedTabIn(+ groups: readonly TileGroup[],+ activeByGroup: Readonly<Record<string, string>>,+ tabId: string,+): string {+ const group = groupForTab(groups, tabId);+ return group ? lastActiveIn(group, activeByGroup) : tabId;+}++export function pruneActiveByGroup(+ groups: readonly TileGroup[],+ activeByGroup: Readonly<Record<string, string>>,+): Record<string, string> {+ const next: Record<string, string> = {};+ for (const group of groups) {+ const tabId = activeByGroup[group.id];+ if (tabId && tabIdsIn(group.root).includes(tabId)) next[group.id] = tabId;+ }+ const same =+ Object.keys(next).length === Object.keys(activeByGroup).length &&+ Object.entries(next).every(([id, tabId]) => activeByGroup[id] === tabId);+ return same ? activeByGroup : next;+}++function sameSizes(a: number[] | undefined, b: number[]): boolean {+ return !!a && a.length === b.length && a.every((v, i) => v === b[i]);+}++function withSizes(node: TileNode, splitId: string, sizes: number[]): TileNode {+ if (node.type === "tab") return node;+ if (node.id === splitId) {+ return sameSizes(node.sizes, sizes) ? node : { ...node, sizes };+ }+ const children = node.children.map((child) =>+ withSizes(child, splitId, sizes),+ );+ return children.every((child, i) => child === node.children[i])+ ? node+ : { ...node, children };+}++export function setSplitSizes(+ groups: TileGroup[],+ splitId: string,+ sizes: number[],+): TileGroup[] {+ const next = groups.map((g) => {+ const root = withSizes(g.root, splitId, sizes);+ return root === g.root ? g : { id: g.id, root };+ });+ return next.every((g, i) => g === groups[i]) ? groups : next;+}++export function pruneGroups(+ groups: TileGroup[],+ liveTabIds: readonly string[],+): TileGroup[] {+ const live = new Set(liveTabIds);+ let next = groups;+ for (const group of groups) {+ for (const tabId of tabIdsIn(group.root)) {+ if (!live.has(tabId)) next = untileTab(next, tabId);+ }+ }+ return next;+}diff --git a/products/desktop/packages/ui/src/features/tab-tiling/useActiveTabTiled.ts b/products/desktop/packages/ui/src/features/tab-tiling/useActiveTabTiled.tsnew file mode 100644index 000000000000..8a93772d0ffa--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/useActiveTabTiled.ts@@ -0,0 +1,9 @@+import { useActiveTabId } from "@posthog/ui/features/browser-tabs/useActiveTabId";+import { useTileLayoutStore } from "./tileLayoutStore";+import { groupForTab } from "./tileTree";++export function useActiveTabTiled(): boolean {+ const groups = useTileLayoutStore((s) => s.groups);+ const activeTabId = useActiveTabId();+ return activeTabId !== null && groupForTab(groups, activeTabId) !== null;+}diff --git a/products/desktop/packages/ui/src/features/tab-tiling/useFocusTab.ts b/products/desktop/packages/ui/src/features/tab-tiling/useFocusTab.tsnew file mode 100644index 000000000000..40223b910eb3--- /dev/null+++ b/products/desktop/packages/ui/src/features/tab-tiling/useFocusTab.ts@@ -0,0 +1,32 @@+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import type { TabRef } from "@posthog/ui/features/browser-tabs/useGoToTab";+import { useGoToTab } from "@posthog/ui/features/browser-tabs/useGoToTab";+import { track } from "@posthog/ui/shell/analytics";+import { useCallback, useRef } from "react";+import { useTileLayoutStore } from "./tileLayoutStore";+import { groupForTab, tabIdsIn } from "./tileTree";++export function useFocusTab(activeTabId: string | null): (tab: TabRef) => void {+ const goToTab = useGoToTab();+ const activeRef = useRef(activeTabId);+ activeRef.current = activeTabId;+ return useCallback(+ (tab: TabRef) => {+ const active = activeRef.current;+ const { groups, noteActive } = useTileLayoutStore.getState();+ const target = groupForTab(groups, tab.id);+ const shown = active ? groupForTab(groups, active) : null;+ if (target) noteActive(tab.id);+ if (target && target === shown) {+ if (tab.id !== active) {+ track(ANALYTICS_EVENTS.BROWSER_TAB_TILE_FOCUSED, {+ tile_count: tabIdsIn(target.root).length,+ });+ }+ return;+ }+ goToTab(tab);+ },+ [goToTab],+ );+}diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskDetail.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskDetail.tsxindex 32a91ad2e6a3..b01fe2170f0b 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskDetail.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskDetail.tsx@@ -23,6 +23,7 @@ import { useReviewInRightPanel } from "../../navigation/useReviewInRightPanel";import { PanelLayout } from "../../panels/components/PanelLayout";import { MIN_CHAT_WIDTH } from "../../sessions/constants";import { useCwd } from "../../sidebar/useCwd";+import { useInUnfocusedTile } from "../../tab-tiling/tileContext";import { useRenameTask } from "../../tasks/useTaskMutations";import { useWorkspace } from "../../workspace/useWorkspace";import { useWorkspaceEvents } from "../../workspace/useWorkspaceEvents";@@ -60,6 +61,8 @@ export function TaskDetail({const openFilePicker = useFileSearchStore((state) => state.openPicker);+ const inBackgroundTile = useInUnfocusedTile();+const { enableScope, disableScope } = useHotkeysContext();const { requestArchive, dialog: archiveDialog } = useTaskArchive(task, {navigateUnscoped: !channelId,@@ -73,6 +76,7 @@ export function TaskDetail({},{scopes: ["taskDetail"],+ enabled: !inBackgroundTile,enableOnContentEditable: true,enableOnFormTags: true,},@@ -80,11 +84,12 @@ export function TaskDetail({);useEffect(() => {+ if (inBackgroundTile) return;enableScope("taskDetail");return () => {disableScope("taskDetail");};- }, [enableScope, disableScope]);+ }, [enableScope, disableScope, inBackgroundTile]);// Mounting TaskDetail means the task was actually rendered in front of the// user — that, not any API fetch of the task, is what clears the unread@@ -100,6 +105,7 @@ export function TaskDetail({}, [markTasksRead, taskId]);useHotkeys("mod+p", () => openFilePicker(), {+ enabled: !inBackgroundTile,enableOnContentEditable: true,enableOnFormTags: true,preventDefault: true,diff --git a/products/desktop/packages/ui/src/hooks/useSetHeaderContent.test.tsx b/products/desktop/packages/ui/src/hooks/useSetHeaderContent.test.tsxnew file mode 100644index 000000000000..1a93505e0140--- /dev/null+++ b/products/desktop/packages/ui/src/hooks/useSetHeaderContent.test.tsx@@ -0,0 +1,35 @@+import { TileProvider } from "@posthog/ui/features/tab-tiling/tileContext";+import { useHeaderStore } from "@posthog/ui/shell/headerStore";+import { renderHook } from "@testing-library/react";+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it } from "vitest";+import { useSetHeaderContent } from "./useSetHeaderContent";++describe("useSetHeaderContent", () => {+ beforeEach(() => {+ useHeaderStore.setState({ content: null });+ });++ it("publishes the content and clears it on unmount", () => {+ const { unmount } = renderHook(() => useSetHeaderContent("Active page"));+ expect(useHeaderStore.getState().content).toBe("Active page");++ unmount();+ expect(useHeaderStore.getState().content).toBeNull();+ });++ it("leaves the active page's header alone from inside a background tile", () => {+ useHeaderStore.setState({ content: "Active page" });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <TileProvider value={{ focused: false }}>{children}</TileProvider>+ );+ const { unmount } = renderHook(+ () => useSetHeaderContent("Background page"),+ { wrapper },+ );+ expect(useHeaderStore.getState().content).toBe("Active page");++ unmount();+ expect(useHeaderStore.getState().content).toBe("Active page");+ });+});diff --git a/products/desktop/packages/ui/src/hooks/useSetHeaderContent.ts b/products/desktop/packages/ui/src/hooks/useSetHeaderContent.tsindex d5e500006629..2de9ecc31218 100644--- a/products/desktop/packages/ui/src/hooks/useSetHeaderContent.ts+++ b/products/desktop/packages/ui/src/hooks/useSetHeaderContent.ts@@ -1,3 +1,4 @@+import { useInTile } from "@posthog/ui/features/tab-tiling/tileContext";import { useHeaderStore } from "@posthog/ui/shell/headerStore";import { type ReactNode, useLayoutEffect } from "react";@@ -8,13 +9,14 @@ import { type ReactNode, useLayoutEffect } from "react";*/export function useSetHeaderContent(content: ReactNode, enabled = true) {const setContent = useHeaderStore((state) => state.setContent);+ const inBackgroundTile = useInTile();useLayoutEffect(() => {- if (!enabled) return;+ if (!enabled || inBackgroundTile) return;setContent(content);return () => {setContent(null);};- }, [content, enabled, setContent]);+ }, [content, enabled, inBackgroundTile, setContent]);}diff --git a/products/desktop/packages/ui/src/router/routes/__root.tsx b/products/desktop/packages/ui/src/router/routes/__root.tsxindex df4457e05deb..7ca4fb2f6aeb 100644--- a/products/desktop/packages/ui/src/router/routes/__root.tsx+++ b/products/desktop/packages/ui/src/router/routes/__root.tsx@@ -61,6 +61,8 @@ import {import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";import { useSidebarData } from "@posthog/ui/features/sidebar/useSidebarData";import { useVisualTaskOrder } from "@posthog/ui/features/sidebar/useVisualTaskOrder";+import { TileLayout } from "@posthog/ui/features/tab-tiling/TileLayout";+import { useInTile } from "@posthog/ui/features/tab-tiling/tileContext";import { ExistingWorktreeDialog } from "@posthog/ui/features/task-detail/components/ExistingWorktreeDialog";import { RemoteBranchCheckoutDialog } from "@posthog/ui/features/task-detail/components/RemoteBranchCheckoutDialog";import { useTasks } from "@posthog/ui/features/tasks/useTasks";@@ -108,9 +110,13 @@ const log = logger.scope("root-route");const WINDOWS_TITLEBAR_INSET = 140;export const Route = createRootRoute({- component: RootLayout,+ component: RootRoute,});+function RootRoute() {+ return useInTile() ? <Outlet /> : <RootLayout />;+}+function RootLayout() {const view = useAppView();const router = useRouter();@@ -466,7 +472,9 @@ function RootLayout() {and, on a task, its action row. */}{!shellOwnsHeader && <ContentHeader />}<Box flexGrow="1" overflow="hidden">- <Outlet />+ <TileLayout>+ <Outlet />+ </TileLayout></Box></Flex></Box>diff --git a/products/desktop/packages/ui/src/shell/ContentHeader.tsx b/products/desktop/packages/ui/src/shell/ContentHeader.tsxindex 424a4a2df32c..d19dcc51bc1e 100644--- a/products/desktop/packages/ui/src/shell/ContentHeader.tsx+++ b/products/desktop/packages/ui/src/shell/ContentHeader.tsx@@ -1,3 +1,4 @@+import { useActiveTabTiled } from "@posthog/ui/features/tab-tiling/useActiveTabTiled";import { TaskHeaderActions } from "@posthog/ui/features/task-detail/components/TaskHeaderActions";import { useTasks } from "@posthog/ui/features/tasks/useTasks";import { ChromeBar } from "@posthog/ui/primitives/ChromeBar";@@ -25,6 +26,7 @@ const BREADCRUMB_VIEWS = new Set(["task-detail", "loops", "inbox", "report"]);export function ContentHeader() {const content = useHeaderStore((state) => state.content);const view = useAppView();+ const tiled = useActiveTabTiled();const activeTaskId = view.type === "task-detail" ? view.taskId : undefined;const { data: tasks } = useTasks();@@ -33,7 +35,7 @@ export function ContentHeader() {: undefined;const showTaskSection = view.type === "task-detail" && Boolean(activeTask);- if (!BREADCRUMB_VIEWS.has(view.type)) return null;+ if (tiled || !BREADCRUMB_VIEWS.has(view.type)) return null;if (!content && !showTaskSection) return null;