Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): make browser tabs independent and persistent (#87734)

Adam Leith5f074ad39302
diff --git a/products/desktop/apps/code/src/renderer/di/container.ts b/products/desktop/apps/code/src/renderer/di/container.ts
index 6e84c0fab662..844c593723e6 100644
--- a/products/desktop/apps/code/src/renderer/di/container.ts
+++ b/products/desktop/apps/code/src/renderer/di/container.ts
@@ -217,10 +217,12 @@ container.bind(CONNECTIVITY_CLIENT).toConstantValue(connectivityClient);
const browserTabsClient: BrowserTabsClient = {
getSnapshot: () => trpcClient.browserTabs.getSnapshot.query(),
getPrimaryWindowId: () => trpcClient.browserTabs.getPrimaryWindowId.query(),
- openOrFocus: (input) => trpcClient.browserTabs.openOrFocus.mutate(input),
- newBlankTab: (input) => trpcClient.browserTabs.newBlankTab.mutate(input),
+ reset: () => trpcClient.browserTabs.reset.mutate(),
+ openTab: (input) => trpcClient.browserTabs.openTab.mutate(input),
setTabTarget: (input) => trpcClient.browserTabs.setTabTarget.mutate(input),
close: (tabId) => trpcClient.browserTabs.close.mutate({ tabId }),
+ closeMany: (input) => trpcClient.browserTabs.closeMany.mutate(input),
+ setOrder: (input) => trpcClient.browserTabs.setOrder.mutate(input),
setActiveTab: (input) => trpcClient.browserTabs.setActiveTab.mutate(input),
onSnapshotChange: (sub) =>
trpcClient.browserTabs.onSnapshotChange.subscribe(undefined, sub),
diff --git a/products/desktop/apps/code/src/renderer/platform-adapters/auth-side-effects.ts b/products/desktop/apps/code/src/renderer/platform-adapters/auth-side-effects.ts
index f206c9372a24..968b567e30b7 100644
--- a/products/desktop/apps/code/src/renderer/platform-adapters/auth-side-effects.ts
+++ b/products/desktop/apps/code/src/renderer/platform-adapters/auth-side-effects.ts
@@ -6,16 +6,24 @@ import {
} from "@posthog/ui/features/auth/authQueries";
import { useAuthUiStateStore } from "@posthog/ui/features/auth/authUiStateStore";
import type { IAuthSideEffects } from "@posthog/ui/features/auth/identifiers";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "@posthog/ui/features/browser-tabs/browserTabsClient";
import { resetCurrentChannel } from "@posthog/ui/features/canvas/stores/currentChannelStore";
-import { resetRailHistory } from "@posthog/ui/features/canvas/stores/railHistoryStore";
import { useOnboardingStore } from "@posthog/ui/features/onboarding/onboardingStore";
import { resetSessionService } from "@posthog/ui/features/sessions/sessionServiceHost";
import { openTaskInput } from "@posthog/ui/router/useOpenTask";
import { track } from "@posthog/ui/shell/analytics";
-import { injectable } from "inversify";
+import { inject, injectable } from "inversify";
@injectable()
export class RendererAuthSideEffects implements IAuthSideEffects {
+ constructor(
+ @inject(BROWSER_TABS_CLIENT)
+ private readonly browserTabsClient: BrowserTabsClient,
+ ) {}
+
onAuthSuccess(region: CloudRegion, projectId: number | null): void {
void refreshAuthStateQuery();
useAuthUiStateStore.getState().clearStaleRegion();
@@ -29,17 +37,19 @@ export class RendererAuthSideEffects implements IAuthSideEffects {
resetSessionService();
}
- onProjectSelected(): void {
+ async onProjectSelected(): Promise<void> {
clearAuthScopedQueries();
- void refreshAuthStateQuery();
// Before openTaskInput, which files a new task into the scoped channel —
// a channel id from the project we just left.
resetCurrentChannel();
- resetRailHistory();
+ await Promise.all([
+ refreshAuthStateQuery(),
+ this.browserTabsClient.reset(),
+ ]);
openTaskInput();
}
- onLogout(previousRegion: CloudRegion | null): void {
+ async onLogout(previousRegion: CloudRegion | null): Promise<void> {
track(ANALYTICS_EVENTS.USER_LOGGED_OUT);
resetSessionService();
clearAuthScopedQueries();
@@ -47,7 +57,7 @@ export class RendererAuthSideEffects implements IAuthSideEffects {
useAuthUiStateStore.getState().setStaleRegion(previousRegion);
}
resetCurrentChannel();
- resetRailHistory();
+ await this.browserTabsClient.reset();
openTaskInput();
useOnboardingStore.getState().resetSelections();
}
diff --git a/products/desktop/apps/web/src/web-auth-side-effects.ts b/products/desktop/apps/web/src/web-auth-side-effects.ts
index 908a3419eaf6..0e082c2a97ed 100644
--- a/products/desktop/apps/web/src/web-auth-side-effects.ts
+++ b/products/desktop/apps/web/src/web-auth-side-effects.ts
@@ -5,17 +5,25 @@ import {
} from "@posthog/ui/features/auth/authQueries";
import { useAuthUiStateStore } from "@posthog/ui/features/auth/authUiStateStore";
import type { IAuthSideEffects } from "@posthog/ui/features/auth/identifiers";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "@posthog/ui/features/browser-tabs/browserTabsClient";
import { resetCurrentChannel } from "@posthog/ui/features/canvas/stores/currentChannelStore";
-import { resetRailHistory } from "@posthog/ui/features/canvas/stores/railHistoryStore";
import { useOnboardingStore } from "@posthog/ui/features/onboarding/onboardingStore";
import { openTaskInput } from "@posthog/ui/router/useOpenTask";
-import { injectable } from "inversify";
+import { inject, injectable } from "inversify";
// Web counterpart of the desktop RendererAuthSideEffects. Identical store/query
// coordination, minus the desktop SessionService reset — web cloud sessions are
// owned by the core SessionService, not a renderer singleton.
@injectable()
export class WebAuthSideEffects implements IAuthSideEffects {
+ constructor(
+ @inject(BROWSER_TABS_CLIENT)
+ private readonly browserTabsClient: BrowserTabsClient,
+ ) {}
+
onAuthSuccess(_region: CloudRegion, _projectId: number | null): void {
void refreshAuthStateQuery();
useAuthUiStateStore.getState().clearStaleRegion();
@@ -23,23 +31,25 @@ export class WebAuthSideEffects implements IAuthSideEffects {
beforeProjectSwitch(): void {}
- onProjectSelected(): void {
+ async onProjectSelected(): Promise<void> {
clearAuthScopedQueries();
- void refreshAuthStateQuery();
// Before openTaskInput, which files a new task into the scoped channel —
// a channel id from the project we just left.
resetCurrentChannel();
- resetRailHistory();
+ await Promise.all([
+ refreshAuthStateQuery(),
+ this.browserTabsClient.reset(),
+ ]);
openTaskInput();
}
- onLogout(previousRegion: CloudRegion | null): void {
+ async onLogout(previousRegion: CloudRegion | null): Promise<void> {
clearAuthScopedQueries();
if (previousRegion) {
useAuthUiStateStore.getState().setStaleRegion(previousRegion);
}
resetCurrentChannel();
- resetRailHistory();
+ await this.browserTabsClient.reset();
openTaskInput();
useOnboardingStore.getState().resetSelections();
}
diff --git a/products/desktop/apps/web/src/web-browser-tabs-store.ts b/products/desktop/apps/web/src/web-browser-tabs-store.ts
index 44286a9e2f11..05bc67881ce6 100644
--- a/products/desktop/apps/web/src/web-browser-tabs-store.ts
+++ b/products/desktop/apps/web/src/web-browser-tabs-store.ts
@@ -2,11 +2,12 @@ import {
type BrowserWindow,
closeTab,
closeTabs,
- newBlankTab,
- openOrFocusTab,
+ openTab,
+ resetTabs,
setTabOrder,
setTabTarget,
setWindowActiveTab,
+ type TabLocation,
type TabsSnapshot,
type TabTarget,
TypedEventEmitter,
@@ -72,34 +73,30 @@ class WebBrowserTabsStore extends TypedEventEmitter<SnapshotChangeEvents> {
return primary.id;
}
- openOrFocus(
- input: TabTarget & {
- windowId: string;
- channelId: string | null;
- channelSection?: string | null;
- appView?: string | null;
- tabId?: string;
- },
- ): TabsSnapshot {
- // Honor a renderer-minted id so the caller's optimistic apply and this
- // persisted state agree on the id.
- const providedId = input.tabId;
- const { snapshot } = openOrFocusTab(this.snapshot, {
- ...input,
- makeId: providedId ? () => providedId : makeId,
- now,
- });
- return this.commit(snapshot);
+ reset(): TabsSnapshot {
+ return this.commit(
+ resetTabs(this.snapshot, { href: "/spaces", makeId, now }),
+ );
}
- newBlankTab(input: { windowId: string; tabId?: string }): TabsSnapshot {
+ openTab(
+ input: TabTarget &
+ TabLocation & {
+ windowId: string;
+ channelId: string | null;
+ channelSection?: string | null;
+ appView?: string | null;
+ tabId?: string;
+ },
+ ): TabsSnapshot {
const providedId = input.tabId;
- // Idempotent on the renderer-minted id: a replay must not append a second tab.
+ // Idempotent on the renderer-minted id. There is no dedup to absorb a
+ // replayed open, so this is what keeps it from appending a second copy.
if (providedId && this.snapshot.tabs.some((t) => t.id === providedId)) {
return this.snapshot;
}
- const { snapshot } = newBlankTab(this.snapshot, {
- windowId: input.windowId,
+ const { snapshot } = openTab(this.snapshot, {
+ ...input,
makeId: providedId ? () => providedId : makeId,
now,
});
@@ -107,12 +104,13 @@ class WebBrowserTabsStore extends TypedEventEmitter<SnapshotChangeEvents> {
}
setTabTarget(
- input: TabTarget & {
- tabId: string;
- channelId: string | null;
- channelSection?: string | null;
- appView?: string | null;
- },
+ input: TabTarget &
+ TabLocation & {
+ tabId: string;
+ channelId: string | null;
+ channelSection?: string | null;
+ appView?: string | null;
+ },
): TabsSnapshot {
return this.commit(setTabTarget(this.snapshot, { ...input, now }));
}
diff --git a/products/desktop/apps/web/src/web-container.ts b/products/desktop/apps/web/src/web-container.ts
index a9668e6c2cfd..03ecd3983ac5 100644
--- a/products/desktop/apps/web/src/web-container.ts
+++ b/products/desktop/apps/web/src/web-container.ts
@@ -633,13 +633,16 @@ const webBrowserTabsClient: BrowserTabsClient = {
getSnapshot: () => Promise.resolve(webBrowserTabsStore.getSnapshot()),
getPrimaryWindowId: () =>
Promise.resolve(webBrowserTabsStore.getPrimaryWindowId()),
- openOrFocus: (input) =>
- Promise.resolve(webBrowserTabsStore.openOrFocus(input)),
- newBlankTab: (input) =>
- Promise.resolve(webBrowserTabsStore.newBlankTab(input)),
+ reset: () => Promise.resolve(webBrowserTabsStore.reset()),
+ openTab: (input) => Promise.resolve(webBrowserTabsStore.openTab(input)),
setTabTarget: (input) =>
Promise.resolve(webBrowserTabsStore.setTabTarget(input)),
close: (tabId) => Promise.resolve(webBrowserTabsStore.close(tabId)),
+ closeMany: (input) =>
+ Promise.resolve(
+ webBrowserTabsStore.closeMany(input.tabIds, input.focusTabId),
+ ),
+ setOrder: (input) => Promise.resolve(webBrowserTabsStore.setOrder(input)),
setActiveTab: (input) =>
Promise.resolve(webBrowserTabsStore.setActiveTab(input)),
onSnapshotChange: (sub) => {
diff --git a/products/desktop/apps/web/src/web-host-router.ts b/products/desktop/apps/web/src/web-host-router.ts
index 8c4702c29bd9..c5e986548e9c 100644
--- a/products/desktop/apps/web/src/web-host-router.ts
+++ b/products/desktop/apps/web/src/web-host-router.ts
@@ -17,6 +17,7 @@ import {
type CloudRegion,
getCloudUrlFromRegion,
tabsSnapshotSchema,
+ tabViewStateSchema,
} from "@posthog/shared";
import { getAuthenticatedClient } from "@posthog/ui/features/auth/authClientImperative";
import { z } from "zod";
@@ -423,7 +424,10 @@ const logsStubRouter = router({
// a REAL implementation, not a stub — the "+" (new tab), close, reorder, and
// in-tab navigation all persist and fan out to the renderer mirror via
// onSnapshotChange, exactly as on desktop (with a single window).
-const tabTargetFields = {
+/** Where a tab is, plus the route-derived label/icon cache. */
+const tabLocationFields = {
+ href: z.string().nullable().default(null),
+ viewState: tabViewStateSchema.nullable().default(null),
dashboardId: z.string().nullable().default(null),
taskId: z.string().nullable().default(null),
channelId: z.string().nullable().default(null),
@@ -437,22 +441,27 @@ const browserTabsRouter = router({
getPrimaryWindowId: publicProcedure
.output(z.string())
.query(() => webBrowserTabsStore.getPrimaryWindowId()),
- openOrFocus: publicProcedure
+ reset: publicProcedure
+ .output(tabsSnapshotSchema)
+ .mutation(() => webBrowserTabsStore.reset()),
+ openTab: publicProcedure
.input(
z.object({
windowId: z.string(),
- ...tabTargetFields,
+ ...tabLocationFields,
tabId: z.string().optional(),
}),
)
.output(tabsSnapshotSchema)
- .mutation(({ input }) => webBrowserTabsStore.openOrFocus(input)),
- newBlankTab: publicProcedure
- .input(z.object({ windowId: z.string(), tabId: z.string().optional() }))
- .output(tabsSnapshotSchema)
- .mutation(({ input }) => webBrowserTabsStore.newBlankTab(input)),
+ .mutation(({ input }) => webBrowserTabsStore.openTab(input)),
setTabTarget: publicProcedure
- .input(z.object({ tabId: z.string(), ...tabTargetFields }))
+ .input(
+ z.object({
+ tabId: z.string(),
+ ...tabLocationFields,
+ activate: z.boolean().optional(),
+ }),
+ )
.output(tabsSnapshotSchema)
.mutation(({ input }) => webBrowserTabsStore.setTabTarget(input)),
close: publicProcedure
diff --git a/products/desktop/docs/plans/browser-tabs.md b/products/desktop/docs/plans/browser-tabs.md
index 80fd2d998fab..a5c7f1917637 100644
--- a/products/desktop/docs/plans/browser-tabs.md
+++ b/products/desktop/docs/plans/browser-tabs.md
@@ -1,6 +1,9 @@
# PRD: Browser Tabs for the Channels Canvas Surface
-Status: ready-for-agent
+Status: shipped. The decisions below record the strip as it was built into the pre-rail layout.
+Superseded in part by [tabs-in-spaces.md](./tabs-in-spaces.md), which brings the strip into the
+spaces layout, removes content deduplication, and changes the tab record, launch authority, and
+per-tab state.
Surface: Channels space (`/spaces/*`) — the canvas surface with the `< >` nav and "Go back to Code" / "Leave feedback" chrome.
## Problem Statement
diff --git a/products/desktop/docs/plans/tabs-in-spaces.md b/products/desktop/docs/plans/tabs-in-spaces.md
new file mode 100644
index 000000000000..061994993bb4
--- /dev/null
+++ b/products/desktop/docs/plans/tabs-in-spaces.md
@@ -0,0 +1,211 @@
+# PRD: Browser tabs in the spaces layout
+
+Status: mostly shipped. Settings-in-content and the broader tier-2 store migration remain deferred.
+Surface: the whole app under `channelsLayout` (spaces / project-bluebird), not just `/spaces/*`
+Supersedes the decisions in [browser-tabs.md](./browser-tabs.md), which describes the strip as it shipped
+into the pre-rail layout. That document stays as the record of what was built; this one records what changes.
+
+## Problem Statement
+
+The tab strip is switched off in the spaces layout. `__root.tsx` renders it only when `channelsLayout`
+is false; with the layout on, its slot in the title bar holds the command search bar instead. So the
+surface that grew a nav rail, a space sidebar and a flattened route tree is also the surface with no
+way to keep more than one thing open.
+
+Meanwhile the spaces layout grew its own answer to "put me back where I was": `railHistoryStore`
+records the last href per rail destination, and a rail pick restores it. That is a second
+remember-where-you-were system sitting beside the tabs snapshot, scoped per window rather than per
+tab. The two cannot both be right once tabs are on.
+
+## Solution
+
+Tabs come back, in both layouts, and become the app's only unit of "a place you are". A tab owns a
+route and the nav state that route cannot express. Everything that used to remember a location per
+window now remembers it per tab.
+
+The governing rule:
+
+> **Navigation never changes which tab you're in. Back/forward may.**
+
+A tab is a full router experience. Change the URL and the active tab changes with it. Nothing focuses
+another tab behind your back.
+
+## Implementation Decisions
+
+### Tab scope
+Tabs are window-global. A tab may hold any route: a space, a canvas, a task, `/inbox`, `/loops`,
+`/settings/$category`. The rail stays a global column; the sidebar beside it is a function of the
+active tab, because the sidebar is derived from the route (`railPaneForMatches` → `railPaneHasSidebar`)
+and the route is now per tab.
+
+### The tab record is href-primary
+`browser_tabs` stores an `href`, not a reference set. The existing identity columns
+(`dashboardId` / `taskId` / `channelId` / `channelSection` / `appView`) demote to a label and icon cache.
+
+References cannot express a location. They drop search params, and they have no representation at all
+for most of the flattened route tree (`/`, `/activity`, `/loops`, `/loops/$loopId`, `/new`,
+`/archived`, `/feeds/$feedId`, `/folders/$folderId`, `/tasks/pending/$key`, `/settings/$category`,
+`/spaces`, and the space children `canvases`, `loops`, `new`, `context`). That is not only data loss:
+`useAppView` collapses anything it does not recognise into `task-input`, and the strip then reconciles
+the location against the wrong tab and navigates back off the page, which is what the warning at the
+top of `BrowserTabStrip` is about. `/activity` and `/loops` are rail destinations, so this fires on
+day one.
+
+`rewriteSavedLocation` gains a second call site over persisted tab hrefs. The `/website/*` → `/spaces/*`
+flatten already landed, so a snapshot written before it restores onto dead routes.
+
+### No dedup, no teleporting
+The identity dedup branch in `decideTabNavigation` is deleted. Navigating to something another tab
+already shows replaces the active tab's target; it does not focus the other tab. Two tabs may hold the
+same page, as in any browser.
+
+That branch was load-bearing for one recovery case: a rapid tab switch whose history stamp was lost
+still re-identified the intended tab from the route. Removing it means the stamp has to be reliable
+rather than recoverable, so the `tabId` stamp is minted synchronously at the call site of every switch
+(`applyLocalTransform` already runs in the same tick) and `serverActiveTabId` becomes persistence-only.
+There is no route-based recovery fallback because a route cannot identify which of several
+same-location tabs the user selected.
+
+### Back / forward
+Unchanged: one shared, tab-tagged timeline per window. Switching tabs pushes an entry, back at a tab
+boundary returns to the previous tab. This is the one place the app is deliberately not browser-like,
+and it is the only remaining path that moves you between tabs.
+
+### Per-tab nav state
+Most of "each tab has its own nav" is free, because the route is per tab. What is not in the URL:
+
+- `channelPaneStore.pane` (`list` vs `channel`)
+- `currentChannelStore.currentChannelId`, for routes with no `$channelId`
+- the `keepListForChannelId` latch
+- rail memory (below)
+
+These live in **router history state** (primary, via module augmentation, the way `tabId` already does)
+and are **written through to the tab row** for relaunch. History-primary because the state is per entry,
+not per tab: open the list, enter a space, open the list again, press back, and a single per-tab value
+lies. It also keeps the fast path fast, since history flips on navigate while the server snapshot
+round-trips.
+
+Toggling the list without navigating is a pure store write today. It gains a `router.replace` to stamp
+the current entry.
+
+### Rail memory, per tab
+The global `railHistoryStore` dies and its behavior narrows. Each tab remembers where each rail destination was
+*within that tab*, so clicking Inbox navigates the active tab to that tab's last inbox href rather than
+to `/inbox`. No cross-tab movement, no dedup, no teleport. `RailVisit` becomes part of the per-tab
+`viewState` record, so `lastByPane` moves into it unchanged.
+A window-global memory would let tab 1's rail click restore an href tab 2 established, which is
+cross-tab state bleed in another costume.
+
+### Search moves to the rail
+`CommandSearchBar` gives the title bar's middle back to the strip and becomes an icon at the top of
+`NavRail`. The label and the `⌘K` hint move into the rail's existing `NavIcon` tooltip.
+
+This is a shrink in affordance, and that file's own comment argues against it ("a target you aim at,
+not an icon you hunt for"). It wins anyway because the bar is not an omnibox: it renders no URL,
+accepts no typing, and its only job is to open the command menu. Browser-address-bar reasoning, and
+the permanent second row it would justify, does not apply. The rail also survives `⌘B`, which the
+sidebar does not.
+
+### `+` opens `/spaces`
+Blank tabs stop existing. A tab with no href cannot be a router location, and the blank state props up
+four special cases: `activeTabIsBlank`, `primaryWindowHasNoTabs`, the `showBlankTab` override of the
+`<Outlet>`, and the `activeIsBlank` guard inside `decideTabNavigation`. It is also the sole reason
+`/spaces` must never redirect.
+
+`+` navigates to `/spaces`, whose index renders the space grid. That page is currently unreachable:
+`showSpaces()` navigates to the scoped channel whenever one exists, and `ChannelRouteSync` auto-scopes
+to `#me` on cold start, so `navigateToSpaces()` is effectively dead code. The new-tab page becomes
+"pick a space", which is the right browser analogy.
+
+Cmd/Ctrl-clicking a rail destination is the other explicit new-tab action. It opens the destination's
+root in a fresh tab and never runs the active tab's normal rail-navigation or remembered-visit path.
+Settings is excluded because it still uses the full-window shell.
+
+`BlankTabView` is deleted.
+
+### Settings remains a full-window route
+The `isSettingsRoute` early return in `__root.tsx` renders no title bar, rail, sidebar, or tab strip.
+Opening that shell as a browser tab would hide the controls needed to leave or close the tab, so
+modifier-clicking Settings follows the normal in-window settings action. Moving settings into the
+content pane remains a separate layout and visual QA project.
+
+### Launch authority
+The tabs snapshot decides where the app opens. `startupLocation` demotes to the fallback for the cases
+with no snapshot: fresh install, flag off, and hosts with no tabs backend. It cannot be deleted, since
+it carries first-run provisioning (`#general`, `firstRun.generalChannelId`) and the legacy-key migration,
+none of which is about tabs.
+
+This costs an ordering change. `App.tsx` resolves `startupLocation` and calls `router.history.replace`
+**before the router mounts**, gating the loading screen on it, while the snapshot is seeded later by a
+boot contribution. The snapshot has to move into that boot gate. Optimistically painting the saved href
+and reconciling afterwards was considered and rejected: it flashes when the two disagree, and after a
+normal quit they never disagree, because both are written from the same navigations.
+
+`rememberStartupLocation`'s subscription on every history change should write only when the strip is
+off. Left on, it is a second, per-window record of where you were, which is the duplicate authority
+this work removes everywhere else.
+
+### View state tiers
+Every view store is assigned a tier. The rule: **if it describes the content a tab is showing, it is
+per tab; if it describes how the app is configured, it is global.**
+
+| Tier | Restores on | Lives in | Stores |
+| --- | --- | --- | --- |
+| 1, per history entry | back/forward and tab switch | history state, written through to the tab row | route href, `channelPaneStore.pane`, `currentChannelStore.currentChannelId`, rail memory |
+| 2, per tab | tab switch | tab row `viewState` | `threadPanelStore`, `canvasChatPanelStore`, `dashboardEditStore`, `taskFeedSelectionStore`, `rightPanelStore` open/which |
+| 3, global | never, it is not navigation | localStorage, as today | `channelsSidebarStore.width`, `rightPanelStore` width, `sidebarStore` nav order and overrides, `spaceTreeStore` expansion, `pinnedTabsStore`, `sidebarPeekStore` |
+
+`rightPanelStore` splits because which panel is open is content while its width is a preference, and a
+user who resizes it in one tab expects that width everywhere.
+
+The general tier-2 `createTabScopedStore` migration is deferred. The shipped implementation persists
+the tier-1 space, pane, and rail state in each tab's `viewState`; the stores listed in tier 2 still need
+an explicit migration before they can be treated as tab-scoped.
+
+Judgement calls worth revisiting once it is usable, all cheap to flip once the primitive exists:
+`dashboardEditStore` is per tab (two tabs both believing they are the editor of one canvas is a
+data-loss shape); `activityFilterStore` is global (a filter reads as a preference);
+`spaceTreeStore` expansion is global (tree expansion is muscle memory, not location).
+
+### Gating
+A new `SPACES_TABS` flag gates only whether the strip **renders** under `channelsLayout`. Everything
+above is unconditional.
+
+Flag-off is the degenerate case of the same implementation, not a second one: with a single tab, the
+tab is the window, so per-tab history, per-tab `viewState` and per-tab rail memory all behave exactly
+as the window-global versions do today. Gating the model instead would fork the subsystem being
+rewritten and double its test surface.
+
+## Shape
+
+1. **Model, nothing visible.** href-primary schema and migration, per-tab `viewState`, rail memory
+ moved onto the tab, dedup deleted, snapshot in the boot gate. One implicit tab throughout.
+2. **The UX, one PR.** Strip renders under `channelsLayout` behind `SPACES_TABS`, search moves to the
+ rail, and `+` goes to `/spaces`. Settings-in-content and the general tier-2 store migration are
+ deferred.
+
+## What This Deletes
+
+`railHistoryStore` as a global, `restoreVisit`, the identity dedup branch, `activeTabIsBlank`,
+`primaryWindowHasNoTabs`, `showBlankTab`, `BlankTabView`, the `activeIsBlank` guard, the
+"`/spaces` must not redirect" constraint.
+`decideTabNavigation` shrinks to roughly "stamp the entry, or activate on a history tag".
+
+## Open Questions
+
+- **`⌘W` on the last tab.** A browser closes the window; the primary window currently lands on the
+ channels landing instead.
+- **Strip overflow.** Already a rough edge (pinned pills are incompressible, the tablist only clips).
+ Rail destinations becoming tabs makes it likely on day one rather than eventually.
+- **Bluebird flag-off restore.** A flag-off user with several `/spaces/*` tabs is bounced once per
+ focus by the guard in `__root.tsx`, which only sees the active tab. Either filter bluebird-only hrefs
+ at restore, or skip the snapshot entirely while the flag is off.
+
+## Remaining
+
+`packages/ui/src/features/browser-tabs/AGENTS.md` documents the shipped core behavior and is the live
+reference. Two broader items remain intentionally deferred:
+
+- Settings still uses the full-window `isSettingsRoute` shell. Moving it into the content pane needs
+ separate layout work and visual QA.
+- The tier-2 view-state stores are not yet scoped through a `createTabScopedStore` primitive.
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
index 54bf99f880c3..fb8879e1ffa9 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
@@ -358,6 +358,28 @@ describe("TaskCreationSaga", () => {
);
});
+ it("does not roll back task creation when the ready callback throws", async () => {
+ const createdTask = createTask({ repository: undefined });
+ const onTaskReady = vi.fn(() => {
+ throw new Error("renderer unmounted");
+ });
+ const deleteTask = vi.fn();
+ const saga = makeSaga(
+ { createTask: vi.fn().mockResolvedValue(createdTask), deleteTask },
+ { onTaskReady },
+ );
+
+ const result = await saga.run({
+ content: "Draft a launch email",
+ workspaceMode: "local",
+ allowNoRepo: true,
+ });
+
+ expect(result.success).toBe(true);
+ expect(onTaskReady).toHaveBeenCalledOnce();
+ expect(deleteTask).not.toHaveBeenCalled();
+ });
+
it("starts a Pi session without creating an ACP session", async () => {
const createdTask = createTask({ repository: undefined });
const createTaskRequest = vi.fn().mockResolvedValue(createdTask);
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
index d97f43a21aac..d39a20373221 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
@@ -90,6 +90,17 @@ export class TaskCreationSaga extends Saga<
super(logger);
}
+ private notifyTaskReady(output: TaskCreationOutput): void {
+ try {
+ this.deps.onTaskReady?.(output);
+ } catch (error) {
+ this.log.error("Task-ready callback failed", {
+ taskId: output.task.id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
protected async execute(
input: TaskCreationInput,
): Promise<TaskCreationOutput> {
@@ -141,9 +152,7 @@ export class TaskCreationSaga extends Saga<
if (hasProvisioning) {
this.deps.host.setProvisioningActive(task.id);
- if (this.deps.onTaskReady) {
- this.deps.onTaskReady({ task, workspace });
- }
+ this.notifyTaskReady({ task, workspace });
}
if (repoPath) {
@@ -333,7 +342,7 @@ export class TaskCreationSaga extends Saga<
if (!taskId && workspaceMode === "cloud") {
await this.deps.sessionService.watchCreatedCloudTask(task);
}
- this.deps.onTaskReady?.({ task, workspace });
+ this.notifyTaskReady({ task, workspace });
}
if (hasProvisioning) {
@@ -487,7 +496,7 @@ export class TaskCreationSaga extends Saga<
if (!hasProvisioning) {
await this.deps.sessionService.watchCreatedCloudTask(task);
- this.deps.onTaskReady?.({ task, workspace });
+ this.notifyTaskReady({ task, workspace });
}
}
diff --git a/products/desktop/packages/host-router/src/routers/browser-tabs.router.ts b/products/desktop/packages/host-router/src/routers/browser-tabs.router.ts
index 8fc00b8f51ed..671438e47620 100644
--- a/products/desktop/packages/host-router/src/routers/browser-tabs.router.ts
+++ b/products/desktop/packages/host-router/src/routers/browser-tabs.router.ts
@@ -5,8 +5,7 @@ import {
browserTabsSnapshotOutput,
closeTabInput,
closeTabsInput,
- newBlankTabInput,
- openOrFocusTabInput,
+ openTabInput,
setActiveTabInput,
setTabOrderInput,
setTabTargetInput,
@@ -26,15 +25,14 @@ export const browserTabsRouter = router({
.output(z.string())
.query(({ ctx }) => svc(ctx.container).getPrimaryWindowId()),
- openOrFocus: publicProcedure
- .input(openOrFocusTabInput)
+ reset: publicProcedure
.output(browserTabsSnapshotOutput)
- .mutation(({ ctx, input }) => svc(ctx.container).openOrFocus(input)),
+ .mutation(({ ctx }) => svc(ctx.container).reset()),
- newBlankTab: publicProcedure
- .input(newBlankTabInput)
+ openTab: publicProcedure
+ .input(openTabInput)
.output(browserTabsSnapshotOutput)
- .mutation(({ ctx, input }) => svc(ctx.container).newBlankTab(input)),
+ .mutation(({ ctx, input }) => svc(ctx.container).openTab(input)),
setTabTarget: publicProcedure
.input(setTabTargetInput)
diff --git a/products/desktop/packages/shared/src/browser-tabs-schemas.ts b/products/desktop/packages/shared/src/browser-tabs-schemas.ts
index c7f36d332928..3109a37e2eec 100644
--- a/products/desktop/packages/shared/src/browser-tabs-schemas.ts
+++ b/products/desktop/packages/shared/src/browser-tabs-schemas.ts
@@ -3,17 +3,63 @@ import { z } from "zod";
/**
* Persisted browser-tab domain shapes for the Channels canvas surface.
*
- * A tab stores references only (which canvas, which channel, which window,
- * and where in the strip). Display — label, icon, channel-hover — is resolved
- * at render time from the dashboard/channel records, never denormalised here.
+ * A tab stores an `href` (the location it is on) plus the nav state that href
+ * cannot express (`viewState`). The reference fields below — dashboard, task,
+ * channel, section, appView — are a label/icon cache derived from the route,
+ * never the source of truth for where a tab is. The resolved display name is
+ * kept in viewState so a background tab can render immediately after restart,
+ * before its record query has loaded.
*
* `scrollState` is reserved for a later follow-up (scroll restoration needs a
* sandbox postMessage contract). It is persisted as opaque JSON so adding it
* needs no migration.
*/
+/**
+ * A rail destination as a tab last left it. `href` alone cannot bring a visit
+ * back: whether the space list was drawn over the space pane, and the space it
+ * was drawn over, are view state rather than route.
+ */
+export const railVisitSchema = z.object({
+ href: z.string(),
+ listOpen: z.boolean().optional(),
+ spaceId: z.string().nullable().optional(),
+});
+export type RailVisit = z.infer<typeof railVisitSchema>;
+
+/**
+ * The nav state a tab carries on top of its href: which sidebar pane is drawn,
+ * which space is scoped when the route names none, and where each rail
+ * destination was when this tab last left it.
+ *
+ * Scoped per tab because two tabs may sit on different spaces with different
+ * sidebars; a window-global copy would let one tab's rail click restore an href
+ * another tab established.
+ */
+export const tabViewStateSchema = z.object({
+ /**
+ * The last name this tab resolved for itself. A background tab's record is
+ * not fetched, and the live lists that name it may not have loaded yet, so
+ * without this a restored strip reads "Task" until they arrive. Written only
+ * when a name actually resolves, so a loading frame cannot blank it.
+ */
+ title: z.string().optional(),
+ listOpen: z.boolean().optional(),
+ spaceId: z.string().nullable().optional(),
+ /** Keyed by NavRailPane. Typed loosely here so shared stays route-agnostic. */
+ lastByPane: z.record(z.string(), railVisitSchema).optional(),
+});
+export type TabViewState = z.infer<typeof tabViewStateSchema>;
+
export const browserTabSchema = z.object({
id: z.string(),
windowId: z.string(),
+ /**
+ * Where this tab is. The source of truth for restoring it: search params and
+ * every route outside the reference vocabulary below survive only here.
+ */
+ href: z.string().nullable().default(null),
+ /** Nav state the href cannot express. See {@link tabViewStateSchema}. */
+ viewState: tabViewStateSchema.nullable().default(null),
/** Canvas this tab shows. Null for a task tab or a blank tab. */
dashboardId: z.string().nullable(),
/** Task this tab shows. Null for a canvas tab or a blank tab. */
@@ -26,10 +72,10 @@ export const browserTabSchema = z.object({
*/
channelSection: z.string().nullable().default(null),
/**
- * Top-level app page this tab shows (`inbox` / `agents` / `skills` /
- * `mcp-servers` / `command-center` / `home`). Null for a canvas / task /
- * channel / blank tab. These pages have no channel, task, or dashboard id, so
- * this is what lets them be a real tab target (label + restore-on-refocus).
+ * Top-level app page this tab shows (for example `inbox`, `activity`, `loops`,
+ * or `settings`). Null for a canvas / task / channel / blank tab. These pages
+ * have no channel, task, or dashboard id, so this keeps their label metadata
+ * alongside the canonical href.
*/
appView: z.string().nullable().default(null),
/** Gap-spaced ordering key within a window. Reindexed on collision. */
diff --git a/products/desktop/packages/shared/src/browser-tabs.test.ts b/products/desktop/packages/shared/src/browser-tabs.test.ts
index 955f63a8a77b..1a9af48bcbfe 100644
--- a/products/desktop/packages/shared/src/browser-tabs.test.ts
+++ b/products/desktop/packages/shared/src/browser-tabs.test.ts
@@ -1,17 +1,16 @@
import { describe, expect, it } from "vitest";
import {
- activeTabIsBlank,
closeTab,
closeTabs,
decideTabNavigation,
- newBlankTab,
- openOrFocusTab,
+ openTab,
POSITION_GAP,
primaryWindow,
- primaryWindowHasNoTabs,
+ resetTabs,
setTabOrder,
setTabTarget,
setWindowActiveTab,
+ type TabIdentity,
} from "./browser-tabs";
import type { TabsSnapshot } from "./browser-tabs-schemas";
@@ -20,6 +19,14 @@ const makeId = () => `tab-${++idCounter}`;
let clock = 0;
const now = () => ++clock;
+const NO_IDENTITY: TabIdentity = {
+ dashboardId: null,
+ taskId: null,
+ channelId: null,
+ channelSection: null,
+ appView: null,
+};
+
function snapshot(partial?: Partial<TabsSnapshot>): TabsSnapshot {
return {
windows: [{ id: "w1", isPrimary: true, bounds: null, activeTabId: null }],
@@ -28,14 +35,17 @@ function snapshot(partial?: Partial<TabsSnapshot>): TabsSnapshot {
};
}
+/** Open a canvas tab. The href is the truth; the identity fields are its label cache. */
function open(
s: TabsSnapshot,
windowId: string,
dashboardId: string,
channelId: string | null = "c1",
) {
- return openOrFocusTab(s, {
+ return openTab(s, {
windowId,
+ href: `/spaces/${channelId}/dashboards/${dashboardId}`,
+ viewState: null,
dashboardId,
taskId: null,
channelId,
@@ -44,68 +54,67 @@ function open(
});
}
-describe("openOrFocusTab", () => {
- it("opens a new tab and makes it active", () => {
- const r = open(snapshot(), "w1", "dash-a");
- expect(r.opened).toBe(true);
+/** Open a tab on a bare href, with no identity to cache. */
+function openAt(s: TabsSnapshot, windowId: string, href: string) {
+ return openTab(s, {
+ windowId,
+ href,
+ viewState: null,
+ ...NO_IDENTITY,
+ makeId,
+ now,
+ });
+}
+
+/** A navigation to `href` while `activeTab` is focused. */
+function navigate(input: {
+ href: string;
+ activeTab: {
+ id: string;
+ href: string | null;
+ identity?: TabIdentity;
+ } | null;
+ historyTabId?: string | null;
+ windowTabIds?: string[];
+ serverActiveTabId?: string | null;
+ identity?: TabIdentity;
+}) {
+ return decideTabNavigation({
+ historyTabId: input.historyTabId ?? null,
+ windowTabIds: input.windowTabIds,
+ serverActiveTabId:
+ input.serverActiveTabId !== undefined
+ ? input.serverActiveTabId
+ : (input.activeTab?.id ?? null),
+ activeTab: input.activeTab
+ ? {
+ ...input.activeTab,
+ viewState: null,
+ identity: input.activeTab.identity ?? NO_IDENTITY,
+ }
+ : null,
+ href: input.href,
+ viewState: null,
+ identity: input.identity ?? NO_IDENTITY,
+ });
+}
+
+describe("openTab", () => {
+ it("opens a tab on the given href and makes it active", () => {
+ const r = openAt(snapshot(), "w1", "/inbox/pulls/42");
expect(r.snapshot.tabs).toHaveLength(1);
+ expect(r.snapshot.tabs[0].href).toBe("/inbox/pulls/42");
expect(r.snapshot.windows[0].activeTabId).toBe(r.tabId);
expect(r.snapshot.tabs[0].position).toBe(POSITION_GAP);
});
- it("dedups within a window: focuses the existing tab instead of opening", () => {
+ // No dedup anywhere: navigation must never move you to another tab, and an
+ // explicit open makes the same promise.
+ it("opens a second tab on a page that is already open", () => {
const first = open(snapshot(), "w1", "dash-a");
const second = open(first.snapshot, "w1", "dash-a");
- expect(second.opened).toBe(false);
- expect(second.tabId).toBe(first.tabId);
- expect(second.snapshot.tabs).toHaveLength(1);
- });
-
- it("allows the same canvas in two different windows", () => {
- const twoWindows = snapshot({
- windows: [
- { id: "w1", isPrimary: true, bounds: null, activeTabId: null },
- { id: "w2", isPrimary: false, bounds: null, activeTabId: null },
- ],
- });
- const a = open(twoWindows, "w1", "dash-a");
- const b = open(a.snapshot, "w2", "dash-a");
- expect(b.opened).toBe(true);
- expect(b.snapshot.tabs).toHaveLength(2);
- });
-
- it("treats a channel's sections as distinct tabs but dedups the same one", () => {
- const history = openOrFocusTab(snapshot(), {
- windowId: "w1",
- dashboardId: null,
- taskId: null,
- channelId: "c1",
- channelSection: "history",
- makeId,
- now,
- });
- const artifacts = openOrFocusTab(history.snapshot, {
- windowId: "w1",
- dashboardId: null,
- taskId: null,
- channelId: "c1",
- channelSection: "artifacts",
- makeId,
- now,
- });
- expect(artifacts.opened).toBe(true);
- expect(artifacts.snapshot.tabs).toHaveLength(2);
- const historyAgain = openOrFocusTab(artifacts.snapshot, {
- windowId: "w1",
- dashboardId: null,
- taskId: null,
- channelId: "c1",
- channelSection: "history",
- makeId,
- now,
- });
- expect(historyAgain.opened).toBe(false);
- expect(historyAgain.tabId).toBe(history.tabId);
+ expect(second.tabId).not.toBe(first.tabId);
+ expect(second.snapshot.tabs).toHaveLength(2);
});
it("appends new tabs after existing ones", () => {
@@ -118,499 +127,275 @@ describe("openOrFocusTab", () => {
});
});
-describe("closeTab", () => {
- it("focuses the neighbouring tab when the active tab closes", () => {
- let s = snapshot();
- const a = open(s, "w1", "dash-a");
- const b = open(a.snapshot, "w1", "dash-b");
- s = b.snapshot; // active = b
- const r = closeTab(s, b.tabId);
- expect(r.snapshot.tabs).toHaveLength(1);
- expect(r.nextActiveTabId).toBe(a.tabId);
- expect(r.snapshot.windows[0].activeTabId).toBe(a.tabId);
- });
-
- it("closes a secondary window when its last tab closes", () => {
- const s = snapshot({
+describe("resetTabs", () => {
+ it("removes auth-scoped metadata from every window", () => {
+ const withWindows = snapshot({
windows: [
{ id: "w1", isPrimary: true, bounds: null, activeTabId: null },
{ id: "w2", isPrimary: false, bounds: null, activeTabId: null },
],
});
- const t = open(s, "w2", "dash-a");
- const r = closeTab(t.snapshot, t.tabId);
- expect(r.closedWindowId).toBe("w2");
- expect(r.snapshot.windows.map((w) => w.id)).toEqual(["w1"]);
- });
+ const first = openAt(withWindows, "w1", "/tasks/private-a");
+ const second = openAt(first.snapshot, "w2", "/inbox/private-b");
- it("shows the landing (null active) when the primary's last tab closes", () => {
- const t = open(snapshot(), "w1", "dash-a");
- const r = closeTab(t.snapshot, t.tabId);
- expect(r.closedWindowId).toBeNull();
- expect(r.snapshot.windows[0].activeTabId).toBeNull();
- expect(r.snapshot.tabs).toHaveLength(0);
- });
-});
+ const reset = resetTabs(second.snapshot, {
+ href: "/spaces",
+ makeId,
+ now,
+ });
-describe("newBlankTab", () => {
- it("appends a focused blank tab with no canvas", () => {
- const existing = open(snapshot(), "w1", "dash-a");
- const r = newBlankTab(existing.snapshot, { windowId: "w1", makeId, now });
- expect(r.snapshot.tabs).toHaveLength(2);
- const blank = r.snapshot.tabs.find((t) => t.id === r.tabId);
- expect(blank?.dashboardId).toBeNull();
- expect(r.snapshot.windows[0].activeTabId).toBe(r.tabId);
+ expect(reset.tabs).toHaveLength(2);
+ expect(reset.tabs).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ windowId: "w1", href: "/spaces" }),
+ expect.objectContaining({ windowId: "w2", href: "/spaces" }),
+ ]),
+ );
+ expect(reset.tabs.every((tab) => tab.viewState === null)).toBe(true);
+ expect(reset.windows.every((window) => window.activeTabId !== null)).toBe(
+ true,
+ );
});
});
describe("setTabTarget", () => {
- it("points an existing tab at a canvas and focuses it (in-tab nav)", () => {
- const blank = newBlankTab(snapshot(), { windowId: "w1", makeId, now });
- const next = setTabTarget(blank.snapshot, {
- tabId: blank.tabId,
- dashboardId: "dash-x",
- taskId: null,
- channelId: "c1",
- now,
- });
- const tab = next.tabs.find((t) => t.id === blank.tabId);
- expect(tab?.dashboardId).toBe("dash-x");
- expect(tab?.channelId).toBe("c1");
- expect(next.tabs).toHaveLength(1); // replaced contents, no new tab
- expect(next.windows[0].activeTabId).toBe(blank.tabId);
- });
-
- it("points an existing tab at a task (tasks are first-class targets)", () => {
- const blank = newBlankTab(snapshot(), { windowId: "w1", makeId, now });
- const next = setTabTarget(blank.snapshot, {
- tabId: blank.tabId,
- dashboardId: null,
- taskId: "task-9",
+ // The whole location moves together: href, the view state the href cannot
+ // express, and the label cache. A tab that keeps a stale field here restores
+ // onto the wrong page or renders the previous page's name.
+ it("writes the tab's whole location and focuses it", () => {
+ const a = open(snapshot(), "w1", "dash-a");
+ const b = open(a.snapshot, "w1", "dash-b");
+ const s = setTabTarget(b.snapshot, {
+ tabId: a.tabId,
+ href: "/spaces/c1/tasks/t9",
+ viewState: { listOpen: true, spaceId: "c1" },
+ ...NO_IDENTITY,
+ taskId: "t9",
channelId: "c1",
now,
});
- const tab = next.tabs.find((t) => t.id === blank.tabId);
- expect(tab?.taskId).toBe("task-9");
+ const tab = s.tabs.find((t) => t.id === a.tabId);
+ expect(tab?.href).toBe("/spaces/c1/tasks/t9");
+ expect(tab?.viewState).toEqual({ listOpen: true, spaceId: "c1" });
+ expect(tab?.taskId).toBe("t9");
expect(tab?.dashboardId).toBeNull();
+ expect(s.windows[0].activeTabId).toBe(a.tabId);
});
- it("is a no-op for an unknown tab id", () => {
- const s = snapshot();
- expect(
- setTabTarget(s, {
- tabId: "nope",
- dashboardId: "d",
- taskId: null,
- channelId: null,
- now,
- }),
- ).toBe(s);
- });
-});
-
-describe("decideTabNavigation", () => {
- const base = {
- historyTabId: null as string | null,
- serverActiveTabId: null as string | null,
- activeTab: null as {
- id: string;
- dashboardId: string | null;
- taskId: string | null;
- } | null,
- routeDashboardId: null as string | null,
- routeTaskId: null as string | null,
- routeChannelId: null as string | null,
- };
-
- it("activates the tagged tab on a switch / back-forward replay", () => {
- expect(
- decideTabNavigation({
- ...base,
- historyTabId: "tab-b",
- serverActiveTabId: "tab-a",
- }),
- ).toEqual({ type: "activate", tabId: "tab-b" });
- });
-
- it("back to the previous tab activates it (history entry tagged with that tab)", () => {
- // After switching A→B, pressing back lands on A's entry: historyTabId=A
- // while the server still thinks B is active → activate A.
- expect(
- decideTabNavigation({
- ...base,
- historyTabId: "tab-a",
- serverActiveTabId: "tab-b",
- }),
- ).toEqual({ type: "activate", tabId: "tab-a" });
- });
-
- it("is a noop when the tagged tab is already active", () => {
- expect(
- decideTabNavigation({
- ...base,
- historyTabId: "tab-a",
- serverActiveTabId: "tab-a",
- }),
- ).toEqual({ type: "noop" });
- });
-
- it("replaces the active tab's canvas on an untagged in-tab nav", () => {
- expect(
- decideTabNavigation({
- ...base,
- serverActiveTabId: "tab-a",
- activeTab: { id: "tab-a", dashboardId: "old", taskId: null },
- routeDashboardId: "new",
- routeChannelId: "c1",
- }),
- ).toEqual({
- type: "replace",
- tabId: "tab-a",
- dashboardId: "new",
- taskId: null,
- channelId: "c1",
- channelSection: null,
- appView: null,
- stampTabId: "tab-a",
- });
- });
-
- it("replaces even when the entry is tagged with the active tab (inherited tag)", () => {
- // A plain navigate (sidebar) inherits the active tab's tag, so an in-tab nav
- // arrives tagged with the active tab. It must still replace, not noop.
- expect(
- decideTabNavigation({
- ...base,
- historyTabId: "tab-a",
- serverActiveTabId: "tab-a",
- activeTab: { id: "tab-a", dashboardId: "old", taskId: null },
- routeDashboardId: "new",
- routeChannelId: "c1",
- }),
- ).toEqual({
- type: "replace",
- tabId: "tab-a",
- dashboardId: "new",
- taskId: null,
- channelId: "c1",
- channelSection: null,
- appView: null,
- stampTabId: "tab-a",
+ it("can retarget a background tab without focusing it", () => {
+ const a = open(snapshot(), "w1", "dash-a");
+ const b = open(a.snapshot, "w1", "dash-b");
+ const s = setTabTarget(b.snapshot, {
+ tabId: a.tabId,
+ href: "/tasks/t9",
+ viewState: { title: "Background task" },
+ ...NO_IDENTITY,
+ taskId: "t9",
+ activate: false,
+ now,
});
- });
- it("opens a tab when an untagged canvas nav has no active tab", () => {
- expect(
- decideTabNavigation({
- ...base,
- routeDashboardId: "d1",
- routeChannelId: "c1",
- }),
- ).toEqual({
- type: "open",
- dashboardId: "d1",
- taskId: null,
- channelId: "c1",
- channelSection: null,
- appView: null,
- stampTabId: null,
+ expect(s.tabs.find((t) => t.id === a.tabId)).toMatchObject({
+ href: "/tasks/t9",
+ taskId: "t9",
});
+ expect(s.windows[0].activeTabId).toBe(b.tabId);
});
- it("replaces the active tab when navigating between channel sections", () => {
- // In-tab nav from a channel's history to its artifacts: same tab, new section.
- expect(
- decideTabNavigation({
- ...base,
- serverActiveTabId: "tab-a",
- activeTab: {
- id: "tab-a",
- dashboardId: null,
- taskId: null,
- channelId: "c1",
- channelSection: "history",
- },
- routeChannelId: "c1",
- routeChannelSection: "artifacts",
- }),
- ).toEqual({
- type: "replace",
- tabId: "tab-a",
- dashboardId: null,
- taskId: null,
- channelId: "c1",
- channelSection: "artifacts",
- appView: null,
- stampTabId: "tab-a",
+ it("ignores an unknown tab", () => {
+ const a = open(snapshot(), "w1", "dash-a");
+ const s = setTabTarget(a.snapshot, {
+ tabId: "nope",
+ href: "/loops",
+ viewState: null,
+ ...NO_IDENTITY,
+ now,
});
+ expect(s).toBe(a.snapshot);
});
+});
- it("opens a channel-section tab when there is no active tab", () => {
- expect(
- decideTabNavigation({
- ...base,
- routeChannelId: "c1",
- routeChannelSection: "history",
- }),
- ).toEqual({
- type: "open",
- dashboardId: null,
- taskId: null,
- channelId: "c1",
- channelSection: "history",
- appView: null,
- stampTabId: null,
+describe("decideTabNavigation", () => {
+ // The governing rule: a plain navigation stays in the tab you are in.
+ //
+ // The last two cases are why the match is on href. Identity is all-null for
+ // `/loops` and `/archived` alike, and identical across a search-param change,
+ // so an identity-keyed comparison read both as "already there" and the strip
+ // never followed the navigation.
+ it.each([
+ ["a different page", "/spaces/c1", "/inbox"],
+ ["two routes outside the label vocabulary", "/loops", "/archived"],
+ [
+ "a search-param change",
+ "/spaces/c1/canvases",
+ "/spaces/c1/canvases?filter=mine",
+ ],
+ ])("replaces the active tab's location on %s", (_case, from, to) => {
+ const d = navigate({ href: to, activeTab: { id: "t1", href: from } });
+ expect(d).toMatchObject({ type: "replace", tabId: "t1", href: to });
+ });
+
+ it("never activates another tab that already holds the destination", () => {
+ const d = navigate({
+ href: "/inbox",
+ activeTab: { id: "t1", href: "/spaces/c1" },
+ windowTabIds: ["t1", "t2"],
+ });
+ expect(d.type).toBe("replace");
+ });
+
+ it("opens a tab when there is no active one", () => {
+ const d = navigate({ href: "/inbox", activeTab: null });
+ expect(d).toMatchObject({ type: "open", href: "/inbox" });
+ });
+
+ it("stamps the entry when the active tab already holds the location", () => {
+ const d = navigate({
+ href: "/inbox",
+ activeTab: { id: "t1", href: "/inbox" },
+ });
+ expect(d).toEqual({ type: "stamp", stampTabId: "t1" });
+ });
+
+ // The router updates location.href before the new route's params, so the
+ // first pass writes the new href with the old identity. Keyed on href alone,
+ // the corrected identity arriving a frame later compared equal and was
+ // dropped, leaving a task tab labelled as its space forever.
+ it("writes a label cache that resolves after the href did", () => {
+ const d = navigate({
+ href: "/spaces/c1/tasks/t9",
+ activeTab: {
+ id: "t1",
+ href: "/spaces/c1/tasks/t9",
+ identity: { ...NO_IDENTITY, channelId: "c1" },
+ },
+ identity: { ...NO_IDENTITY, channelId: "c1", taskId: "t9" },
});
+ expect(d).toMatchObject({ type: "replace", tabId: "t1", taskId: "t9" });
});
- it("only stamps when the active tab already shows the route channel section", () => {
- expect(
- decideTabNavigation({
- ...base,
- serverActiveTabId: "tab-a",
- activeTab: {
- id: "tab-a",
- dashboardId: null,
- taskId: null,
- channelId: "c1",
- channelSection: "history",
- },
- routeChannelId: "c1",
- routeChannelSection: "history",
- }),
- ).toEqual({ type: "stamp", stampTabId: "tab-a" });
- });
-
- it("only stamps when the active tab already shows the route canvas", () => {
- expect(
- decideTabNavigation({
- ...base,
- serverActiveTabId: "tab-a",
- activeTab: { id: "tab-a", dashboardId: "same", taskId: null },
- routeDashboardId: "same",
- }),
- ).toEqual({ type: "stamp", stampTabId: "tab-a" });
- });
-
- it("is a noop on a blank/landing route (no canvas)", () => {
- expect(
- decideTabNavigation({
- ...base,
- serverActiveTabId: "tab-a",
- activeTab: { id: "tab-a", dashboardId: null, taskId: null },
- routeDashboardId: null,
- }),
- ).toEqual({ type: "noop" });
- });
-});
-
-describe("decideTabNavigation: dedup against existing tabs (windowTabs)", () => {
- const identity = {
- dashboardId: null,
- taskId: null,
- channelId: null,
- channelSection: null,
- appView: null,
- };
-
- it("activates the existing tab instead of replacing the active tab's target (would-be duplicate)", () => {
- // A rapid switch whose history stamp was lost arrives looking like an in-tab
- // nav: active tab A, but the route identifies tab B (already open). Without
- // the dedup this replaces A's target → two tabs on c2/artifacts. With it, B
- // is focused.
- expect(
- decideTabNavigation({
- historyTabId: "tab-a",
- serverActiveTabId: "tab-a",
- windowTabs: [
- { id: "tab-a", ...identity, channelId: "c1" },
- {
- id: "tab-b",
- ...identity,
- channelId: "c2",
- channelSection: "artifacts",
- },
- ],
- activeTab: {
- id: "tab-a",
- dashboardId: null,
- taskId: null,
- channelId: "c1",
- },
- routeDashboardId: null,
- routeTaskId: null,
- routeChannelId: "c2",
- routeChannelSection: "artifacts",
+ it("persists a view-state change made without navigating", () => {
+ const d = decideTabNavigation({
+ historyTabId: null,
+ serverActiveTabId: "t1",
+ activeTab: {
+ id: "t1",
+ href: "/spaces/c1",
+ viewState: null,
+ identity: NO_IDENTITY,
+ },
+ href: "/spaces/c1",
+ viewState: { listOpen: true, spaceId: "c1" },
+ identity: NO_IDENTITY,
+ });
+ expect(d).toMatchObject({ type: "replace", tabId: "t1" });
+ });
+
+ // Back/forward is the only thing that may move you between tabs.
+ it("activates the tab a history entry is tagged with", () => {
+ const d = navigate({
+ href: "/spaces/c1",
+ activeTab: { id: "t1", href: "/spaces/c1" },
+ historyTabId: "t2",
+ windowTabIds: ["t1", "t2"],
+ serverActiveTabId: "t1",
+ });
+ expect(d).toEqual({ type: "activate", tabId: "t2" });
+ });
+
+ it("ignores a tag equal to the active tab and decides from the route", () => {
+ const d = navigate({
+ href: "/inbox",
+ activeTab: { id: "t1", href: "/spaces/c1" },
+ historyTabId: "t1",
+ windowTabIds: ["t1"],
+ serverActiveTabId: "t1",
+ });
+ expect(d).toMatchObject({ type: "replace", tabId: "t1" });
+ });
+
+ // Switching tabs must not write anything. Fed settled inputs, no frame of the
+ // switch is a `replace` — the corruption this guards is a frame that pairs the
+ // new tab's tag with the old tab's href, which reads as "tab B navigated to
+ // A's page" and copies A's URL onto B.
+ it("writes nothing across the frames of a tab switch", () => {
+ const tabA = { id: "a", href: "/spaces/a" };
+ const tabB = { id: "b", href: "/spaces/b" };
+ const frames = [
+ // Navigation pending: the settled entry is still A's, and so is its tag.
+ navigate({
+ href: tabA.href,
+ historyTabId: "a",
+ activeTab: tabA,
+ serverActiveTabId: "a",
+ windowTabIds: ["a", "b"],
}),
- ).toEqual({ type: "activate", tabId: "tab-b" });
- });
-
- it("activates an existing matching tab instead of opening a duplicate (no active tab)", () => {
- expect(
- decideTabNavigation({
- historyTabId: null,
- serverActiveTabId: null,
- windowTabs: [{ id: "tab-b", ...identity, channelId: "c2" }],
- activeTab: null,
- routeDashboardId: null,
- routeTaskId: null,
- routeChannelId: "c2",
+ // Landed: the settled tag is now B, which the mirror hasn't caught up to.
+ navigate({
+ href: tabB.href,
+ historyTabId: "b",
+ activeTab: tabA,
+ serverActiveTabId: "a",
+ windowTabIds: ["a", "b"],
}),
- ).toEqual({ type: "activate", tabId: "tab-b" });
- });
-
- it("does NOT jump when the active tab already shows the route, even if a duplicate exists", () => {
- // Two tabs share an identity (a pre-existing duplicate). The active one
- // already shows the route → stamp/noop. Jumping to the other duplicate
- // would ping-pong between them forever (Maximum update depth exceeded).
- expect(
- decideTabNavigation({
- historyTabId: "tab-x",
- serverActiveTabId: "tab-x",
- windowTabs: [
- {
- id: "tab-x",
- ...identity,
- channelId: "c1",
- channelSection: "artifacts",
- },
- {
- id: "tab-y",
- ...identity,
- channelId: "c1",
- channelSection: "artifacts",
- },
- ],
- activeTab: {
- id: "tab-x",
- dashboardId: null,
- taskId: null,
- channelId: "c1",
- channelSection: "artifacts",
- },
- routeDashboardId: null,
- routeTaskId: null,
- routeChannelId: "c1",
- routeChannelSection: "artifacts",
+ // Focus applied: everything agrees.
+ navigate({
+ href: tabB.href,
+ historyTabId: "b",
+ activeTab: tabB,
+ serverActiveTabId: "b",
+ windowTabIds: ["a", "b"],
}),
- ).toEqual({ type: "stamp", stampTabId: "tab-x" });
- });
+ ];
- it("fills a blank active tab (fresh + tab) even when the route is open elsewhere", () => {
- // Cmd+T lands the new blank tab on #me. If a #me tab is already open, the
- // dedup must NOT steal the navigation to it — that would strand the blank
- // tab forever. The blank active tab means "fill me".
- expect(
- decideTabNavigation({
- historyTabId: "tab-blank",
- serverActiveTabId: "tab-blank",
- windowTabs: [
- { id: "tab-blank", ...identity },
- { id: "tab-me", ...identity, channelId: "me-ch" },
- ],
- activeTab: { id: "tab-blank", dashboardId: null, taskId: null },
- routeDashboardId: null,
- routeTaskId: null,
- routeChannelId: "me-ch",
- }),
- ).toEqual({
- type: "replace",
- tabId: "tab-blank",
- dashboardId: null,
- taskId: null,
- channelId: "me-ch",
- channelSection: null,
- appView: null,
- stampTabId: "tab-blank",
- });
+ expect(frames.map((f) => f.type)).toEqual(["stamp", "activate", "stamp"]);
});
- it("still replaces for a genuine in-tab nav to a target no other tab holds", () => {
- expect(
- decideTabNavigation({
- historyTabId: "tab-a",
- serverActiveTabId: "tab-a",
- windowTabs: [{ id: "tab-a", ...identity, channelId: "c1" }],
- activeTab: {
- id: "tab-a",
- dashboardId: null,
- taskId: null,
- channelId: "c1",
- },
- routeDashboardId: null,
- routeTaskId: null,
- routeChannelId: "c1",
- routeChannelSection: "artifacts",
- }),
- ).toEqual({
- type: "replace",
- tabId: "tab-a",
- dashboardId: null,
- taskId: null,
- channelId: "c1",
- channelSection: "artifacts",
- appView: null,
- stampTabId: "tab-a",
+ it("skips a tag for a tab that has since been closed", () => {
+ const d = navigate({
+ href: "/inbox",
+ activeTab: { id: "t1", href: "/spaces/c1" },
+ historyTabId: "gone",
+ windowTabIds: ["t1"],
+ serverActiveTabId: "t1",
});
+ expect(d).toMatchObject({ type: "replace", tabId: "t1" });
});
});
-function openChannel(s: TabsSnapshot, windowId: string, channelId: string) {
- return openOrFocusTab(s, {
- windowId,
- dashboardId: null,
- taskId: null,
- channelId,
- makeId,
- now,
- });
-}
-
-describe("activeTabIsBlank", () => {
- it("is true when the active tab has no canvas, task, or channel", () => {
- const t = newBlankTab(snapshot(), { windowId: "w1", makeId, now });
- expect(activeTabIsBlank(t.snapshot)).toBe(true);
- });
-
- it("is false when the active tab points at a canvas", () => {
- const t = open(snapshot(), "w1", "dash-a");
- expect(activeTabIsBlank(t.snapshot)).toBe(false);
- });
-
- it("is false when the active tab is a channel tab (channel home)", () => {
- const t = openChannel(snapshot(), "w1", "c1");
- expect(activeTabIsBlank(t.snapshot)).toBe(false);
- });
-
- it("is false when there is no active tab", () => {
- expect(activeTabIsBlank(snapshot())).toBe(false);
- });
-});
-
-describe("primaryWindowHasNoTabs", () => {
- it("is true when the primary window's last tab was closed", () => {
- const opened = open(snapshot(), "w1", "dash-a");
- const closed = closeTab(opened.snapshot, opened.tabId);
- expect(primaryWindowHasNoTabs(closed.snapshot)).toBe(true);
- });
-
- it("is false while the primary window still has a tab", () => {
- const t = open(snapshot(), "w1", "dash-a");
- expect(primaryWindowHasNoTabs(t.snapshot)).toBe(false);
+describe("closeTab", () => {
+ it("focuses the neighbouring tab when the active tab closes", () => {
+ let s = snapshot();
+ const a = open(s, "w1", "dash-a");
+ const b = open(a.snapshot, "w1", "dash-b");
+ s = b.snapshot; // active = b
+ const r = closeTab(s, b.tabId);
+ expect(r.snapshot.tabs).toHaveLength(1);
+ expect(r.nextActiveTabId).toBe(a.tabId);
+ expect(r.snapshot.windows[0].activeTabId).toBe(a.tabId);
});
- it("ignores tabs that belong to other windows", () => {
+ it("closes a secondary window when its last tab closes", () => {
const s = snapshot({
windows: [
{ id: "w1", isPrimary: true, bounds: null, activeTabId: null },
{ id: "w2", isPrimary: false, bounds: null, activeTabId: null },
],
});
- const onlyInSecondary = open(s, "w2", "dash-a");
- expect(primaryWindowHasNoTabs(onlyInSecondary.snapshot)).toBe(true);
+ const t = open(s, "w2", "dash-a");
+ const r = closeTab(t.snapshot, t.tabId);
+ expect(r.closedWindowId).toBe("w2");
+ expect(r.snapshot.windows.map((w) => w.id)).toEqual(["w1"]);
});
-});
+ it("shows the landing (null active) when the primary's last tab closes", () => {
+ const t = open(snapshot(), "w1", "dash-a");
+ const r = closeTab(t.snapshot, t.tabId);
+ expect(r.closedWindowId).toBeNull();
+ expect(r.snapshot.windows[0].activeTabId).toBeNull();
+ expect(r.snapshot.tabs).toHaveLength(0);
+ });
+});
describe("closeTabs", () => {
/** Open n dashboards in w1, returning the snapshot and ordered tab ids. */
function openMany(n: number) {
@@ -694,7 +479,6 @@ describe("closeTabs", () => {
};
}
});
-
describe("setTabOrder", () => {
function openThree() {
let s = snapshot();
@@ -746,7 +530,6 @@ describe("setTabOrder", () => {
expect(w2tab?.position).toBe(POSITION_GAP);
});
});
-
describe("primaryWindow", () => {
it("prefers the primary window, falling back to the first", () => {
const s = snapshot({
@@ -759,18 +542,6 @@ describe("primaryWindow", () => {
});
});
-function openAppView(s: TabsSnapshot, windowId: string, appView: string) {
- return openOrFocusTab(s, {
- windowId,
- dashboardId: null,
- taskId: null,
- channelId: null,
- appView,
- makeId,
- now,
- });
-}
-
describe("setWindowActiveTab", () => {
it("focuses a tab that exists in the window", () => {
const a = open(snapshot(), "w1", "dash-a");
@@ -830,485 +601,3 @@ describe("setWindowActiveTab", () => {
);
});
});
-
-describe("decideTabNavigation: dead history tags (back/forward over closed tabs)", () => {
- const base = {
- historyTabId: null as string | null,
- serverActiveTabId: null as string | null,
- activeTab: null as {
- id: string;
- dashboardId: string | null;
- taskId: string | null;
- } | null,
- routeDashboardId: null as string | null,
- routeTaskId: null as string | null,
- routeChannelId: null as string | null,
- };
-
- it("does NOT activate a tagged tab that no longer exists — replays in the active tab", () => {
- // Back onto an entry whose tab was closed: fall through to the route and
- // replace the active tab, instead of persisting a dangling activeTabId.
- expect(
- decideTabNavigation({
- ...base,
- historyTabId: "tab-closed",
- windowTabIds: ["tab-a", "tab-b"],
- serverActiveTabId: "tab-a",
- activeTab: { id: "tab-a", dashboardId: "old", taskId: null },
- routeDashboardId: "from-history",
- routeChannelId: "c1",
- }),
- ).toEqual({
- type: "replace",
- tabId: "tab-a",
- dashboardId: "from-history",
- taskId: null,
- channelId: "c1",
- channelSection: null,
- appView: null,
- stampTabId: "tab-a",
- });
- });
-
- it("opens a tab for a dead tag when nothing is active", () => {
- expect(
- decideTabNavigation({
- ...base,
- historyTabId: "tab-closed",
- windowTabIds: [],
- serverActiveTabId: null,
- routeDashboardId: "d1",
- routeChannelId: "c1",
- }),
- ).toEqual({
- type: "open",
- dashboardId: "d1",
- taskId: null,
- channelId: "c1",
- channelSection: null,
- appView: null,
- stampTabId: null,
- });
- });
-
- it("re-stamps the entry with the live active tab when the route already matches", () => {
- expect(
- decideTabNavigation({
- ...base,
- historyTabId: "tab-closed",
- windowTabIds: ["tab-a"],
- serverActiveTabId: "tab-a",
- activeTab: { id: "tab-a", dashboardId: "same", taskId: null },
- routeDashboardId: "same",
- routeChannelId: null,
- }),
- ).toEqual({ type: "stamp", stampTabId: "tab-a" });
- });
-
- it("still activates a live tagged tab (windowTabIds provided)", () => {
- expect(
- decideTabNavigation({
- ...base,
- historyTabId: "tab-b",
- windowTabIds: ["tab-a", "tab-b"],
- serverActiveTabId: "tab-a",
- }),
- ).toEqual({ type: "activate", tabId: "tab-b" });
- });
-
- it("trusts the tag when windowTabIds is omitted (legacy callers)", () => {
- expect(
- decideTabNavigation({
- ...base,
- historyTabId: "tab-b",
- serverActiveTabId: "tab-a",
- }),
- ).toEqual({ type: "activate", tabId: "tab-b" });
- });
-});
-
-describe("decideTabNavigation: app-view tabs (Inbox, Command center, …)", () => {
- const base = {
- historyTabId: null as string | null,
- serverActiveTabId: null as string | null,
- activeTab: null,
- routeDashboardId: null as string | null,
- routeTaskId: null as string | null,
- routeChannelId: null as string | null,
- };
-
- it("replaces the active tab in place on an untagged nav to an app view", () => {
- // The reported bug: clicking a nav item (Inbox, Command center, …) must
- // navigate IN the current tab, not open a new one.
- expect(
- decideTabNavigation({
- ...base,
- serverActiveTabId: "tab-a",
- activeTab: {
- id: "tab-a",
- dashboardId: "dash-1",
- taskId: null,
- },
- routeAppView: "inbox",
- }),
- ).toEqual({
- type: "replace",
- tabId: "tab-a",
- dashboardId: null,
- taskId: null,
- channelId: null,
- channelSection: null,
- appView: "inbox",
- stampTabId: "tab-a",
- });
- });
-
- it("a blank tab absorbs the first app view clicked (new-tab page keeps the URL)", () => {
- expect(
- decideTabNavigation({
- ...base,
- serverActiveTabId: "tab-blank",
- activeTab: {
- id: "tab-blank",
- dashboardId: null,
- taskId: null,
- },
- routeAppView: "command-center",
- }),
- ).toEqual({
- type: "replace",
- tabId: "tab-blank",
- dashboardId: null,
- taskId: null,
- channelId: null,
- channelSection: null,
- appView: "command-center",
- stampTabId: "tab-blank",
- });
- });
-
- it("only stamps when the active tab already shows the app view", () => {
- expect(
- decideTabNavigation({
- ...base,
- serverActiveTabId: "tab-a",
- activeTab: {
- id: "tab-a",
- dashboardId: null,
- taskId: null,
- appView: "inbox",
- },
- routeAppView: "inbox",
- }),
- ).toEqual({ type: "stamp", stampTabId: "tab-a" });
- });
-
- it("switching between app views replaces in place (no duplicate tab)", () => {
- expect(
- decideTabNavigation({
- ...base,
- serverActiveTabId: "tab-a",
- activeTab: {
- id: "tab-a",
- dashboardId: null,
- taskId: null,
- appView: "inbox",
- },
- routeAppView: "skills",
- }),
- ).toEqual({
- type: "replace",
- tabId: "tab-a",
- dashboardId: null,
- taskId: null,
- channelId: null,
- channelSection: null,
- appView: "skills",
- stampTabId: "tab-a",
- });
- });
-
- it("opens a tab for an app view when nothing is active", () => {
- expect(
- decideTabNavigation({
- ...base,
- routeAppView: "agents",
- }),
- ).toEqual({
- type: "open",
- dashboardId: null,
- taskId: null,
- channelId: null,
- channelSection: null,
- appView: "agents",
- stampTabId: null,
- });
- });
-});
-
-describe("openOrFocusTab: app-view identity", () => {
- it("dedups the same app view instead of opening a second tab", () => {
- const first = openAppView(snapshot(), "w1", "inbox");
- const second = openAppView(first.snapshot, "w1", "inbox");
- expect(second.opened).toBe(false);
- expect(second.tabId).toBe(first.tabId);
- expect(second.snapshot.tabs).toHaveLength(1);
- });
-
- it("treats different app views as distinct tabs", () => {
- const inbox = openAppView(snapshot(), "w1", "inbox");
- const skills = openAppView(inbox.snapshot, "w1", "skills");
- expect(skills.opened).toBe(true);
- expect(skills.snapshot.tabs).toHaveLength(2);
- });
-
- it("an app-view tab and a blank tab are distinct identities", () => {
- const blank = newBlankTab(snapshot(), { windowId: "w1", makeId, now });
- const inbox = openAppView(blank.snapshot, "w1", "inbox");
- expect(inbox.opened).toBe(true);
- expect(inbox.snapshot.tabs).toHaveLength(2);
- });
-});
-
-describe("setTabTarget: app views", () => {
- it("points a blank tab at an app view and back to blank", () => {
- const blank = newBlankTab(snapshot(), { windowId: "w1", makeId, now });
- const withView = setTabTarget(blank.snapshot, {
- tabId: blank.tabId,
- dashboardId: null,
- taskId: null,
- channelId: null,
- appView: "command-center",
- now,
- });
- expect(withView.tabs[0].appView).toBe("command-center");
- expect(activeTabIsBlank(withView)).toBe(false);
-
- const backToBlank = setTabTarget(withView, {
- tabId: blank.tabId,
- dashboardId: null,
- taskId: null,
- channelId: null,
- now,
- });
- expect(backToBlank.tabs[0].appView).toBeNull();
- expect(activeTabIsBlank(backToBlank)).toBe(true);
- });
-
- it("clears the app view when the tab navigates to a canvas", () => {
- const inbox = openAppView(snapshot(), "w1", "inbox");
- const next = setTabTarget(inbox.snapshot, {
- tabId: inbox.tabId,
- dashboardId: "dash-1",
- taskId: null,
- channelId: "c1",
- now,
- });
- const tab = next.tabs.find((t) => t.id === inbox.tabId);
- expect(tab?.appView).toBeNull();
- expect(tab?.dashboardId).toBe("dash-1");
- });
-});
-
-describe("regression: the reported tab-persistence bugs", () => {
- // Three tabs; the third is active (this is the persisted boot state in the
- // report: "my third tab is taking the URL of any URL I try on tab 1/2").
- function threeTabs() {
- const t1 = open(snapshot(), "w1", "dash-1");
- const t2 = open(t1.snapshot, "w1", "dash-2");
- const t3 = open(t2.snapshot, "w1", "dash-3");
- return { s: t3.snapshot, ids: [t1.tabId, t2.tabId, t3.tabId] as const };
- }
-
- it("a navigation after a tab switch writes to the switched tab, not the previous one", () => {
- const { s, ids } = threeTabs();
- const [t1, , t3] = ids;
- expect(s.windows[0].activeTabId).toBe(t3);
-
- // User clicks tab 1 in the strip → the entry is tagged t1 → activate.
- const clickTab1 = decideTabNavigation({
- historyTabId: t1,
- windowTabIds: ids,
- serverActiveTabId: t3,
- activeTab: null,
- routeDashboardId: "dash-1",
- routeTaskId: null,
- routeChannelId: "c1",
- });
- expect(clickTab1).toEqual({ type: "activate", tabId: t1 });
-
- // The strip applies the focus to its mirror synchronously (the fix): the
- // next decision must see t1 active, NOT the stale t3.
- const afterSwitch = setWindowActiveTab(s, "w1", t1);
- expect(afterSwitch.windows[0].activeTabId).toBe(t1);
-
- // User clicks a nav item (untagged navigation). It must replace t1.
- const activeTab = afterSwitch.tabs.find((t) => t.id === t1);
- const navToInbox = decideTabNavigation({
- historyTabId: null,
- windowTabIds: ids,
- serverActiveTabId: t1,
- activeTab: activeTab
- ? {
- id: activeTab.id,
- dashboardId: activeTab.dashboardId,
- taskId: activeTab.taskId,
- channelId: activeTab.channelId,
- channelSection: activeTab.channelSection,
- appView: activeTab.appView,
- }
- : null,
- routeDashboardId: null,
- routeTaskId: null,
- routeChannelId: null,
- routeAppView: "inbox",
- });
- expect(navToInbox.type).toBe("replace");
- if (navToInbox.type !== "replace") throw new Error("unreachable");
- expect(navToInbox.tabId).toBe(t1);
-
- // Apply the write: only t1 changed; t3 keeps its canvas.
- const applied = setTabTarget(afterSwitch, {
- tabId: navToInbox.tabId,
- dashboardId: navToInbox.dashboardId,
- taskId: navToInbox.taskId,
- channelId: navToInbox.channelId,
- channelSection: navToInbox.channelSection,
- appView: navToInbox.appView,
- now,
- });
- expect(applied.tabs.find((t) => t.id === t1)?.appView).toBe("inbox");
- expect(applied.tabs.find((t) => t.id === t3)?.dashboardId).toBe("dash-3");
- expect(applied.tabs.find((t) => t.id === ids[1])?.dashboardId).toBe(
- "dash-2",
- );
- });
-
- it("switching tabs never rewrites the target tab's contents", () => {
- const { s, ids } = threeTabs();
- const [t1, t2] = ids;
- // Switch t3 → t2 → t1: pure focus changes.
- let cur = setWindowActiveTab(s, "w1", t2);
- cur = setWindowActiveTab(cur, "w1", t1);
- expect(cur.tabs.find((t) => t.id === t1)?.dashboardId).toBe("dash-1");
- expect(cur.tabs.find((t) => t.id === t2)?.dashboardId).toBe("dash-2");
- expect(cur.tabs.find((t) => t.id === ids[2])?.dashboardId).toBe("dash-3");
- // Tab records are untouched by focus changes — same array identity.
- expect(cur.tabs).toBe(s.tabs);
- });
-
- it("back over a closed tab's entry cannot dangle focus and flood new tabs", () => {
- const { s, ids } = threeTabs();
- const [t1, , t3] = ids;
- // Close t1, then replay a history entry tagged with it.
- const closed = closeTabs(s, [t1]);
- const live = closed.tabs.map((t) => t.id);
- const decision = decideTabNavigation({
- historyTabId: t1,
- windowTabIds: live,
- serverActiveTabId: closed.windows[0].activeTabId,
- activeTab: (() => {
- const active = closed.tabs.find(
- (t) => t.id === closed.windows[0].activeTabId,
- );
- return active
- ? {
- id: active.id,
- dashboardId: active.dashboardId,
- taskId: active.taskId,
- channelId: active.channelId,
- channelSection: active.channelSection,
- appView: active.appView,
- }
- : null;
- })(),
- routeDashboardId: "dash-1",
- routeTaskId: null,
- routeChannelId: "c1",
- });
- // Never "activate" the dead id — the route replays in the active tab.
- expect(decision.type).toBe("replace");
- if (decision.type !== "replace") throw new Error("unreachable");
- expect(live).toContain(decision.tabId);
- expect(decision.tabId).toBe(t3);
-
- // And even a hostile setActiveTab with the dead id is a validated no-op.
- expect(setWindowActiveTab(closed, "w1", t1)).toBe(closed);
- });
-
- it("a new blank tab stays blank until the user navigates, then keeps that URL", () => {
- const withTabs = open(snapshot(), "w1", "dash-1");
- const blank = newBlankTab(withTabs.snapshot, {
- windowId: "w1",
- makeId,
- now,
- });
- expect(activeTabIsBlank(blank.snapshot)).toBe(true);
-
- // The landing route is a noop — nothing may rewrite the blank tab.
- const onLanding = decideTabNavigation({
- historyTabId: blank.tabId,
- windowTabIds: blank.snapshot.tabs.map((t) => t.id),
- serverActiveTabId: blank.tabId,
- activeTab: {
- id: blank.tabId,
- dashboardId: null,
- taskId: null,
- channelId: null,
- channelSection: null,
- appView: null,
- },
- routeDashboardId: null,
- routeTaskId: null,
- routeChannelId: null,
- routeAppView: null,
- });
- expect(onLanding).toEqual({ type: "noop" });
-
- // First click (Command center) replaces the blank tab in place…
- const firstNav = decideTabNavigation({
- historyTabId: blank.tabId,
- windowTabIds: blank.snapshot.tabs.map((t) => t.id),
- serverActiveTabId: blank.tabId,
- activeTab: {
- id: blank.tabId,
- dashboardId: null,
- taskId: null,
- channelId: null,
- channelSection: null,
- appView: null,
- },
- routeDashboardId: null,
- routeTaskId: null,
- routeChannelId: null,
- routeAppView: "command-center",
- });
- expect(firstNav.type).toBe("replace");
- if (firstNav.type !== "replace") throw new Error("unreachable");
- expect(firstNav.tabId).toBe(blank.tabId);
-
- const applied = setTabTarget(blank.snapshot, {
- tabId: firstNav.tabId,
- dashboardId: firstNav.dashboardId,
- taskId: firstNav.taskId,
- channelId: firstNav.channelId,
- channelSection: firstNav.channelSection,
- appView: firstNav.appView,
- now,
- });
- // …and the other tab keeps its canvas untouched.
- expect(applied.tabs.find((t) => t.id === blank.tabId)?.appView).toBe(
- "command-center",
- );
- expect(applied.tabs.find((t) => t.id === withTabs.tabId)?.dashboardId).toBe(
- "dash-1",
- );
- });
-});
-
-describe("activeTabIsBlank: app views", () => {
- it("is false when the active tab shows an app view", () => {
- const t = openAppView(snapshot(), "w1", "inbox");
- expect(activeTabIsBlank(t.snapshot)).toBe(false);
- });
-});
diff --git a/products/desktop/packages/shared/src/browser-tabs.ts b/products/desktop/packages/shared/src/browser-tabs.ts
index d196a5a52d78..ae94a73e648f 100644
--- a/products/desktop/packages/shared/src/browser-tabs.ts
+++ b/products/desktop/packages/shared/src/browser-tabs.ts
@@ -1,4 +1,8 @@
-import type { BrowserTab, TabsSnapshot } from "./browser-tabs-schemas";
+import type {
+ BrowserTab,
+ TabsSnapshot,
+ TabViewState,
+} from "./browser-tabs-schemas";
/** Spacing between adjacent tab positions, leaving room to insert without reindex. */
export const POSITION_GAP = 1000;
@@ -9,8 +13,6 @@ type IdFactory = () => string;
export type OpenTabResult = {
snapshot: TabsSnapshot;
tabId: string;
- /** False when an existing tab was focused (dedup) rather than created. */
- opened: boolean;
};
export type CloseTabResult = {
@@ -32,34 +34,6 @@ export function primaryWindow(snapshot: TabsSnapshot) {
return snapshot.windows.find((w) => w.isPrimary) ?? snapshot.windows[0];
}
-/**
- * True when the primary window's active tab is a blank "+" tab: no canvas,
- * task, or channel. The blank tab parks at the spaces index (`/spaces`); the
- * root layout uses this to render the new-tab placeholder there instead of the
- * space list (`showBlankTab` in `__root`).
- */
-export function activeTabIsBlank(snapshot: TabsSnapshot): boolean {
- const w = primaryWindow(snapshot);
- if (!w?.activeTabId) return false;
- const t = snapshot.tabs.find((x) => x.id === w.activeTabId);
- return (
- !!t &&
- t.dashboardId == null &&
- t.taskId == null &&
- t.channelId == null &&
- t.appView == null
- );
-}
-
-/**
- * True when the primary window has no tabs at all — the user closed every tab.
- */
-export function primaryWindowHasNoTabs(snapshot: TabsSnapshot): boolean {
- const w = primaryWindow(snapshot);
- if (!w) return false;
- return !snapshot.tabs.some((t) => t.windowId === w.id);
-}
-
function setActiveTab(
snapshot: TabsSnapshot,
windowId: string,
@@ -95,17 +69,26 @@ export function setWindowActiveTab(
return setActiveTab(snapshot, windowId, tabId);
}
-/** What a tab points at: a canvas, a task, or neither (blank). */
+/** What a tab points at: a canvas, a task, or neither. */
export type TabTarget = {
dashboardId: string | null;
taskId: string | null;
};
/**
- * Everything that identifies a tab's contents: a canvas, a task, or a channel
- * sub-section (channel + section). Two tabs with the same identity are the same
- * page, so dedup and in-tab-nav comparisons key on all four — a channel's
- * `history` and `artifacts`, or two channels' artifacts, are distinct pages.
+ * Where a tab is. `href` is the truth — it is the only field that survives a
+ * route outside the reference vocabulary below, and the only one that keeps
+ * search params. `viewState` carries the nav state the href cannot express.
+ */
+export type TabLocation = {
+ href: string | null;
+ viewState: TabViewState | null;
+};
+
+/**
+ * Route-derived label and icon metadata stored alongside a tab's location.
+ * This cache is compared only to decide whether the active tab record needs an
+ * update. It never establishes equivalence between different tabs.
*/
export type TabIdentity = {
dashboardId: string | null;
@@ -126,83 +109,50 @@ function sameIdentity(a: TabIdentity, b: TabIdentity): boolean {
}
/**
- * Open a target (canvas or task) in a window, deduping within that window: if a
- * tab for the same target already exists in the window it is focused, otherwise
- * a new tab is appended. Duplicates across different windows are allowed.
+ * Whether two view states describe the same visit. Compared structurally so a
+ * change with no navigation — toggling the space list, a rail destination
+ * recording where it was — still reaches the tab record.
*/
-export function openOrFocusTab(
- snapshot: TabsSnapshot,
- input: TabTarget & {
- windowId: string;
- channelId: string | null;
- channelSection?: string | null;
- appView?: string | null;
- makeId: IdFactory;
- now: Clock;
- },
-): OpenTabResult {
- const { windowId, dashboardId, taskId, channelId, makeId, now } = input;
- const channelSection = input.channelSection ?? null;
- const appView = input.appView ?? null;
- const existing = snapshot.tabs.find(
- (t) =>
- t.windowId === windowId &&
- sameIdentity(t, {
- dashboardId,
- taskId,
- channelId,
- channelSection,
- appView,
- }),
- );
- if (existing) {
- const ts = now();
- const withActivity: TabsSnapshot = {
- ...snapshot,
- tabs: snapshot.tabs.map((t) =>
- t.id === existing.id ? { ...t, lastActiveAt: ts } : t,
- ),
- };
- return {
- snapshot: setActiveTab(withActivity, windowId, existing.id),
- tabId: existing.id,
- opened: false,
- };
- }
-
- return appendTab(snapshot, {
- windowId,
- dashboardId,
- taskId,
- channelId,
- channelSection,
- appView,
- makeId,
- now,
- });
+function sameViewState(
+ a: TabViewState | null,
+ b: TabViewState | null,
+): boolean {
+ if (a === b) return true;
+ if (!a || !b) return false;
+ return JSON.stringify(a) === JSON.stringify(b);
}
-function appendTab(
+/**
+ * Open a location in a new tab and focus it.
+ *
+ * No dedup: navigating to something another tab already shows must never move
+ * you to that tab (see {@link decideTabNavigation}), and an explicit open makes
+ * the same promise. Two tabs may hold the same page, as in any browser.
+ */
+export function openTab(
snapshot: TabsSnapshot,
- input: TabTarget & {
- windowId: string;
- channelId: string | null;
- channelSection?: string | null;
- appView?: string | null;
- makeId: IdFactory;
- now: Clock;
- },
+ input: TabTarget &
+ TabLocation & {
+ windowId: string;
+ channelId: string | null;
+ channelSection?: string | null;
+ appView?: string | null;
+ makeId: IdFactory;
+ now: Clock;
+ },
): OpenTabResult {
- const { windowId, dashboardId, taskId, channelId, makeId, now } = input;
+ const { windowId, makeId, now } = input;
const siblings = tabsInWindow(snapshot, windowId);
const lastPos = siblings.length ? siblings[siblings.length - 1].position : 0;
const ts = now();
const tab: BrowserTab = {
id: makeId(),
windowId,
- dashboardId,
- taskId,
- channelId,
+ href: input.href,
+ viewState: input.viewState,
+ dashboardId: input.dashboardId,
+ taskId: input.taskId,
+ channelId: input.channelId,
channelSection: input.channelSection ?? null,
appView: input.appView ?? null,
position: lastPos + POSITION_GAP,
@@ -214,43 +164,61 @@ function appendTab(
return {
snapshot: setActiveTab(withTab, windowId, tab.id),
tabId: tab.id,
- opened: true,
};
}
/**
- * Append a blank tab (no target) and focus it. The strip shows it as an empty
- * placeholder; navigating while it is active replaces its contents via
- * {@link setTabTarget}.
+ * Remove every persisted location and replace it with one fresh tab per window.
+ * Window identities stay stable so live renderer windows remain attached, while
+ * all route, title, and view-state metadata from the previous scope disappears.
*/
-export function newBlankTab(
+export function resetTabs(
snapshot: TabsSnapshot,
- input: { windowId: string; makeId: IdFactory; now: Clock },
-): OpenTabResult {
- return appendTab(snapshot, {
- windowId: input.windowId,
- dashboardId: null,
- taskId: null,
- channelId: null,
- makeId: input.makeId,
- now: input.now,
- });
+ input: { href: string; makeId: IdFactory; now: Clock },
+): TabsSnapshot {
+ let reset: TabsSnapshot = {
+ windows: snapshot.windows.map((window) => ({
+ ...window,
+ activeTabId: null,
+ })),
+ tabs: [],
+ };
+
+ for (const window of reset.windows) {
+ reset = openTab(reset, {
+ windowId: window.id,
+ href: input.href,
+ viewState: null,
+ dashboardId: null,
+ taskId: null,
+ channelId: null,
+ makeId: input.makeId,
+ now: input.now,
+ }).snapshot;
+ }
+
+ return reset;
}
/**
- * Point an existing tab at a target (canvas or task) — the in-tab navigation
- * primitive. Used when the user navigates while a tab is active, so the target
- * replaces the tab's contents instead of opening a new tab. Also focuses it.
+ * Point an existing tab at a location: the in-tab navigation primitive. Used
+ * when the user navigates while a tab is active, so the location replaces the
+ * tab's contents instead of opening a new tab. Focuses it unless the caller is
+ * completing work in a background tab.
*/
export function setTabTarget(
snapshot: TabsSnapshot,
- input: TabTarget & {
- tabId: string;
- channelId: string | null;
- channelSection?: string | null;
- appView?: string | null;
- now: Clock;
- },
+ input: TabTarget &
+ TabLocation & {
+ tabId: string;
+ channelId: string | null;
+ channelSection?: string | null;
+ appView?: string | null;
+ /** Keep the current tab focused when an async operation finishes in the
+ * background. Normal in-tab navigation activates by default. */
+ activate?: boolean;
+ now: Clock;
+ },
): TabsSnapshot {
const tab = snapshot.tabs.find((t) => t.id === input.tabId);
if (!tab) return snapshot;
@@ -261,17 +229,21 @@ export function setTabTarget(
t.id === input.tabId
? {
...t,
+ href: input.href,
+ viewState: input.viewState,
dashboardId: input.dashboardId,
taskId: input.taskId,
channelId: input.channelId,
channelSection: input.channelSection ?? null,
appView: input.appView ?? null,
- lastActiveAt: ts,
+ lastActiveAt: input.activate === false ? t.lastActiveAt : ts,
}
: t,
),
};
- return setActiveTab(withTarget, tab.windowId, input.tabId);
+ return input.activate === false
+ ? withTarget
+ : setActiveTab(withTarget, tab.windowId, input.tabId);
}
/**
@@ -410,37 +382,33 @@ export function setTabOrder(
* decision the renderer makes on every location change; extracted as a pure
* function so the UX rules are testable without a router.
*
- * - `activate`: the entry is tagged with a tab (a tab switch, or a back/forward
- * replay landing on a tab) → focus that tab.
- * - `replace`: an untagged navigation to a target (canvas or task) while a tab
- * is active → swap the active tab's target in place (in-tab navigation), and
- * stamp the entry.
- * - `open`: an untagged navigation to a target with no active tab → open one.
- * - `stamp`: an untagged navigation whose target already matches the active tab
- * → nothing to change, just tag the entry so back/forward can replay it.
- * - `noop`: nothing to do (already on the right tab, or a blank/landing route).
+ * The governing rule: **navigation never changes which tab you are in;
+ * back/forward may.** So there is exactly one branch that moves focus between
+ * tabs (`activate`, driven by a history tag), and it is unreachable from a
+ * plain navigation.
+ *
+ * - `activate`: the entry is tagged with a different live tab (a tab switch, or
+ * a back/forward replay landing on that tab) → focus it.
+ * - `replace`: a navigation while a tab is active → point that tab at the new
+ * location in place, and stamp the entry.
+ * - `open`: a navigation with no active tab → open one.
+ * - `stamp`: the active tab already holds this location → just tag the entry so
+ * back/forward can replay it.
+ * - `noop`: nothing to do.
*/
export type TabNavDecision =
| { type: "activate"; tabId: string }
- | {
+ | ({
type: "replace";
tabId: string;
- dashboardId: string | null;
- taskId: string | null;
- channelId: string | null;
- channelSection: string | null;
- appView: string | null;
stampTabId: string | null;
- }
- | {
+ } & TabLocation &
+ TabIdentity)
+ | ({
type: "open";
- dashboardId: string | null;
- taskId: string | null;
- channelId: string | null;
- channelSection: string | null;
- appView: string | null;
stampTabId: string | null;
- }
+ } & TabLocation &
+ TabIdentity)
| { type: "stamp"; stampTabId: string }
| { type: "noop" };
@@ -451,51 +419,27 @@ export function decideTabNavigation(input: {
* Ids of the tabs that currently exist in this window. A history entry can
* be tagged with a tab that has since been closed (back/forward replays the
* entry); such a dead tag must NOT activate — it falls through and the route
- * decides (in-tab replace / open / stamp), which also re-stamps the entry
- * with a live tab. When omitted, tags are trusted (legacy behaviour).
+ * decides, which also re-stamps the entry with a live tab.
*/
windowTabIds?: readonly string[];
- /**
- * The window's tabs with their identities. When a navigation's route matches
- * an existing tab that isn't the active one, we activate that tab instead of
- * replacing the active tab's target (which would duplicate it) or opening a
- * second copy. This also self-heals a rapid tab switch whose history stamp
- * was lost: it arrives looking like an in-tab nav, but the route still
- * identifies the intended tab, so we focus it rather than corrupt the active
- * tab. When omitted, this dedup is skipped (legacy behaviour).
- */
- windowTabs?: readonly (TabIdentity & { id: string })[];
/** The window's active tab id from the server snapshot (lags history). */
serverActiveTabId: string | null;
/** The active tab record, if one exists. */
activeTab: {
id: string;
- dashboardId: string | null;
- taskId: string | null;
- channelId?: string | null;
- channelSection?: string | null;
- appView?: string | null;
+ href: string | null;
+ viewState: TabViewState | null;
+ identity: TabIdentity;
} | null;
- /** Canvas in the current route, if any. */
- routeDashboardId: string | null;
- /** Task in the current route, if any. */
- routeTaskId: string | null;
- routeChannelId: string | null;
- /** Channel sub-section in the current route, if any. */
- routeChannelSection?: string | null;
- /** Top-level app page in the current route, if any. */
- routeAppView?: string | null;
+ /** The location being navigated to. */
+ href: string;
+ /** Nav state this location carries that the href cannot express. */
+ viewState: TabViewState | null;
+ /** Route-derived label/icon cache written alongside the location. */
+ identity: TabIdentity;
}): TabNavDecision {
- const {
- historyTabId,
- serverActiveTabId,
- activeTab,
- routeDashboardId,
- routeTaskId,
- routeChannelId,
- } = input;
- const routeChannelSection = input.routeChannelSection ?? null;
- const routeAppView = input.routeAppView ?? null;
+ const { historyTabId, serverActiveTabId, activeTab, href, identity } = input;
+ const viewState = input.viewState;
// Tagged entry for a DIFFERENT tab → a tab switch or a back/forward replay.
// Focus it (this is how "back returns to the previous tab" resolves). Two
@@ -511,82 +455,36 @@ export function decideTabNavigation(input: {
return { type: "activate", tabId: historyTabId };
}
- // Navigation within the active tab. A real target is a canvas, a task, or a
- // channel (home or sub-section); the landing/blank route (no channel) is a
- // noop.
- const routeIdentity: TabIdentity = {
- dashboardId: routeDashboardId,
- taskId: routeTaskId,
- channelId: routeChannelId,
- channelSection: routeChannelSection,
- appView: routeAppView,
- };
- if (!routeDashboardId && !routeTaskId && !routeChannelId && !routeAppView) {
- return { type: "noop" };
- }
-
- const activeMatchesRoute =
- !!activeTab &&
- sameIdentity(
- {
- dashboardId: activeTab.dashboardId,
- taskId: activeTab.taskId,
- channelId: activeTab.channelId ?? null,
- channelSection: activeTab.channelSection ?? null,
- appView: activeTab.appView ?? null,
- },
- routeIdentity,
- );
-
- // A blank active tab is a fresh `+` tab waiting for its first target: the
- // navigation is "fill me", never a switch — so the dedup below must not
- // steal it (activating another tab would strand the blank forever).
- const activeIsBlank =
- !!activeTab &&
- activeTab.dashboardId == null &&
- activeTab.taskId == null &&
- (activeTab.channelId ?? null) == null &&
- (activeTab.appView ?? null) == null;
-
- // The route already lives in another tab → focus it instead of replacing the
- // active tab's target (which would leave two tabs on the same identity) or
- // opening a duplicate. Also recovers a rapid switch whose history tag was
- // lost: the intended tab is still identified by the route. Only when the
- // active tab does NOT already show the route — otherwise, if a duplicate tab
- // already exists, we'd bounce between the two identical tabs forever.
- if (!activeMatchesRoute && !activeIsBlank) {
- const existingMatch = input.windowTabs?.find(
- (t) => t.id !== activeTab?.id && sameIdentity(t, routeIdentity),
- );
- if (existingMatch) {
- return { type: "activate", tabId: existingMatch.id };
- }
+ // Everything below is a plain navigation, and it stays in the current tab.
+ //
+ // `href` is the primary key. Identity is a label cache, all-null for every
+ // route outside its vocabulary, so `/loops` and `/archived` are equal through
+ // it; deciding on identity made such navigations look like "already there"
+ // and the strip never followed them.
+ //
+ // The three are OR'd, so identity can only ever ADD a write, never suppress
+ // one. It has to be here: the router updates `location.href` before the new
+ // route's params, so the first pass writes the new href with the OLD
+ // identity. Keyed on href alone, the corrected identity arriving a frame
+ // later compares equal and is dropped, and the tab keeps a stale label for
+ // good (a task tab that renders as its space).
+ if (!activeTab) {
+ return { type: "open", href, viewState, ...identity, stampTabId: null };
}
-
- if (activeTab && !activeMatchesRoute) {
+ if (
+ activeTab.href !== href ||
+ !sameViewState(activeTab.viewState, viewState) ||
+ !sameIdentity(activeTab.identity, identity)
+ ) {
return {
type: "replace",
tabId: activeTab.id,
- dashboardId: routeDashboardId,
- taskId: routeTaskId,
- channelId: routeChannelId,
- channelSection: routeChannelSection,
- appView: routeAppView,
- stampTabId: serverActiveTabId,
- };
- }
- if (!activeTab) {
- return {
- type: "open",
- dashboardId: routeDashboardId,
- taskId: routeTaskId,
- channelId: routeChannelId,
- channelSection: routeChannelSection,
- appView: routeAppView,
+ href,
+ viewState,
+ ...identity,
stampTabId: serverActiveTabId,
};
}
- // Active tab already shows this target — just tag the entry.
return serverActiveTabId
? { type: "stamp", stampTabId: serverActiveTabId }
: { type: "noop" };
diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.ts
index 2f33adbba72a..b03b3459fa0a 100644
--- a/products/desktop/packages/shared/src/flags.ts
+++ b/products/desktop/packages/shared/src/flags.ts
@@ -16,6 +16,13 @@ export const PROJECT_BLUEBIRD_FLAG = "project-bluebird";
* project-bluebird. The key predates the rename, matching the live flag.
*/
export const CHANNELS_LAYOUT_FLAG = "code-spaces-layout";
+/**
+ * Gates the browser-tab strip inside the spaces layout. Off is the same code
+ * path with a single tab (the tab is the window), not a second implementation,
+ * so per-tab history and view state behave as their window-global predecessors.
+ * Requires the spaces layout.
+ */
+export const SPACES_TABS_FLAG = "posthog-desktop-spaces-tabs";
// Gates the Loops feature: the sidebar Loops space and the per-channel Loops tab.
export const LOOPS_FLAG = "loops";
export const DESKTOP_HOME_FLAG = "desktop-home-flag";
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index a98fa893bd2f..65d8962cb56f 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -49,20 +49,20 @@ export {
isBinaryFile,
} from "./binary";
export {
- activeTabIsBlank,
type CloseTabResult,
closeTab,
closeTabs,
decideTabNavigation,
- newBlankTab,
type OpenTabResult,
- openOrFocusTab,
+ openTab,
POSITION_GAP,
primaryWindow,
- primaryWindowHasNoTabs,
+ resetTabs,
setTabOrder,
setTabTarget,
setWindowActiveTab,
+ type TabIdentity,
+ type TabLocation,
type TabNavDecision,
type TabTarget,
} from "./browser-tabs";
@@ -71,8 +71,12 @@ export {
type BrowserWindow,
browserTabSchema,
browserWindowSchema,
+ type RailVisit,
+ railVisitSchema,
type TabsSnapshot,
+ type TabViewState,
tabsSnapshotSchema,
+ tabViewStateSchema,
type WindowBounds,
windowBoundsSchema,
} from "./browser-tabs-schemas";
@@ -305,6 +309,7 @@ export {
} from "./regions";
export { normalizeRepoKey } from "./repo";
export { getTaskRepository, parseRepository } from "./repository";
+export { rewriteSavedLocation } from "./route-migrations";
export { Saga, type SagaLogger, type SagaResult, type SagaStep } from "./saga";
export { scoutSkillNameFromSlug, scoutSkillSlug } from "./scout-naming";
export {
diff --git a/products/desktop/packages/shared/src/route-migrations.test.ts b/products/desktop/packages/shared/src/route-migrations.test.ts
new file mode 100644
index 000000000000..c0b8de3b48a7
--- /dev/null
+++ b/products/desktop/packages/shared/src/route-migrations.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from "vitest";
+import { rewriteSavedLocation } from "./route-migrations";
+
+describe("rewriteSavedLocation", () => {
+ it("normalizes root rewrites to one leading slash", () => {
+ expect(rewriteSavedLocation("/website/home//tasks/123")).toBe("/tasks/123");
+ });
+
+ it("preserves query and hash suffixes on root rewrites", () => {
+ expect(rewriteSavedLocation("/website/home?tab=recent")).toBe(
+ "/?tab=recent",
+ );
+ expect(rewriteSavedLocation("/website/home#section")).toBe("/#section");
+ });
+});
diff --git a/products/desktop/packages/shared/src/route-migrations.ts b/products/desktop/packages/shared/src/route-migrations.ts
new file mode 100644
index 000000000000..e38c122331d5
--- /dev/null
+++ b/products/desktop/packages/shared/src/route-migrations.ts
@@ -0,0 +1,49 @@
+/**
+ * Route prefixes that moved when the app's routes were flattened. Saved
+ * locations are raw hrefs (the startup location, and every persisted browser
+ * tab), so an install that last quit on an old path would otherwise reopen on
+ * a route that no longer exists.
+ *
+ * Lives in shared because both the renderer (startup location) and the main
+ * process (the tab repository) have to apply it.
+ */
+const MOVED_PREFIXES: readonly (readonly [string, string])[] = [
+ ["/website/command-center", "/command-center"],
+ ["/website/mcp-servers", "/mcp-servers"],
+ ["/website/activity", "/activity"],
+ ["/website/skills", "/skills"],
+ ["/website/feeds", "/feeds"],
+ ["/website/home", "/"],
+ ["/website/new", "/new"],
+ ["/website", "/spaces"],
+ ["/code/inbox", "/inbox"],
+ ["/code/agents", "/agents"],
+ ["/code/archived", "/archived"],
+ ["/code/loops", "/loops"],
+ ["/code/tasks", "/tasks"],
+ ["/code/pr", "/pr"],
+ ["/code", "/new"],
+];
+
+// Longest first, so `/website/home` can never be eaten by `/website` however
+// the list above is edited.
+const MOVED_LONGEST_FIRST = [...MOVED_PREFIXES].sort(
+ (a, b) => b[0].length - a[0].length,
+);
+
+/** A saved href on today's routes. Unrecognized hrefs are returned unchanged. */
+export function rewriteSavedLocation(href: string): string {
+ for (const [from, to] of MOVED_LONGEST_FIRST) {
+ if (href === from) return to;
+ const boundary = href[from.length];
+ if (
+ href.startsWith(from) &&
+ (boundary === "/" || boundary === "?" || boundary === "#")
+ ) {
+ const rest = href.slice(from.length);
+ if (to !== "/") return to + rest;
+ return `/${rest.replace(/^\/+/, "")}`;
+ }
+ }
+ return href;
+}
diff --git a/products/desktop/packages/ui/src/features/auth/identifiers.ts b/products/desktop/packages/ui/src/features/auth/identifiers.ts
index 2c4624e8d1cc..fe69d0bd7f4b 100644
--- a/products/desktop/packages/ui/src/features/auth/identifiers.ts
+++ b/products/desktop/packages/ui/src/features/auth/identifiers.ts
@@ -10,8 +10,8 @@ import type { CloudRegion } from "@posthog/shared";
export interface IAuthSideEffects {
onAuthSuccess(region: CloudRegion, projectId: number | null): void;
beforeProjectSwitch(): void;
- onProjectSelected(): void;
- onLogout(previousRegion: CloudRegion | null): void;
+ onProjectSelected(): Promise<void>;
+ onLogout(previousRegion: CloudRegion | null): Promise<void>;
}
export const AUTH_SIDE_EFFECTS = Symbol.for("posthog.ui.auth.sideEffects");
diff --git a/products/desktop/packages/ui/src/features/auth/useAuthMutations.ts b/products/desktop/packages/ui/src/features/auth/useAuthMutations.ts
index 686b0bfb5c72..111fae572225 100644
--- a/products/desktop/packages/ui/src/features/auth/useAuthMutations.ts
+++ b/products/desktop/packages/ui/src/features/auth/useAuthMutations.ts
@@ -3,7 +3,6 @@ import { useHostTRPCClient } from "@posthog/host-router/react";
import type { CloudRegion } from "@posthog/shared";
import { clearCapturedLogs } from "@posthog/ui/shell/logCapture";
import { useMutation } from "@tanstack/react-query";
-import { clearAuthScopedQueries, refreshAuthStateQuery } from "./authQueries";
import { AUTH_SIDE_EFFECTS, type IAuthSideEffects } from "./identifiers";
export function useLoginMutation() {
@@ -48,10 +47,7 @@ export function useSwitchOrgMutation() {
fx.beforeProjectSwitch();
return hostClient.auth.switchOrg.mutate({ orgId });
},
- onSuccess: async () => {
- clearAuthScopedQueries();
- await refreshAuthStateQuery();
- },
+ onSuccess: () => fx.onProjectSelected(),
});
}
@@ -72,10 +68,10 @@ export function useLogoutMutation() {
await hostClient.auth.logout.mutate();
return previous;
},
- onSuccess: (previous) => {
+ onSuccess: async (previous) => {
// Privacy boundary: error bundles must never export another account's logs.
clearCapturedLogs();
- fx.onLogout(previous.cloudRegion);
+ await fx.onLogout(previous.cloudRegion);
},
});
}
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.md b/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.md
index 7f3df79cad37..173416db11f3 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.md
+++ b/products/desktop/packages/ui/src/features/browser-tabs/AGENTS.md
@@ -1,28 +1,33 @@
-# Browser tabs (Channels canvas surface)
+# Browser tabs
-A browser-style tab strip in the Channels title bar (`/spaces/*`), each tab
-fronting an open **canvas, task, or channel sub-section** (a `TabIdentity`:
-`dashboardId | taskId | channel(+section) | blank`).
+A browser-style tab strip in the title bar. **A tab is a location**: it stores an
+`href`, plus the nav state that href cannot express (`viewState`). Any route can
+be a tab — a space, a canvas, a task, `/inbox`, `/loops`, `/settings/$category`.
This file documents the UX and the model; edit it when the behaviour changes.
-Canvases and tasks are equal citizens: navigating to either
-(`/spaces/$channelId/dashboards/$dashboardId` or
-`/spaces/$channelId/tasks/$taskId`) replaces the active tab's target in place,
-the label resolves from the canvas name or the task title, and switching back
-returns to whichever the tab points at. `setTabTarget` is the in-tab-nav
-primitive for both.
-
-Channel sub-sections are tabs too: the header nav (`Loops`, `Recents`,
-`CONTEXT.md` — see `canvas/channelSections.ts`) routes to
-`/spaces/$channelId/<section>`, which is identified by `channelId` +
-`channelSection`. The tab labels by the section (`Recents`) with a `#` icon; the
-channel home (`/spaces/$channelId`, no section) labels by the channel name.
-Every channel tab's hover leads with `#<channel>` then the page name (the home
-tab, whose label already is the channel, shows just the one line). Switching
-sections is an in-tab replace — one channel tab, the section is sub-navigation
-within it — because the identity differs only by `channelSection`.
-Dedup/identity keys on all four fields, so two channels' sub-sections are
-distinct tabs.
+The rule everything else follows:
+
+> **Navigation never changes which tab you're in. Back/forward may.**
+
+So there is exactly one path that moves focus between tabs (a history entry
+tagged with a different tab), and a plain navigation can never reach it.
+Navigating while a tab is active replaces that tab's location in place;
+`setTabTarget` is the in-tab-nav primitive.
+
+**There is no dedup.** Navigating to a page another tab already shows does not
+focus that tab, and opening the same page twice gives you two tabs, as in any
+browser. Earlier versions deduped on a `TabIdentity`, which also made the strip
+navigate off any route outside that identity's vocabulary (`/loops` and
+`/archived` are both all-null through it, so they compared equal).
+
+The identity fields (`dashboardId | taskId | channelId + channelSection |
+appView`) survive **only as a label and icon cache**, written alongside the href.
+Never compare them to decide where a tab is.
+
+The strip is gated inside the spaces layout by `useSpacesTabs`
+(`SPACES_TABS_FLAG`). Off is the same code path with a single tab, not a second
+implementation: with one tab, the tab is the window, so per-tab history and view
+state behave the way the window-global versions did.
## Components & styling
@@ -39,13 +44,12 @@ The feature is deliberately split so the rules are portable and testable:
- **`@posthog/shared` (`browser-tabs.ts`, `browser-tabs-schemas.ts`)** — pure,
host-neutral logic: the domain shapes (`BrowserTab` / `BrowserWindow` /
- `TabsSnapshot` / `TabTarget`), the transforms (`openOrFocusTab`, `newBlankTab`,
- `setTabTarget`, `closeTab`, `closeTabs`, `setTabOrder`), `decideTabNavigation` (what a
- location change means for the strip), and the snapshot predicates
- (`primaryWindow`, `activeTabIsBlank`, `primaryWindowHasNoTabs`) — `activeTabIsBlank`
- gates the blank new-tab placeholder on the `/spaces` index. No
- React, no I/O. This is where behaviour is unit-tested. Back/forward is driven by
- router history + `decideTabNavigation`, not a separate action stack.
+ `TabsSnapshot` / `TabLocation` / `TabViewState` / `RailVisit`), the transforms
+ (`openTab`, `setTabTarget`, `closeTab`, `closeTabs`, `setTabOrder`),
+ `decideTabNavigation` (what a location change means for the strip), and
+ `primaryWindow`. No React, no I/O. This is where behaviour is unit-tested.
+ Back/forward is driven by router history + `decideTabNavigation`, not a
+ separate action stack.
- **`@posthog/workspace-server` (`services/browser-tabs/`, `db/`)** — the
authoritative single-instance `BrowserTabsService` in the main process. Owns
the durable snapshot in sqlite (`browser_tabs` / `browser_windows`), applies
@@ -58,8 +62,8 @@ The feature is deliberately split so the rules are portable and testable:
the snapshot, seeded once and kept live by the subscription.
- **this folder (`@posthog/ui`)** — `BrowserTabStrip` (container; mounted in the
Channels title bar in `router/routes/__root.tsx`), `TabStrip` (presentational),
- `BlankTabView` (the new-tab placeholder), `TaskTabIcon` (sidebar-parity status
- icon for task tabs), the client facade, the boot contribution that seeds +
+ `TaskTabMarks` (a session tab's status dot, in the session
+ list's vocabulary), the client facade, the boot contribution that seeds +
subscribes the store, and **`tabsSync.ts` — the local-first sync policy**:
every operation applies its shared pure transform to the renderer mirror
synchronously (interactions are instant; new tabs mint their id client-side
@@ -87,10 +91,11 @@ differ. Desktop ships first.
- Labels **fade** at the right edge (a CSS mask, not an ellipsis). The close
affordance reveals on hover; on hover the button gains right padding so the
label shrinks and its fade follows, clearing room for the close button.
-- Icon: a canvas tab uses the template icon (`iconForTemplate`); a task tab uses
- `TaskTabIcon` — the **same status icon as the sidebar** (cloud run status, PR
- state, generating / unread / pinned / needs-permission), so a tab and its
- sidebar row never drift.
+- Icon: a canvas tab uses the template icon (`iconForTemplate`); a session tab
+ uses **the session list's status dot** (`TaskTabMarks` → `taskDot`), so a tab
+ and its list row never say different things about the same session. The list's
+ trailing identity badges are deliberately *not* carried over: a pill is
+ `max-w-[200px]` and shrinking, and the name is what a tab is scanned for.
- Hover shows a tooltip with the name and (if any) the channel. All tab tooltips
share one `TooltipProvider` so moving across tabs shows each instantly.
- The **active tab's name + highlight follow the current route / history state**
@@ -98,20 +103,30 @@ differ. Desktop ships first.
round-trips (see Gotchas).
### Opening, replacing, the new-tab page
-- **Navigating while a tab is active replaces that tab's target in place**
- (in-tab navigation) — it does *not* open or dedup-focus another tab.
-- **New tabs come only from `+`.** `+` opens a **blank tab** (no target); the
- content pane renders a quill `<Empty>` "new tab page" (`BlankTabView`).
- Navigating to a canvas/task while the blank tab is active fills it in.
-- `openOrFocusTab` **dedups per window** on the full target (canvas or task);
- the same target may be open in different windows.
+- **Navigating while a tab is active replaces that tab's location in place**
+ (in-tab navigation). It does *not* open or focus another tab, ever.
+- **New tabs come only from explicit new-tab actions.** `+` opens a tab on
+ `/spaces`; Cmd/Ctrl-clicking a navigation destination opens that destination's
+ root in a new tab (the rail in Spaces, the sidebar in the legacy layout). The
+ space index renders the space grid and acts as the new-tab page. Without the
+ spaces layout the Code new-task screen stands in.
+- `openTab` always appends. There is no dedup to focus an existing tab.
### Closing
- Closing the active tab focuses its neighbour.
- Closing the last tab of a **secondary** window closes the window; closing the
- last tab of the **primary** window empties the strip and lands on the
- **new-tab screen** at `/spaces` — it does *not* jump to the first channel
- (see Gotchas).
+ last tab of the **primary** window lands on the default (`#me` under the
+ spaces layout, the Code new-task screen otherwise), which opens a fresh tab.
+
+### Keyboard
+- **⌘1-9 switches tabs**, the browser way: 1-8 pick that position, 9 picks the
+ last tab however many there are. It reads the **displayed** (pinned-first)
+ order, so the key matches what you count on screen.
+- Those keys have other owners elsewhere — starred spaces (`ChannelHotkeys`)
+ and task switching (`GlobalEventHandlers`) — so both yield wherever the strip
+ claims them, gated on the same `useSpacesTabs()`. Two owners firing on one
+ press is worse than either.
+- ⌘T opens a tab, ⌘W closes the active one.
### Context menu & pinning
- Right-click on a pill opens a quill `ContextMenu`: **Pin/Unpin tab**, then
@@ -167,9 +182,40 @@ differ. Desktop ships first.
tab is derived from the current history entry; entries for tabs you've since
closed are skipped.
+### Per-tab nav state
+Each tab carries the nav state its href cannot express, in `viewState`:
+
+- `listOpen` / `spaceId` — which sidebar pane is drawn and the space it is drawn
+ over, so two tabs can sit on different spaces with different sidebars.
+- `lastByPane` — **where each rail destination was when this tab last left it.**
+ A rail click navigates the active tab back to its own remembered href rather
+ than to the destination's root. Per tab on purpose: a window-global memory
+ would let one tab's rail click restore an href another tab established.
+
+`BrowserTabStrip`'s navigation effect is the **single writer for settled router
+navigation**. It runs on every settled navigation, including the ones a rail
+click does not make (hotkeys, deep links, links in the content), which is why a
+note taken as you click away is not enough. Async completion can explicitly
+retarget its originating background tab as described below. `railHistoryStore`
+/ `RailHistorySync` were the window-global predecessors and are gone.
+
+### In-flight task creation
+- Submitting a new task snapshots the prompt and originating `tabId` before its
+ first asynchronous preflight. Switching tabs cannot unmount the editor out
+ from under task creation or change which prompt is sent.
+- Pending, success, and failure routes replace the originating tab. When that
+ tab is in the background, `setTabTarget({ activate: false })` updates its
+ durable target without changing the active tab.
+- New-task editor drafts are keyed by `tabId`. Two tabs on the same `/new` route
+ can hold different prompts; successful submission or closing a tab clears
+ only that tab's draft.
+
### Cross-window & persistence
-- Tabs, order, and windows persist to sqlite; the full session (all windows +
- their tabs + active tab) is restored on launch.
+- Tabs, order, windows, and each tab's `href` + `viewState` persist to sqlite;
+ the full session (all windows + their tabs + active tab) is restored on launch.
+- `rewriteSavedLocation` (in `@posthog/shared`) runs over persisted hrefs on
+ load, so a snapshot written before the routes were flattened does not restore
+ tabs onto `/website/*` routes that no longer exist.
- Per-tab `scrollState` is reserved but **unwired** — scroll restoration is a
later follow-up (it needs a sandbox postMessage contract; the canvas iframe is
null-origin so the host can't read scroll).
@@ -182,6 +228,11 @@ differ. Desktop ships first.
tag as a "switch" **only when it differs** from the active tab; an equal tag
falls through to a route-based replace. Getting this wrong makes in-tab
navigation silently noop (the tab reverts on switch-away).
+- **A same-href tab switch must push history directly.** Router-level
+ `navigate({ href })` may collapse a navigation when the selected tab has the
+ same href as the active tab, leaving the old history `tabId` in place. Tab
+ selection uses `pushTabHistoryEntry` so the selected tab identity changes
+ even when its location does not.
- **Stamp with `loc.href`.** When stamping a history entry, use the full
`router.history.location.href` (a string). Reconstructing `pathname + search`
crashes — `search` is parsed to an object at runtime ("Cannot convert object
@@ -191,6 +242,31 @@ differ. Desktop ships first.
round-trips. The strip prefers history for "which tab is active" and resolves
the active tab's label from the *route* target so the name/highlight don't lag
a navigation behind.
+- **Tab selection writes history first.** A click must not optimistically focus
+ the mirror or restore the target's `viewState` while the outgoing route is
+ still settled. That transient pairing lets the navigation effect write the
+ outgoing href into the selected tab. Selection only pushes the target's
+ tagged history entry; that settled entry drives view-state restore,
+ activation, and durable focus through the navigation effect.
+- **The effect reconciles SETTLED state only (`settledLocation.ts`).** During a
+ pending navigation the router's `location` is already the destination while
+ `resolvedLocation` (and `matches`, and so `params` / `railPane`) still describe
+ the page being left. Read the href from one and the tab tag from the other and
+ the effect is told "tab B is on tab A's href", which it writes to B — this is
+ the "switching tabs rewrites another tab's URL" corruption, and it has been
+ reintroduced twice by changing one selector and not the other. `settledLocation`
+ returns the pair from one snapshot and marks it current only when both the
+ href and tab owner match the in-flight entry. The effect must skip every write
+ until that happens: even a harmless-looking `stamp` would otherwise replace
+ the new entry's tab owner with the outgoing tab. The in-flight `location`
+ still drives the strip's **highlight**, which should flip instantly — that is
+ a render, not a write.
+- **A session is not always a path param.** Activity reads its picked item out
+ of `/activity`'s *search*, and a feed does the same. The strip's identity and
+ label therefore come from `useActiveSession()`, never `params.taskId`, or a
+ tab sitting on an open session reads "New tab". That selection lives in the
+ URL precisely so a tab can name it and restore it — don't move it back into a
+ store.
- **Label resolution is reactive + cached.** Names come from the active
record's warm fetch, then the channel list / all-tasks list, then a
module-level cache — and the `tabs` memo references those sources directly (so
@@ -199,15 +275,9 @@ differ. Desktop ships first.
cannot nest inside the Button (button-in-button is invalid + fails a11y lint);
it's an absolutely-positioned sibling. The wrapper is `flex` so it hugs the
button height (a block wrapper adds an inline line-box ~2px taller).
-- **`/spaces` is a page, not a redirect.** It used to bounce to `channels[0]`,
- which put a channel in the route and made `decideTabNavigation` open a tab for
- it — hijacking a blank `+` tab, or re-filling a strip the user had just
- emptied. Three guards existed only to hold that bounce off
- (`activeTabIsBlank`, `primaryWindowHasNoTabs`, and an `onIndexPath` check for
- the frames TanStack renders the stale index after the URL has already moved).
- The index renders the space list in place now, so none of them are needed and
- the blank `+` tab keeps its placeholder through `showBlankTab` in `__root`.
- Don't reintroduce a redirect here.
+- **`/spaces` is a page, not a redirect.** It used to bounce to `channels[0]`.
+ It is now where `+` lands, so a redirect there would send every new tab
+ somewhere the user did not ask for. Don't reintroduce one.
- **All writes are local-first (`tabsSync.ts`).** Close/open/new/reorder apply
their shared transform to the mirror and navigate in the same tick; the
`/spaces` index therefore always renders against post-mutation state. Mutation results and
@@ -219,14 +289,13 @@ differ. Desktop ships first.
## Testing
- **Pure behaviour** is tested in `@posthog/shared` (`browser-tabs.test.ts`):
- open/dedup, close (neighbour / secondary-window / primary-landing),
- `closeTabs` (bulk close + anchor focus), `setTabOrder`, `newBlankTab`,
- `setTabTarget` (canvas + task), and
- **`decideTabNavigation`** — which encodes the activate / replace / open /
- stamp / noop decision the strip makes on every navigation (including "back
- returns to the previous tab" and the inherited-tag in-tab case) — plus the
- snapshot predicates (`activeTabIsBlank`, `primaryWindowHasNoTabs`,
- `primaryWindow`).
+ `openTab` (always appends, never dedups), close (neighbour /
+ secondary-window / primary-landing), `closeTabs` (bulk close + anchor focus),
+ `setTabOrder`, `setTabTarget` (href + view state + label cache move together),
+ `primaryWindow`, `setWindowActiveTab`, and **`decideTabNavigation`** — the
+ activate / replace / open / stamp / noop decision the strip makes on every
+ navigation, including the two cases href-matching exists for (two routes
+ outside the label vocabulary, and a search-param-only change).
`BrowserTabStrip`'s effect dispatches that decision, so the tested function is
the one that runs.
- **Presentational** rendering is tested in `TabStrip.test.tsx` (active styling,
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/BlankTabView.tsx b/products/desktop/packages/ui/src/features/browser-tabs/BlankTabView.tsx
deleted file mode 100644
index c764b7405b71..000000000000
--- a/products/desktop/packages/ui/src/features/browser-tabs/BlankTabView.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { NewspaperClippingIcon } from "@phosphor-icons/react";
-import {
- Empty,
- EmptyDescription,
- EmptyHeader,
- EmptyMedia,
- EmptyTitle,
-} from "@posthog/quill";
-
-/** Placeholder shown when the active browser tab has no canvas yet. */
-export function BlankTabView() {
- return (
- <Empty className="h-full">
- <EmptyHeader>
- <EmptyMedia variant="icon">
- <NewspaperClippingIcon size={28} />
- </EmptyMedia>
- <EmptyTitle>New tab</EmptyTitle>
- <EmptyDescription>
- Pick a channel from the sidebar to open it here.
- </EmptyDescription>
- </EmptyHeader>
- </Empty>
- );
-}
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx
index 56d5e7e860a8..ab85904bbead 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx
+++ b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx
@@ -1,26 +1,17 @@
-import {
- BookOpenTextIcon,
- BrainIcon,
- PlugsConnectedIcon,
- RobotIcon,
- SquaresFourIcon,
- TrayIcon,
-} from "@phosphor-icons/react";
-import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";
import { useService } from "@posthog/di/react";
-import { useHostTRPC } from "@posthog/host-router/react";
import {
closeTab as closeTabLocal,
closeTabs as closeTabsLocal,
decideTabNavigation,
- newBlankTab as newBlankTabLocal,
- openOrFocusTab as openOrFocusLocal,
+ openTab as openTabLocal,
PROJECT_BLUEBIRD_FLAG,
primaryWindow,
setTabOrder,
setTabTarget as setTabTargetLocal,
setWindowActiveTab,
+ type TabIdentity,
type TabsSnapshot,
+ type TabViewState,
} from "@posthog/shared";
import { channelSectionFor } from "@posthog/ui/features/canvas/channelSections";
import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";
@@ -31,48 +22,57 @@ import {
useDashboard,
useDashboards,
} from "@posthog/ui/features/canvas/hooks/useDashboards";
+import { useRailPane } from "@posthog/ui/features/canvas/hooks/useRailSurface";
+import {
+ applyTabViewState,
+ useChannelPaneStore,
+} from "@posthog/ui/features/canvas/stores/channelPaneStore";
+import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";
import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";
+import { useActiveSession } from "@posthog/ui/features/navigation/useActiveSession";
import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";
import { getLeafPanel } from "@posthog/ui/features/panels/panelStoreHelpers";
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
+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 { useIsWorkspaceCloudRun } from "@posthog/ui/features/workspace/useWorkspace";
import { useAppView } from "@posthog/ui/router/useAppView";
-import { useMutation, useQuery } from "@tanstack/react-query";
+import { isMac } from "@posthog/ui/utils/platform";
+import { useQuery } from "@tanstack/react-query";
import {
useNavigate,
useParams,
useRouter,
useRouterState,
} from "@tanstack/react-router";
-import { type ReactNode, useEffect, useMemo } from "react";
+import { useCallback, useEffect, useMemo } from "react";
import { useHotkeys } from "react-hotkeys-hook";
+import { shouldHandleBrowserTabSwitch } from "./browserTabShortcuts";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "./browserTabsClient";
import {
frontOfUnpinnedOrder,
partitionPinnedFirst,
storedOrderIds,
} from "./displayOrder";
import { usePinnedTabsStore } from "./pinnedTabsStore";
+import { settledLocation } from "./settledLocation";
import { TabStrip, type TabView } from "./TabStrip";
-import { TaskTabIcon } from "./TaskTabIcon";
-import { useTabReorderStore } from "./tabReorderStore";
+import { TaskTabDot } from "./TaskTabMarks";
import {
- applyLocalTransform,
- persistWrite,
- readMirror,
- reseedMirror,
-} from "./tabsSync";
+ isTabAppView,
+ TAB_APP_VIEW_META,
+ type TabAppView,
+} from "./tabAppViews";
+import { pushTabHistoryEntry } from "./tabHistory";
+import { useTabReorderStore } from "./tabReorderStore";
+import { applyLocalTransform, persistWrite, readMirror } from "./tabsSync";
import { useTabsSnapshot } from "./useBrowserTabs";
-
-/** The active tab id is carried in router history state so back/forward replay
- * tab switches. */
-declare module "@tanstack/history" {
- interface HistoryState {
- tabId?: string;
- }
-}
+import { useOpenBrowserTab } from "./useOpenBrowserTab";
/**
* Module-level caches of display info, keyed by id. Tabs store only references;
@@ -112,6 +112,8 @@ function taskHasCloseableEditorTab(taskId: string | undefined): boolean {
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;
@@ -119,64 +121,55 @@ type TabRef = {
appView: string | null;
};
-// The top-level app pages that can be a tab. Keyed by useAppView's view.type;
-// each maps to its canonical route (a task/canvas/channel tab has its own
-// route, these don't) plus the strip's label + icon.
-type AppView =
- | "inbox"
- | "agents"
- | "skills"
- | "mcp-servers"
- | "command-center"
- | "context";
-
-const APP_VIEW_META: Record<AppView, { label: string; icon: ReactNode }> = {
- inbox: { label: "Inbox", icon: <TrayIcon size={14} /> },
- agents: { label: "Agents", icon: <RobotIcon size={14} /> },
- skills: { label: "Skills", icon: <BrainIcon size={14} /> },
- "mcp-servers": {
- label: "MCP servers",
- icon: <PlugsConnectedIcon size={14} />,
- },
- "command-center": {
- label: "Command center",
- icon: <SquaresFourIcon size={14} />,
- },
- context: { label: "Context", icon: <BookOpenTextIcon size={14} /> },
-};
-
-function isAppView(value: string): value is AppView {
- return value in APP_VIEW_META;
-}
-
export function BrowserTabStrip() {
const spacesLayout = useChannelsLayout();
- const logger = useService<RootLogger>(ROOT_LOGGER);
const snapshot = useTabsSnapshot();
const navigate = useNavigate();
const router = useRouter();
- const trpc = useHostTRPC();
+ const client = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);
+ const openBrowserTab = useOpenBrowserTab();
const params = useParams({ strict: false }) as {
channelId?: string;
dashboardId?: string;
taskId?: string;
};
+ // 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
+ // matters). `href`, not pathname — search params are part of where a tab is,
+ // and reconstructing `pathname + search` crashes because search is parsed to
+ // an object at runtime.
+ const settled = useRouterState({ select: settledLocation });
+ const locationHref = settled.href;
+ const settledTabId = settled.tabId;
+ const locationIsCurrent = settled.isCurrent;
+ // The nav state the href cannot express: which sidebar pane is drawn, and the
+ // space it is drawn over. Recorded per tab so two tabs can sit on different
+ // spaces with different sidebars.
+ const listOpen = useChannelPaneStore((s) => s.pane === "list");
+ const scopedSpaceId = useCurrentChannelStore((s) => s.currentChannelId);
+ // Which rail destination this location belongs to, so the tab can remember
+ // where that destination was when it left.
+ const railPane = useRailPane();
+ // Which session the content pane is about, wherever it came from: a path
+ // param, Activity's picked item, or a feed's.
+ const activeSession = useActiveSession();
// Tabs work in both spaces: space-scoped tabs live under /spaces, while a
// plain task tab (no space) is unscoped. The space decides where a task or
// blank tab navigates.
const inChannels = pathname.startsWith("/spaces");
- // Top-level app pages (Inbox, Agents, Skills, MCP servers, Command Center)
- // are tab targets too. useAppView normalizes the scoped and unscoped routes
- // to the same view.type, so a tab survives either space. A
- // top-level route that ISN'T here falls through to `task-input`, and the
- // strip then reconciles the location against the wrong tab and navigates
- // straight back off the page.
+ // Top-level app pages are tab targets too. Their typed metadata keeps route
+ // classification, persisted labels, and rendered labels in one vocabulary.
const view = useAppView();
- const routeAppView: AppView | null = isAppView(view.type) ? view.type : null;
+ const routeAppView: TabAppView | null = isTabAppView(view.type)
+ ? view.type
+ : null;
const { channels } = useChannels();
// Whether the channels surface is live — the same gate the sidebar uses. This
@@ -190,11 +183,6 @@ export function BrowserTabStrip() {
const channelsEnabled =
useSidebarStore((s) => s.channelsEnabled) && bluebirdEnabled;
- // A cloud run is read-only, so opening a new tab there makes no sense — hide
- // the new-tab button and disable its Cmd/Ctrl+T shortcut. Off a task route
- // params.taskId is undefined, so this is false and the button stays.
- const isCloudRun = useIsWorkspaceCloudRun(params.taskId);
-
// The active channel sub-section (artifacts/history/context) is the
// route segment after the channelId. Null when on the channel home or a
// non-section route (canvas/task), so a channel-home tab labels by name.
@@ -204,28 +192,13 @@ export function BrowserTabStrip() {
return channelSectionFor(seg)?.key ?? null;
}, [pathname, params.channelId]);
- // Local-first sync (see tabsSync.ts): every operation applies its shared
- // pure transform to the mirror synchronously via applyLocalTransform, then
- // persists in the background via persistWrite. The mutations below are pure
- // transport — their returned snapshots are handled by persistWrite's
- // last-settle reconcile, never applied directly, so a stale echo can't
- // rewind the mirror mid-interaction.
- const openOrFocus = useMutation(
- trpc.browserTabs.openOrFocus.mutationOptions(),
- );
- const newBlankTab = useMutation(
- trpc.browserTabs.newBlankTab.mutationOptions(),
- );
- const setTabTarget = useMutation(
- trpc.browserTabs.setTabTarget.mutationOptions(),
- );
- const close = useMutation(trpc.browserTabs.close.mutationOptions());
- const closeMany = useMutation(trpc.browserTabs.closeMany.mutationOptions());
- const setOrder = useMutation(trpc.browserTabs.setOrder.mutationOptions());
- const setActiveTab = useMutation(
- trpc.browserTabs.setActiveTab.mutationOptions(),
- );
-
+ // Local-first sync (see tabsSync.ts): each mutation applies its shared pure
+ // transform to the mirror synchronously via applyLocalTransform, then
+ // persists in the background via persistWrite. Selection itself is
+ // history-first; the settled navigation triggers its local focus mutation.
+ // The mutations below are pure transport — their returned snapshots are
+ // handled by persistWrite's last-settle reconcile, never applied directly,
+ // so a stale echo can't rewind the mirror mid-interaction.
const pinnedTabIds = usePinnedTabsStore((s) => s.pinnedTabIds);
const togglePinned = usePinnedTabsStore((s) => s.togglePinned);
const prunePinned = usePinnedTabsStore((s) => s.prune);
@@ -252,6 +225,11 @@ export function BrowserTabStrip() {
const activeTabId =
(historyTabIsLive ? historyTabId : null) ?? win?.activeTabId ?? null;
+ const channelName = useMemo(() => {
+ const map = new Map(channels.map((c) => [c.id, c.name]));
+ return (id: string | null) => (id ? (map.get(id) ?? null) : null);
+ }, [channels]);
+
// Names feed the tab labels. The channel canvas list + all-tasks list cover
// most tabs; a direct fetch of the *current route's* canvas/task (warm cache
// from the detail page) makes the focused tab's name update the instant you
@@ -261,9 +239,12 @@ export function BrowserTabStrip() {
const { dashboards } = useDashboards(params.channelId);
const { dashboard: activeRecord } = useDashboard(params.dashboardId);
const { data: allTasks } = useTasks(undefined, { enabled: hasTaskTab });
+ // Keyed on the active SESSION, not the path param: on Activity the session
+ // comes from the route's search, and without this its title would wait on the
+ // all-tasks list (itself gated on a tab already carrying a taskId).
const { data: activeTaskRecord } = useQuery({
- ...taskDetailQuery(params.taskId ?? ""),
- enabled: !!params.taskId,
+ ...taskDetailQuery(activeSession.taskId ?? ""),
+ enabled: !!activeSession.taskId,
});
// Remember names so a background tab from another channel keeps its label
// after its channel's list unloads. Written in an effect (not during render)
@@ -284,6 +265,49 @@ export function BrowserTabStrip() {
}
}, [dashboards, activeRecord, allTasks, activeTaskRecord]);
+ // The name the active tab resolves for itself, stored so the tab still reads
+ // as a session (not as its space) while it is in the background. Null while
+ // the record is still loading, which keeps a loading frame from overwriting
+ // the name already stored.
+ const activeTitle = useMemo(() => {
+ const sessionId = activeSession.taskId;
+ if (sessionId) {
+ if (activeTaskRecord?.id === sessionId) return activeTaskRecord.title;
+ return allTasks?.find((t) => t.id === sessionId)?.title ?? null;
+ }
+ if (params.dashboardId) {
+ if (activeRecord?.id === params.dashboardId) return activeRecord.name;
+ return dashboards.find((d) => d.id === params.dashboardId)?.name ?? null;
+ }
+ return null;
+ }, [
+ activeSession.taskId,
+ params.dashboardId,
+ activeTaskRecord,
+ allTasks,
+ activeRecord,
+ dashboards,
+ ]);
+
+ const routeTitle = useMemo(() => {
+ if (activeTitle) return activeTitle;
+ const currentChannelId =
+ params.channelId ?? activeSession.channelId ?? null;
+ if (currentChannelId) {
+ const channel = channelName(currentChannelId);
+ return channelSectionFor(routeChannelSection)?.label ?? channel;
+ }
+ if (routeAppView) return TAB_APP_VIEW_META[routeAppView].label;
+ return null;
+ }, [
+ activeTitle,
+ params.channelId,
+ activeSession.channelId,
+ channelName,
+ routeChannelSection,
+ routeAppView,
+ ]);
+
// Resolve what the current location means for the strip (see
// decideTabNavigation) and apply it: focus a tab, replace the active tab's
// target in place, open a tab, and/or stamp the history entry with the tab it
@@ -298,7 +322,10 @@ export function BrowserTabStrip() {
// the stale tab — yanking focus back and mis-targeting the follow-up
// navigation as an in-tab replace of the wrong tab.
useEffect(() => {
- if (!windowId) return;
+ // A history push updates `location` before `resolvedLocation`. Writing in
+ // that gap can restamp the new entry with the outgoing tab, so the route
+ // must fully own both its href and tab tag before reconciliation starts.
+ if (!windowId || !locationIsCurrent) return;
const stamp = (tabId: string) => {
const loc = router.history.location;
// Already tagged — skip the replace so history entries and router
@@ -314,104 +341,119 @@ export function BrowserTabStrip() {
const mirrorActive = mirrorWin?.activeTabId
? mirrorTabs.find((t) => t.id === mirrorWin.activeTabId)
: 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
+ // unrelated routes look identical through it.
+ const identity: TabIdentity = {
+ dashboardId: params.dashboardId ?? null,
+ // `activeSession`, not `params`: Activity and a feed read a session into
+ // the pane from their route's SEARCH rather than a path param, so the tab
+ // would otherwise show "New tab" over an open session.
+ taskId: activeSession.taskId ?? null,
+ channelId: params.channelId ?? activeSession.channelId ?? null,
+ channelSection: routeChannelSection,
+ appView: routeAppView,
+ };
+ // Where each rail destination was when this tab last left it, carried
+ // forward from the tab's own memory. Per tab, so one tab's rail click can
+ // never restore an href another tab established. One writer: this effect
+ // runs on every settled navigation, including the ones a rail click does
+ // not make (hotkeys, deep links, links in the content).
+ const visit = {
+ href: locationHref,
+ ...(railPane === "spaces" ? { listOpen, spaceId: scopedSpaceId } : {}),
+ };
+ const viewState: TabViewState = {
+ // Keep the stored name when nothing has resolved yet, so a loading frame
+ // does not blank a background tab's label.
+ title: routeTitle ?? mirrorActive?.viewState?.title,
+ listOpen,
+ spaceId: scopedSpaceId,
+ lastByPane: {
+ ...(mirrorActive?.viewState?.lastByPane ?? {}),
+ [railPane]: visit,
+ },
+ };
const decision = decideTabNavigation({
- historyTabId: historyTabId ?? null,
+ // 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,
// 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),
- // Identities of this window's tabs, so a navigation to a target already
- // open in another tab focuses it instead of duplicating it (and a rapid
- // switch whose history stamp was lost self-heals to the right tab).
- windowTabs: mirrorTabs.map((t) => ({
- id: t.id,
- dashboardId: t.dashboardId,
- taskId: t.taskId,
- channelId: t.channelId,
- channelSection: t.channelSection,
- appView: t.appView,
- })),
serverActiveTabId: mirrorWin?.activeTabId ?? null,
activeTab: mirrorActive
? {
id: mirrorActive.id,
- dashboardId: mirrorActive.dashboardId,
- taskId: mirrorActive.taskId,
- channelId: mirrorActive.channelId,
- channelSection: mirrorActive.channelSection,
- appView: mirrorActive.appView,
+ href: mirrorActive.href,
+ viewState: mirrorActive.viewState ?? null,
+ identity: {
+ dashboardId: mirrorActive.dashboardId,
+ taskId: mirrorActive.taskId,
+ channelId: mirrorActive.channelId,
+ channelSection: mirrorActive.channelSection,
+ appView: mirrorActive.appView,
+ },
}
: null,
- routeDashboardId: params.dashboardId ?? null,
- routeTaskId: params.taskId ?? null,
- routeChannelId: params.channelId ?? null,
- routeChannelSection,
- routeAppView,
+ href: locationHref,
+ viewState,
+ identity,
});
+ const location = { href: locationHref, viewState };
switch (decision.type) {
case "activate": {
+ // Put this tab's sidebar back before anything else runs. The pane and
+ // the scoped space are window-global, so without this the next pass
+ // reads the tab we LEFT and replaces this tab's stored view state with
+ // it — switching to a tab would erase its own memory.
+ const target = mirrorTabs.find((t) => t.id === decision.tabId);
+ if (target?.viewState) applyTabViewState(target.viewState);
// Focus in the mirror synchronously; persist in the background.
applyLocalTransform((s) =>
setWindowActiveTab(s, windowId, decision.tabId),
);
void persistWrite(() =>
- setActiveTab.mutateAsync({ windowId, tabId: decision.tabId }),
+ client.setActiveTab({ windowId, tabId: decision.tabId }),
);
- // Heal the history tag to the tab we're activating. Normally it already
- // matches (a tagged switch), so `stamp` no-ops. When the dedup path
- // activated an existing tab the route pointed at (a switch whose stamp
- // was lost), the entry still carries the STALE tab — left unhealed, the
- // first branch above would re-activate it next render and ping-pong with
- // the dedup (a "Maximum update depth exceeded" loop). Stamping breaks it.
+ // Heal the history tag to the tab we're activating. Normally it
+ // already matches (a tagged switch), so `stamp` no-ops.
stamp(decision.tabId);
break;
}
case "replace": {
const target = {
tabId: decision.tabId,
- dashboardId: decision.dashboardId,
- taskId: decision.taskId,
- channelId: decision.channelId,
- channelSection: decision.channelSection,
- appView: decision.appView,
+ ...location,
+ ...identity,
};
- // Synchronous local apply keeps re-entrant runs (and the /website index
- // redirect guard) from ever seeing the pre-navigation target.
+ // Synchronous local apply keeps re-entrant runs from ever seeing the
+ // pre-navigation location.
applyLocalTransform((s) =>
setTabTargetLocal(s, { ...target, now: Date.now }),
);
- void persistWrite(() => setTabTarget.mutateAsync(target));
+ void persistWrite(() => client.setTabTarget(target));
if (decision.stampTabId) stamp(decision.stampTabId);
break;
}
case "open": {
- const input = {
- windowId,
- dashboardId: decision.dashboardId,
- taskId: decision.taskId,
- channelId: decision.channelId,
- channelSection: decision.channelSection,
- appView: decision.appView,
- };
+ const input = { windowId, ...location, ...identity };
// Mint the id here so the local apply and the persisted state agree on
- // it; openOrFocusLocal may instead dedup-focus an existing tab, in
- // which case the minted id goes unused (identically on the server).
+ // it, and so a replayed call is idempotent on the server.
const mintedId = crypto.randomUUID();
- let openedTabId: string = mintedId;
- applyLocalTransform((s) => {
- const result = openOrFocusLocal(s, {
- ...input,
- makeId: () => mintedId,
- now: Date.now,
- });
- openedTabId = result.tabId;
- return result.snapshot;
- });
- void persistWrite(() =>
- openOrFocus.mutateAsync({ ...input, tabId: mintedId }),
+ applyLocalTransform(
+ (s) =>
+ openTabLocal(s, {
+ ...input,
+ makeId: () => mintedId,
+ now: Date.now,
+ }).snapshot,
);
+ void persistWrite(() => client.openTab({ ...input, tabId: mintedId }));
// Stamp the entry with the tab that now owns this route.
- stamp(openedTabId);
+ stamp(mintedId);
break;
}
case "stamp":
@@ -423,23 +465,23 @@ export function BrowserTabStrip() {
// initial route. Everything else here is location; mirror state is read
// fresh inside, deliberately NOT a dependency (see the comment above).
windowId,
- historyTabId,
+ locationIsCurrent,
+ settledTabId,
params.channelId,
params.dashboardId,
- params.taskId,
routeChannelSection,
routeAppView,
- openOrFocus.mutateAsync,
- setTabTarget.mutateAsync,
- setActiveTab.mutateAsync,
+ locationHref,
+ activeSession.taskId,
+ activeSession.channelId,
+ routeTitle,
+ railPane,
+ listOpen,
+ scopedSpaceId,
+ client,
router,
]);
- const channelName = useMemo(() => {
- const map = new Map(channels.map((c) => [c.id, c.name]));
- return (id: string | null) => (id ? (map.get(id) ?? null) : null);
- }, [channels]);
-
const tabs: TabView[] = useMemo(() => {
if (!windowId) return [];
// Reference the reactive sources directly so labels recompute the instant a
@@ -482,9 +524,11 @@ export function BrowserTabStrip() {
// 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 ? (params.taskId ?? null) : t.taskId;
+ const taskId = isActive ? (activeSession.taskId ?? null) : t.taskId;
const dashId = isActive ? (params.dashboardId ?? null) : t.dashboardId;
- const channelId = isActive ? (params.channelId ?? null) : t.channelId;
+ 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);
@@ -492,8 +536,14 @@ export function BrowserTabStrip() {
const task = findTask(taskId);
return {
id: t.id,
- label: task?.title ?? taskInfo.get(taskId) ?? "Task",
- icon: <TaskTabIcon task={task} size={14} />,
+ 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,
};
@@ -502,7 +552,7 @@ export function BrowserTabStrip() {
const info = resolveCanvas(dashId);
return {
id: t.id,
- label: info?.name ?? "Canvas",
+ label: info?.name ?? t.viewState?.title ?? "Canvas",
icon: iconForTemplate(info?.templateId ?? "freeform", {
size: 14,
}),
@@ -518,7 +568,10 @@ export function BrowserTabStrip() {
return {
id: t.id,
label:
- meta?.label ?? channel ?? (spacesLayout ? "Space" : "Channel"),
+ meta?.label ??
+ channel ??
+ t.viewState?.title ??
+ (spacesLayout ? "Space" : "Channel"),
icon: channelGlyph(channel ?? undefined, {
size: 14,
space: spacesLayout,
@@ -530,16 +583,21 @@ export function BrowserTabStrip() {
};
}
// A top-level app page (Inbox, Agents, Skills, …).
- if (appView && isAppView(appView)) {
+ if (appView && isTabAppView(appView)) {
return {
id: t.id,
- label: APP_VIEW_META[appView].label,
- icon: APP_VIEW_META[appView].icon,
+ label: TAB_APP_VIEW_META[appView].label,
+ icon: TAB_APP_VIEW_META[appView].icon,
channelName: null,
pinned,
};
}
- return { id: t.id, label: "New tab", channelName: null, pinned };
+ return {
+ id: t.id,
+ label: t.viewState?.title ?? "New tab",
+ channelName: null,
+ pinned,
+ };
});
}, [
snapshot,
@@ -554,94 +612,128 @@ export function BrowserTabStrip() {
activeTabId,
params.channelId,
params.dashboardId,
- params.taskId,
+ activeSession.taskId,
+ activeSession.channelId,
routeChannelSection,
routeAppView,
spacesLayout,
]);
// Navigate to a tab, tagging the history entry with its id so the switch is
- // replayable by back/forward. A canvas/task tab goes to its route; a blank tab
- // pushes a plain entry (the empty placeholder renders from the active tab).
- const goToTab = (tab: TabRef) => {
- const state = (prev: object) => ({ ...prev, tabId: tab.id });
- 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) {
+ // replayable by back/forward.
+ //
+ // The href is where the tab is, so it is what we go back to: it is the only
+ // thing that carries search params, and the only thing that covers routes
+ // outside the label cache's vocabulary. Rebuilding a canonical route from
+ // that cache instead sent every such tab (a loop, an archived list, a space's
+ // canvases) to the fallback below on every switch.
+ //
+ // 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/${section.key}` as const,
- params,
+ to: "/spaces/$channelId/tasks/$taskId",
+ params: { channelId: tab.channelId, taskId: tab.taskId },
state,
});
- } else {
- navigate({ to: "/spaces/$channelId", params, state });
- }
- } else if (tab.appView && isAppView(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 "inbox":
- navigate({ to: "/inbox", state });
- break;
- case "agents":
- navigate({ to: "/agents", 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;
- 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 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":
+ navigate({ to: "/", state });
+ break;
+ case "inbox":
+ navigate({ to: "/inbox", state });
+ break;
+ case "agents":
+ navigate({ to: "/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 {
+ // Blank / landing tab: park on the space's home — the channels index, or
+ // the Code new-task screen.
+ navigate({ to: inChannels ? "/spaces" : "/new", state });
}
- } else {
- // Blank / landing tab: park on the space's home — the channels index, or
- // the Code new-task screen.
- navigate({ to: inChannels ? "/spaces" : "/new", state });
- }
- };
+ },
+ [inChannels, navigate, router.history],
+ );
- const handleSelect = (tabId: string) => {
- const tab = snapshot.tabs.find((t) => t.id === tabId);
- if (!tab || !windowId) return;
- // goToTab stamps historyTabId; the navigation effect picks it up and issues
- // setActiveTab via the "activate" path — no need to also fire it here.
- goToTab(tab);
- };
+ const handleSelect = useCallback(
+ (tabId: string) => {
+ if (!windowId) return;
+ const target = readMirror().tabs.find(
+ (tab) => tab.windowId === windowId && tab.id === tabId,
+ );
+ if (target) goToTab(target);
+ },
+ [goToTab, windowId],
+ );
// Navigate to the close's survivor, or — when the last tab was closed — to the
// flag's default landing (#me / new-task), never the /website index (which
@@ -659,9 +751,12 @@ export function BrowserTabStrip() {
// /website index therefore always renders against the post-close snapshot
// and can't redirect (re-opening a tab) mid-flight.
const handleClose = (tabId: string) => {
+ useDraftStore
+ .getState()
+ .actions.setDraft(getTaskInputSessionId(tabId), null);
const next = applyLocalTransform((s) => closeTabLocal(s, tabId).snapshot);
applyCloseResult(next);
- void persistWrite(() => close.mutateAsync({ tabId }));
+ void persistWrite(() => client.close(tabId));
};
// Unpinning re-homes the tab at the front of the unpinned block. Apply the
@@ -673,7 +768,7 @@ export function BrowserTabStrip() {
if (!wasPinned || !windowId) return;
const order = frontOfUnpinnedOrder(snapshot, windowId, tabId, pinnedTabIds);
applyLocalTransform((s) => setTabOrder(s, windowId, order));
- void persistWrite(() => setOrder.mutateAsync({ windowId, tabIds: order }));
+ void persistWrite(() => client.setOrder({ windowId, tabIds: order }));
};
// Bulk closes operate on the strip's *displayed* order (pinned-first) and
@@ -681,12 +776,16 @@ export function BrowserTabStrip() {
// always survives) takes focus if the active tab was among those closed.
const handleCloseMany = (tabIds: string[], anchorTabId: string) => {
if (tabIds.length === 0) return;
+ const draftActions = useDraftStore.getState().actions;
+ for (const tabId of tabIds) {
+ draftActions.setDraft(getTaskInputSessionId(tabId), null);
+ }
const next = applyLocalTransform((s) =>
closeTabsLocal(s, tabIds, anchorTabId),
);
applyCloseResult(next);
void persistWrite(() =>
- closeMany.mutateAsync({ tabIds, focusTabId: anchorTabId }),
+ client.closeMany({ tabIds, focusTabId: anchorTabId }),
);
};
@@ -721,11 +820,10 @@ export function BrowserTabStrip() {
);
};
- // The default landing, keyed off the channels toggle (not the current route,
- // which lags a toggle flip): #me when channels are on, the Code new-task
- // screen otherwise. Deliberately never routes through the /website index,
- // which would redirect to channels[0]. `tabId` (a fresh blank tab) fills that
- // tab in place; without one (last tab closed) the navigation opens a new tab.
+ // Where closing the last tab lands, keyed off the channels toggle (not the
+ // current route, which lags a toggle flip): #me when channels are on, the
+ // Code new-task screen otherwise. The navigation opens a fresh tab, since by
+ // then the window has none.
const landOnDefault = (tabId?: string) => {
const state = tabId ? (prev: object) => ({ ...prev, tabId }) : undefined;
if (!channelsEnabled) {
@@ -746,55 +844,13 @@ export function BrowserTabStrip() {
}
};
- // New tab is fully local: mint the id here, append the blank tab to the
- // mirror and navigate in the same tick (no IPC wait), then persist with the
- // same id so the durable state matches. The service is idempotent on the
- // minted id, so a replay can't append a duplicate.
- const createBlankTab = (targetWindowId: string) => {
- const tabId = crypto.randomUUID();
- applyLocalTransform(
- (s) =>
- newBlankTabLocal(s, {
- windowId: targetWindowId,
- makeId: () => tabId,
- now: Date.now,
- }).snapshot,
- );
- landOnDefault(tabId);
- void persistWrite(() =>
- newBlankTab.mutateAsync({ windowId: targetWindowId, tabId }),
- );
- };
+ // Where `+` lands. The space index is the app's "pick something" screen, so
+ // a new tab shows the spaces rather than an empty placeholder. Without the
+ // spaces layout that page does not exist, so the Code new-task screen stands
+ // in. Keyed off the channels toggle, not the current route, which lags a flip.
+ const newTabHref = channelsEnabled ? "/spaces" : "/new";
- const handleNewTab = () => {
- if (windowId) {
- createBlankTab(windowId);
- return;
- }
- // No window means the mirror never seeded (the boot fetch raced or
- // failed) — the click must not die. Re-pull the authoritative snapshot
- // (the server always has a primary window) and append into it. Resolve
- // the window from the FETCHED snapshot, not the mirror: reseedMirror
- // skips the store apply when a local write or newer remote push raced
- // the fetch, and the mirror could still be windowless then.
- void reseedMirror()
- .then((server) => {
- const win = server
- ? primaryWindow(server)
- : primaryWindow(readMirror());
- if (win) {
- createBlankTab(win.id);
- return;
- }
- // Should be unreachable (the server always mints a primary window),
- // but a silent skip here reproduces the dead-"+" this path exists to
- // fix — make it loud instead.
- logger.error("browser-tabs: new-tab found no window after reseed");
- })
- .catch((error) => {
- logger.error("browser-tabs: new-tab reseed failed", { error });
- });
- };
+ const handleNewTab = () => openBrowserTab(newTabHref);
// Cmd/Ctrl+T opens a new browser tab. Bound here (not globally) so it only
// fires where the strip is mounted; the new-task shortcut owns Cmd/Ctrl+N.
@@ -807,10 +863,33 @@ export function BrowserTabStrip() {
{
enableOnFormTags: true,
enableOnContentEditable: true,
- enabled: !isCloudRun,
},
);
+ // Cmd/Ctrl+1-9 switches tabs, the browser way: 1-8 pick that position in the
+ // strip, 9 picks the last tab however many there are. Reads the DISPLAYED
+ // (pinned-first) order, so the key matches what you are counting on screen.
+ //
+ // Owned by the strip wherever it is mounted, so a press has one local-first
+ // path. On macOS, pure ctrl stays with the task editor's inner tab switcher.
+ useHotkeys(
+ SHORTCUTS.SWITCH_BROWSER_TAB,
+ (event, handler) => {
+ if (!shouldHandleBrowserTabSwitch(event, isMac)) return;
+ const slot = Number.parseInt(handler.keys?.[0] ?? "", 10);
+ if (Number.isNaN(slot) || tabs.length === 0) return;
+ const tab = slot === 9 ? tabs[tabs.length - 1] : tabs[slot - 1];
+ if (!tab) return;
+ handleSelect(tab.id);
+ },
+ {
+ enableOnFormTags: true,
+ enableOnContentEditable: true,
+ preventDefault: true,
+ },
+ [tabs, handleSelect],
+ );
+
// Cmd/Ctrl+W closes the active browser tab. Always preventDefault so Electron
// doesn't close the window, but defer to the task's editor panel when it has a
// closeable tab (inner-first) — that handler closes the editor tab instead.
@@ -824,29 +903,6 @@ export function BrowserTabStrip() {
{ enableOnFormTags: true, enableOnContentEditable: true },
);
- // With channels on, Cmd/Ctrl+1-9 switches to the Nth browser tab (in the
- // displayed, pinned-first order) instead of the Nth sidebar task. The global
- // task-switch handler yields via the same channelsEnabled gate, so exactly one
- // owner fires. Mirror its pure-ctrl guard: ctrl+1-9 is the editor-panel tab
- // switcher (SWITCH_TAB), so leave ctrl-only presses to it.
- useHotkeys(
- SHORTCUTS.SWITCH_TASK,
- (event, handler) => {
- if (event.ctrlKey && !event.metaKey) return;
- const key = handler.keys?.[0];
- if (!key) return;
- const tab = tabs[Number.parseInt(key, 10) - 1];
- if (tab) handleSelect(tab.id);
- },
- {
- enableOnFormTags: true,
- enableOnContentEditable: true,
- preventDefault: true,
- enabled: channelsEnabled,
- },
- [tabs, handleSelect],
- );
-
return (
<TabStrip
tabs={tabs}
@@ -857,7 +913,7 @@ export function BrowserTabStrip() {
onCloseOthers={handleCloseOthers}
onCloseToRight={handleCloseToRight}
onCloseToLeft={handleCloseToLeft}
- onNewTab={isCloudRun ? undefined : handleNewTab}
+ 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.tsx
index 810523c7c63d..a014e5d39a2a 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabsDnd.tsx
+++ b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabsDnd.tsx
@@ -1,9 +1,12 @@
import { type DragDropEvents, DragDropProvider } from "@dnd-kit/react";
import { browserTabsStore } from "@posthog/core/browser-tabs/browserTabsStore";
-import { useHostTRPC } from "@posthog/host-router/react";
+import { useService } from "@posthog/di/react";
import { primaryWindow, setTabOrder } from "@posthog/shared";
-import { useMutation } from "@tanstack/react-query";
import { type ReactNode, useRef } from "react";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "./browserTabsClient";
import { reorderWithinGroup, storedOrderIds } from "./displayOrder";
import { usePinnedTabsStore } from "./pinnedTabsStore";
import { useTabReorderStore } from "./tabReorderStore";
@@ -28,8 +31,7 @@ function sameOrder(a: string[], b: string[]): boolean {
* drops the preview.
*/
export function BrowserTabsDndProvider({ children }: { children: ReactNode }) {
- const trpc = useHostTRPC();
- const setOrder = useMutation(trpc.browserTabs.setOrder.mutationOptions());
+ const client = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);
/** Stored order captured at dragstart — used to skip a no-op persist. */
const initialOrder = useRef<string[] | null>(null);
@@ -92,7 +94,7 @@ export function BrowserTabsDndProvider({ children }: { children: ReactNode }) {
// rewind a newer write.
applyLocalTransform((s) => setTabOrder(s, win.id, order));
void persistWrite(() =>
- setOrder.mutateAsync({ windowId: win.id, tabIds: order }),
+ client.setOrder({ windowId: win.id, tabIds: order }),
);
});
};
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.tsx b/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.tsx
index 1a89f5c3ce63..31d2b72e49b7 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.tsx
+++ b/products/desktop/packages/ui/src/features/browser-tabs/TabStrip.tsx
@@ -19,7 +19,7 @@ import type { ReactNode } from "react";
export interface TabView {
id: string;
label: string;
- /** Optional leading icon (template-derived). */
+ /** Optional leading icon (template-derived, or a session's status dot). */
icon?: ReactNode;
/** Channel the tab belongs to; shown `#`-prefixed atop the hover. Null = no
* channel (a blank tab). */
@@ -42,8 +42,9 @@ export interface TabStripProps {
activeTabId: string | null;
onSelect: (tabId: string) => void;
onClose: (tabId: string) => void;
- /** When omitted, the trailing new-tab button is hidden (e.g. on read-only
- * cloud runs, where opening a tab makes no sense). */
+ /** When omitted, the trailing new-tab button is hidden. The app always passes
+ * it: `+` opens the space index, which has nothing to do with what the
+ * current tab is showing. */
onNewTab?: () => void;
onTogglePin: (tabId: string) => void;
onCloseOthers: (tabId: string) => void;
@@ -229,7 +230,14 @@ function SortableTabPill({
<ContextMenu>
<Tooltip>
<TooltipTrigger render={<ContextMenuTrigger render={pill} />} />
- <TooltipContent side="bottom">
+ {/* `flex-col items-start`: TooltipContent is a centred ROW by default,
+ which laid the two lines side by side and wrapped both. They stack,
+ and each stays on one line — a tooltip that exists to show a
+ truncated name must not truncate it again by wrapping. */}
+ <TooltipContent
+ side="bottom"
+ className="flex-col items-start gap-0 whitespace-nowrap"
+ >
{/* Channel context first (always `#`-prefixed); the channel-home tab
reads `#channel / home`. Then the page name, unless it would just
repeat the channel-home name already shown above. */}
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/TaskTabMarks.tsx b/products/desktop/packages/ui/src/features/browser-tabs/TaskTabMarks.tsx
new file mode 100644
index 000000000000..22cdbaa0526e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/TaskTabMarks.tsx
@@ -0,0 +1,17 @@
+import type { Task } from "@posthog/shared/domain-types";
+import { useTaskStatusInput } from "@posthog/ui/features/canvas/hooks/useChannelTaskStatus";
+import { TaskStatusDot } from "@posthog/ui/features/sidebar/components/items/TaskStatusDot";
+import { taskDot } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";
+
+/**
+ * A session tab wears the session list's status dot. Same vocabulary as the row
+ * it came from, so a tab and its list entry never say different things about
+ * the same session.
+ */
+export function TaskTabDot({ task }: { task: Task | undefined }) {
+ const status = useTaskStatusInput(task);
+ // No run to report yet (the task or its data hasn't landed). The dot's own
+ // resting state already reads as "nothing happening", so it stands in rather
+ // than a second placeholder glyph that would shift when the real one arrives.
+ return <TaskStatusDot dot={taskDot(status ?? {})} />;
+}
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/browser-tabs-events.contribution.ts b/products/desktop/packages/ui/src/features/browser-tabs/browser-tabs-events.contribution.ts
index 85216c5b749b..b22229ff704f 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/browser-tabs-events.contribution.ts
+++ b/products/desktop/packages/ui/src/features/browser-tabs/browser-tabs-events.contribution.ts
@@ -6,7 +6,11 @@ import {
BROWSER_TABS_CLIENT,
type BrowserTabsClient,
} from "./browserTabsClient";
-import { applyRemoteSnapshot, registerSnapshotFetcher } from "./tabsSync";
+import {
+ applyRemoteSnapshot,
+ registerSnapshotFetcher,
+ registerTabTargetWriter,
+} from "./tabsSync";
const SEED_ATTEMPTS = 3;
const SEED_RETRY_BASE_MS = 1_000;
@@ -37,6 +41,7 @@ export class BrowserTabsEventsContribution implements Contribution {
// Lets tabsSync re-pull the authoritative snapshot after a FAILED write
// (a failed mutation emits no snapshotChange, so nothing else reconciles).
registerSnapshotFetcher(() => this.client.getSnapshot());
+ registerTabTargetWriter((input) => this.client.setTabTarget(input));
// Abort any prior loop so a repeated start() can't stack a second one
// (mirrors the subscription replacement below).
@@ -83,6 +88,7 @@ export class BrowserTabsEventsContribution implements Contribution {
this.seedAbort?.abort();
this.seedAbort = null;
registerSnapshotFetcher(null);
+ registerTabTargetWriter(null);
this.subscription?.unsubscribe();
this.subscription = null;
}
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/browserTabShortcuts.test.ts b/products/desktop/packages/ui/src/features/browser-tabs/browserTabShortcuts.test.ts
new file mode 100644
index 000000000000..fb787fb1a1ef
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/browserTabShortcuts.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "vitest";
+import { shouldHandleBrowserTabSwitch } from "./browserTabShortcuts";
+
+describe("shouldHandleBrowserTabSwitch", () => {
+ it("leaves Ctrl+digit to inner task tabs on macOS", () => {
+ expect(
+ shouldHandleBrowserTabSwitch({ ctrlKey: true, metaKey: false }, true),
+ ).toBe(false);
+ });
+
+ it("handles Ctrl+digit as the browser shortcut off macOS", () => {
+ expect(
+ shouldHandleBrowserTabSwitch({ ctrlKey: true, metaKey: false }, false),
+ ).toBe(true);
+ });
+
+ it("handles Cmd+digit on macOS", () => {
+ expect(
+ shouldHandleBrowserTabSwitch({ ctrlKey: false, metaKey: true }, true),
+ ).toBe(true);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/browserTabShortcuts.ts b/products/desktop/packages/ui/src/features/browser-tabs/browserTabShortcuts.ts
new file mode 100644
index 000000000000..28a55c0ae0dc
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/browserTabShortcuts.ts
@@ -0,0 +1,6 @@
+export function shouldHandleBrowserTabSwitch(
+ event: Pick<KeyboardEvent, "ctrlKey" | "metaKey">,
+ macPlatform: boolean,
+): boolean {
+ return !macPlatform || !event.ctrlKey || event.metaKey;
+}
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/browserTabsClient.ts b/products/desktop/packages/ui/src/features/browser-tabs/browserTabsClient.ts
index eaf4df383dbd..5e60f572e5f8 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/browserTabsClient.ts
+++ b/products/desktop/packages/ui/src/features/browser-tabs/browserTabsClient.ts
@@ -1,4 +1,7 @@
-import type { TabsSnapshot } from "@posthog/shared";
+import type { TabIdentity, TabLocation, TabsSnapshot } from "@posthog/shared";
+
+/** Where a tab is, plus the route-derived label/icon cache. */
+type TabLocationInput = TabLocation & TabIdentity;
interface Subscriber<T> {
onData: (data: T) => void;
@@ -14,30 +17,27 @@ interface Subscriber<T> {
export interface BrowserTabsClient {
getSnapshot(): Promise<TabsSnapshot>;
getPrimaryWindowId(): Promise<string>;
- openOrFocus(input: {
- windowId: string;
- dashboardId: string | null;
- taskId: string | null;
- channelId: string | null;
- channelSection?: string | null;
- appView?: string | null;
- /** Renderer-minted id for a tab this call may create (local-first sync). */
- tabId?: string;
+ /** Clear auth-scoped locations and seed a fresh tab in every window. */
+ reset(): Promise<TabsSnapshot>;
+ openTab(
+ input: TabLocationInput & {
+ windowId: string;
+ /** Renderer-minted id for the tab this call creates (local-first sync). */
+ tabId?: string;
+ },
+ ): Promise<TabsSnapshot>;
+ setTabTarget(
+ input: TabLocationInput & { tabId: string; activate?: boolean },
+ ): Promise<TabsSnapshot>;
+ close(tabId: string): Promise<TabsSnapshot>;
+ closeMany(input: {
+ tabIds: string[];
+ focusTabId?: string | null;
}): Promise<TabsSnapshot>;
- newBlankTab(input: {
+ setOrder(input: {
windowId: string;
- /** Renderer-minted id (see openOrFocus.tabId). */
- tabId?: string;
+ tabIds: string[];
}): Promise<TabsSnapshot>;
- setTabTarget(input: {
- tabId: string;
- dashboardId: string | null;
- taskId: string | null;
- channelId: string | null;
- channelSection?: string | null;
- appView?: string | null;
- }): Promise<TabsSnapshot>;
- close(tabId: string): Promise<TabsSnapshot>;
setActiveTab(input: {
windowId: string;
tabId: string | null;
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/displayOrder.test.ts b/products/desktop/packages/ui/src/features/browser-tabs/displayOrder.test.ts
index 5ac2c002492d..436efa42e9a9 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
@@ -12,6 +12,8 @@ function tab(id: string, position: number): BrowserTab {
return {
id,
windowId: "w1",
+ href: null,
+ viewState: null,
dashboardId: null,
taskId: null,
channelId: null,
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.test.ts b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.test.ts
new file mode 100644
index 000000000000..fd3bab4b9da5
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.test.ts
@@ -0,0 +1,138 @@
+import type { TabsSnapshot } from "@posthog/shared";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ getCurrentBrowserTabId,
+ navigateBrowserTab,
+} from "./imperativeTabNavigation";
+
+const mocks = vi.hoisted(() => ({
+ getRouterOrNull: vi.fn(),
+ applyLocalTransform: vi.fn(),
+ persistTabTarget: vi.fn(),
+ readMirror: vi.fn(),
+ setTabTarget: vi.fn(),
+}));
+
+vi.mock("@posthog/ui/router/routerRef", () => ({
+ getRouterOrNull: mocks.getRouterOrNull,
+}));
+vi.mock("./tabsSync", () => ({
+ applyLocalTransform: mocks.applyLocalTransform,
+ persistTabTarget: mocks.persistTabTarget,
+ readMirror: mocks.readMirror,
+}));
+vi.mock("@posthog/shared", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@posthog/shared")>();
+ return { ...actual, setTabTarget: mocks.setTabTarget };
+});
+
+const destination = {
+ href: "/tasks/task-1",
+ title: "Created task",
+ dashboardId: null,
+ taskId: "task-1",
+ channelId: null,
+ channelSection: null,
+ appView: null,
+};
+
+function snapshot(): TabsSnapshot {
+ return {
+ windows: [
+ {
+ id: "window-1",
+ isPrimary: true,
+ bounds: null,
+ activeTabId: "tab-b",
+ },
+ ],
+ tabs: [
+ {
+ id: "tab-a",
+ windowId: "window-1",
+ href: "/new",
+ viewState: { title: "New task" },
+ dashboardId: null,
+ taskId: null,
+ channelId: null,
+ channelSection: null,
+ appView: null,
+ position: 1000,
+ scrollState: null,
+ createdAt: 1,
+ lastActiveAt: 1,
+ },
+ {
+ id: "tab-b",
+ windowId: "window-1",
+ href: "/inbox",
+ viewState: { title: "Inbox" },
+ dashboardId: null,
+ taskId: null,
+ channelId: null,
+ channelSection: null,
+ appView: "inbox",
+ position: 2000,
+ scrollState: null,
+ createdAt: 2,
+ lastActiveAt: 2,
+ },
+ ],
+ };
+}
+
+describe("imperative browser-tab navigation", () => {
+ const history = { location: { state: { tabId: "tab-b" } } };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ history.location.state.tabId = "tab-b";
+ mocks.getRouterOrNull.mockReturnValue({ history });
+ mocks.readMirror.mockReturnValue(snapshot());
+ mocks.applyLocalTransform.mockImplementation((transform) =>
+ transform(snapshot()),
+ );
+ mocks.setTabTarget.mockImplementation((state) => state);
+ });
+
+ it("reads the tab attached to the current history entry", () => {
+ expect(getCurrentBrowserTabId()).toBe("tab-b");
+ });
+
+ it("uses ordinary navigation when the originating tab is still active", () => {
+ history.location.state.tabId = "tab-a";
+ const fallback = vi.fn();
+
+ expect(navigateBrowserTab("tab-a", destination, fallback)).toBe("active");
+ expect(fallback).toHaveBeenCalledOnce();
+ expect(mocks.applyLocalTransform).not.toHaveBeenCalled();
+ });
+
+ it("retargets an inactive origin without activating it", () => {
+ const fallback = vi.fn();
+
+ expect(navigateBrowserTab("tab-a", destination, fallback)).toBe(
+ "background",
+ );
+ expect(mocks.setTabTarget).toHaveBeenCalledWith(
+ expect.any(Object),
+ expect.objectContaining({
+ tabId: "tab-a",
+ href: destination.href,
+ taskId: "task-1",
+ activate: false,
+ }),
+ );
+ expect(mocks.persistTabTarget).toHaveBeenCalledWith(
+ expect.objectContaining({ tabId: "tab-a", activate: false }),
+ );
+ expect(fallback).not.toHaveBeenCalled();
+ });
+
+ it("uses ordinary navigation when browser tabs are unavailable", () => {
+ const fallback = vi.fn();
+
+ expect(navigateBrowserTab(null, destination, fallback)).toBe("active");
+ expect(fallback).toHaveBeenCalledOnce();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts
new file mode 100644
index 000000000000..221116e22ae3
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts
@@ -0,0 +1,64 @@
+import {
+ setTabTarget as setTabTargetLocal,
+ type TabIdentity,
+} from "@posthog/shared";
+import { getRouterOrNull } from "@posthog/ui/router/routerRef";
+import { applyLocalTransform, persistTabTarget, readMirror } from "./tabsSync";
+
+export interface BrowserTabDestination extends Partial<TabIdentity> {
+ href: string;
+ title?: string;
+}
+
+export type BrowserTabNavigationResult = "active" | "background" | "closed";
+
+/** The tab attached to the current history entry, or null when tabs are off. */
+export function getCurrentBrowserTabId(): string | null {
+ return getRouterOrNull()?.history.location.state.tabId ?? null;
+}
+
+/**
+ * Move one browser tab to a new route without stealing focus from another tab.
+ * Active tabs use router history; background tabs update their durable target
+ * and will load that route when the user returns.
+ */
+export function navigateBrowserTab(
+ tabId: string | null,
+ destination: BrowserTabDestination,
+ navigateActiveTab: () => void,
+): BrowserTabNavigationResult {
+ if (!tabId) {
+ navigateActiveTab();
+ return "active";
+ }
+
+ const router = getRouterOrNull();
+ if (router?.history.location.state.tabId === tabId) {
+ navigateActiveTab();
+ return "active";
+ }
+
+ 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);
+ return "background";
+}
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/settledLocation.test.ts b/products/desktop/packages/ui/src/features/browser-tabs/settledLocation.test.ts
new file mode 100644
index 000000000000..77e8b16931a6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/settledLocation.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import { settledLocation } from "./settledLocation";
+
+describe("settledLocation", () => {
+ // The regression: a tab switch tags the new entry immediately while the
+ // navigation is still pending, so `location` says the destination and
+ // `resolvedLocation` still says the page being left. Pairing across the two
+ // hands the effect "tab B, on tab A's href", which it writes to tab B.
+ it("pairs the href and the tab tag from the same snapshot mid-navigation", () => {
+ expect(
+ settledLocation({
+ location: { href: "/spaces/b", state: { tabId: "tab-b" } },
+ resolvedLocation: { href: "/spaces/a", state: { tabId: "tab-a" } },
+ }),
+ ).toEqual({ href: "/spaces/a", tabId: "tab-a", isCurrent: false });
+ });
+
+ it("stays pending when only the tab owner changes", () => {
+ expect(
+ settledLocation({
+ location: { href: "/spaces", state: { tabId: "tab-b" } },
+ resolvedLocation: { href: "/spaces", state: { tabId: "tab-a" } },
+ }),
+ ).toEqual({ href: "/spaces", tabId: "tab-a", isCurrent: false });
+ });
+
+ it("reads the settled entry once the navigation lands", () => {
+ expect(
+ settledLocation({
+ location: { href: "/spaces/b", state: { tabId: "tab-b" } },
+ resolvedLocation: { href: "/spaces/b", state: { tabId: "tab-b" } },
+ }),
+ ).toEqual({ href: "/spaces/b", tabId: "tab-b", isCurrent: true });
+ });
+
+ it("falls back to the location before anything has resolved", () => {
+ expect(
+ settledLocation({
+ location: { href: "/spaces", state: {} },
+ }),
+ ).toEqual({ href: "/spaces", tabId: null, isCurrent: true });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/settledLocation.ts b/products/desktop/packages/ui/src/features/browser-tabs/settledLocation.ts
new file mode 100644
index 000000000000..bdae783f8f4e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/settledLocation.ts
@@ -0,0 +1,40 @@
+/**
+ * The location the strip reconciles against, and the tab that entry belongs to,
+ * **read from one snapshot**.
+ *
+ * During a pending navigation the router's `location` is already the
+ * destination while `resolvedLocation` (and `matches`, and so `params`) still
+ * describe the page being left. Taking the href from one and the tab tag from
+ * the other pairs a tab with a location it was never on, and the strip's effect
+ * then writes that location onto it — the "switching tabs rewrites another
+ * tab's URL" corruption.
+ *
+ * Reading both off the settled snapshot keeps the pair coherent. `isCurrent`
+ * additionally tells the effect not to act until that settled pair matches the
+ * in-flight entry's href and tab owner. The in-flight `location` still drives
+ * the strip's *highlight*, which wants to flip the instant you navigate; that
+ * is a render, not a write.
+ */
+export interface RouterSnapshot {
+ location: { href: string; state: { tabId?: string } };
+ resolvedLocation?: { href: string; state: { tabId?: string } };
+}
+
+export interface SettledLocation {
+ href: string;
+ tabId: string | null;
+ isCurrent: boolean;
+}
+
+export function settledLocation(state: RouterSnapshot): SettledLocation {
+ const loc = state.resolvedLocation ?? state.location;
+ const tabId = loc.state.tabId ?? null;
+ const currentTabId = state.location.state.tabId ?? null;
+ return {
+ href: loc.href,
+ tabId,
+ isCurrent:
+ !state.resolvedLocation ||
+ (state.location.href === loc.href && currentTabId === tabId),
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/tabAppViews.tsx b/products/desktop/packages/ui/src/features/browser-tabs/tabAppViews.tsx
new file mode 100644
index 000000000000..97b346aaf2f6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/tabAppViews.tsx
@@ -0,0 +1,59 @@
+import {
+ ArchiveIcon,
+ BookOpenTextIcon,
+ BrainIcon,
+ ClockCounterClockwiseIcon,
+ GearIcon,
+ PlugsConnectedIcon,
+ RepeatIcon,
+ RobotIcon,
+ SquaresFourIcon,
+ TrayIcon,
+} from "@phosphor-icons/react";
+import type { AppViewType } from "@posthog/ui/router/useAppView";
+import type { ReactNode } from "react";
+
+export type TabAppView = Extract<
+ AppViewType,
+ | "activity"
+ | "home"
+ | "inbox"
+ | "agents"
+ | "loops"
+ | "archived"
+ | "command-center"
+ | "context"
+ | "skills"
+ | "mcp-servers"
+ | "settings"
+>;
+
+export const TAB_APP_VIEW_META: Record<
+ TabAppView,
+ { label: string; icon: ReactNode }
+> = {
+ activity: {
+ label: "Activity",
+ icon: <ClockCounterClockwiseIcon size={14} />,
+ },
+ home: { label: "Home", icon: <SquaresFourIcon size={14} /> },
+ inbox: { label: "Inbox", icon: <TrayIcon size={14} /> },
+ agents: { label: "Agents", icon: <RobotIcon size={14} /> },
+ loops: { label: "Loops", icon: <RepeatIcon size={14} /> },
+ archived: { label: "Archived", icon: <ArchiveIcon size={14} /> },
+ skills: { label: "Skills", icon: <BrainIcon size={14} /> },
+ "mcp-servers": {
+ label: "MCP servers",
+ icon: <PlugsConnectedIcon size={14} />,
+ },
+ "command-center": {
+ label: "Command center",
+ icon: <SquaresFourIcon size={14} />,
+ },
+ context: { label: "Context", icon: <BookOpenTextIcon size={14} /> },
+ settings: { label: "Settings", icon: <GearIcon size={14} /> },
+};
+
+export function isTabAppView(value: string): value is TabAppView {
+ return Object.hasOwn(TAB_APP_VIEW_META, value);
+}
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/tabHistory.test.ts b/products/desktop/packages/ui/src/features/browser-tabs/tabHistory.test.ts
new file mode 100644
index 000000000000..aa813a9b1453
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/tabHistory.test.ts
@@ -0,0 +1,16 @@
+import { createMemoryHistory } from "@tanstack/react-router";
+import { describe, expect, it } from "vitest";
+import { pushTabHistoryEntry } from "./tabHistory";
+
+describe("pushTabHistoryEntry", () => {
+ it("selects a different tab even when both tabs have the same href", () => {
+ const history = createMemoryHistory({ initialEntries: ["/inbox"] });
+ pushTabHistoryEntry(history, "/inbox", "tab-a");
+
+ pushTabHistoryEntry(history, "/inbox", "tab-b");
+
+ expect(history.location.href).toBe("/inbox");
+ expect(history.location.state.tabId).toBe("tab-b");
+ expect(history.length).toBe(3);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/tabHistory.ts b/products/desktop/packages/ui/src/features/browser-tabs/tabHistory.ts
new file mode 100644
index 000000000000..92a47a08c1fd
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/tabHistory.ts
@@ -0,0 +1,20 @@
+import type { RouterHistory } from "@tanstack/react-router";
+
+declare module "@tanstack/history" {
+ interface HistoryState {
+ tabId?: string;
+ }
+}
+
+/**
+ * Select a tab by identity, even when it has the same href as the active tab.
+ * Router-level navigate may collapse a same-href navigation and retain the old
+ * tabId, which makes two tabs showing the same page impossible to select.
+ */
+export function pushTabHistoryEntry(
+ history: RouterHistory,
+ href: string,
+ tabId: string,
+): void {
+ history.push(href, { ...history.location.state, tabId });
+}
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/tabsSync.test.ts b/products/desktop/packages/ui/src/features/browser-tabs/tabsSync.test.ts
index a5a90a96f7eb..62b2020fde85 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/tabsSync.test.ts
+++ b/products/desktop/packages/ui/src/features/browser-tabs/tabsSync.test.ts
@@ -21,6 +21,8 @@ function snap(tabIds: string[]): TabsSnapshot {
tabs: tabIds.map((id, i) => ({
id,
windowId: "w1",
+ href: null,
+ viewState: null,
dashboardId: null,
taskId: null,
channelId: `c-${id}`,
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/tabsSync.ts b/products/desktop/packages/ui/src/features/browser-tabs/tabsSync.ts
index fd2d65cbbf6c..a6b7c0462a24 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/tabsSync.ts
+++ b/products/desktop/packages/ui/src/features/browser-tabs/tabsSync.ts
@@ -1,5 +1,6 @@
import { browserTabsStore } from "@posthog/core/browser-tabs/browserTabsStore";
import type { TabsSnapshot } from "@posthog/shared";
+import type { BrowserTabsClient } from "./browserTabsClient";
/**
* Local-first sync policy for the browser-tabs mirror.
@@ -29,6 +30,7 @@ let needsAuthoritativeReconcile = false;
// contribution (tabsSync can't reach the injected BrowserTabsClient itself).
// Used to reconcile after a failed write or a dropped remote snapshot.
let fetchAuthoritative: (() => Promise<TabsSnapshot>) | null = null;
+let writeTabTarget: BrowserTabsClient["setTabTarget"] | null = null;
export function registerSnapshotFetcher(
fetch: (() => Promise<TabsSnapshot>) | null,
@@ -36,6 +38,12 @@ export function registerSnapshotFetcher(
fetchAuthoritative = fetch;
}
+export function registerTabTargetWriter(
+ write: BrowserTabsClient["setTabTarget"] | null,
+): void {
+ writeTabTarget = write;
+}
+
function reconcileAuthoritative(): void {
void reseedMirror().catch(() => undefined);
}
@@ -107,6 +115,16 @@ export async function persistWrite(
}
}
+/** Persist an imperative background-tab navigation through the client supplied
+ * by the browser-tabs contribution at boot. */
+export function persistTabTarget(
+ input: Parameters<BrowserTabsClient["setTabTarget"]>[0],
+): void {
+ const write = writeTabTarget;
+ if (!write) return;
+ void persistWrite(() => write(input));
+}
+
/**
* Apply a snapshot pushed from the main process (boot seed, or a mutation made
* by another window). A push received during a local write is dropped and
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/useBrowserTabs.ts b/products/desktop/packages/ui/src/features/browser-tabs/useBrowserTabs.ts
index 003e79723133..8aeb50a3947a 100644
--- a/products/desktop/packages/ui/src/features/browser-tabs/useBrowserTabs.ts
+++ b/products/desktop/packages/ui/src/features/browser-tabs/useBrowserTabs.ts
@@ -1,5 +1,4 @@
import { browserTabsStore } from "@posthog/core/browser-tabs/browserTabsStore";
-import { activeTabIsBlank, primaryWindowHasNoTabs } from "@posthog/shared";
import { createSelectors } from "@posthog/ui/hooks/createSelectors";
const tabs = createSelectors(browserTabsStore);
@@ -8,19 +7,3 @@ const tabs = createSelectors(browserTabsStore);
export function useTabsSnapshot() {
return tabs.use.snapshot();
}
-
-/**
- * True when the primary window's active tab is a blank "+" tab (no canvas, task,
- * or channel). The root layout uses this to render the new-tab placeholder on
- * the `/spaces` index instead of the space list (`showBlankTab` in `__root`).
- */
-export function useActiveTabIsBlank(): boolean {
- return activeTabIsBlank(useTabsSnapshot());
-}
-
-/**
- * True when the primary window has no tabs at all — the user closed every tab.
- */
-export function usePrimaryWindowHasNoTabs(): boolean {
- return primaryWindowHasNoTabs(useTabsSnapshot());
-}
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/useOpenBrowserTab.test.tsx b/products/desktop/packages/ui/src/features/browser-tabs/useOpenBrowserTab.test.tsx
new file mode 100644
index 000000000000..5080df6427e8
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/useOpenBrowserTab.test.tsx
@@ -0,0 +1,80 @@
+import { browserTabsStore } from "@posthog/core/browser-tabs/browserTabsStore";
+import { createMemoryHistory } from "@tanstack/react-router";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ client: { openTab: vi.fn() },
+ logger: { error: vi.fn() },
+ history: null as ReturnType<typeof createMemoryHistory> | null,
+}));
+
+vi.mock("@posthog/di/react", () => ({
+ useService: (token: symbol) =>
+ String(token).includes("BrowserTabsClient") ? mocks.client : mocks.logger,
+}));
+vi.mock("@tanstack/react-router", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@tanstack/react-router")>();
+ return {
+ ...actual,
+ useRouter: () => ({ history: mocks.history }),
+ };
+});
+
+import { useOpenBrowserTab } from "./useOpenBrowserTab";
+
+describe("useOpenBrowserTab", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.history = createMemoryHistory({ initialEntries: ["/activity"] });
+ browserTabsStore.getState().setSnapshot({
+ windows: [
+ { id: "window-1", isPrimary: true, bounds: null, activeTabId: "tab-1" },
+ ],
+ tabs: [
+ {
+ id: "tab-1",
+ windowId: "window-1",
+ href: "/activity",
+ viewState: null,
+ dashboardId: null,
+ taskId: null,
+ channelId: null,
+ channelSection: null,
+ appView: "activity",
+ position: 1000,
+ scrollState: null,
+ createdAt: 1,
+ lastActiveAt: 1,
+ },
+ ],
+ });
+ mocks.client.openTab.mockImplementation(
+ async () => browserTabsStore.getState().snapshot,
+ );
+ });
+
+ it("opens and focuses independent tabs without changing the source tab", async () => {
+ const { result } = renderHook(() => useOpenBrowserTab());
+
+ act(() => {
+ result.current("/inbox");
+ result.current("/inbox");
+ });
+
+ const snapshot = browserTabsStore.getState().snapshot;
+ const inboxTabs = snapshot.tabs.filter((tab) => tab.href === "/inbox");
+ expect(snapshot.tabs.find((tab) => tab.id === "tab-1")?.href).toBe(
+ "/activity",
+ );
+ expect(inboxTabs).toHaveLength(2);
+ expect(inboxTabs[0].id).not.toBe(inboxTabs[1].id);
+ expect(snapshot.windows[0].activeTabId).toBe(inboxTabs[1].id);
+ expect(mocks.history?.location).toMatchObject({
+ href: "/inbox",
+ state: { tabId: inboxTabs[1].id },
+ });
+ await waitFor(() => expect(mocks.client.openTab).toHaveBeenCalledTimes(2));
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/browser-tabs/useOpenBrowserTab.ts b/products/desktop/packages/ui/src/features/browser-tabs/useOpenBrowserTab.ts
new file mode 100644
index 000000000000..1c253659a26f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/browser-tabs/useOpenBrowserTab.ts
@@ -0,0 +1,77 @@
+import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";
+import { useService } from "@posthog/di/react";
+import { openTab, primaryWindow } from "@posthog/shared";
+import {
+ BROWSER_TABS_CLIENT,
+ type BrowserTabsClient,
+} from "@posthog/ui/features/browser-tabs/browserTabsClient";
+import { useRouter } from "@tanstack/react-router";
+import { useCallback } from "react";
+import { pushTabHistoryEntry } from "./tabHistory";
+import {
+ applyLocalTransform,
+ persistWrite,
+ readMirror,
+ reseedMirror,
+} from "./tabsSync";
+
+export type OpenBrowserTab = (href: string) => void;
+
+/** Open and focus an independent tab without waiting for host persistence. */
+export function useOpenBrowserTab(): OpenBrowserTab {
+ const client = useService<BrowserTabsClient>(BROWSER_TABS_CLIENT);
+ const logger = useService<RootLogger>(ROOT_LOGGER);
+ const router = useRouter();
+
+ const openInWindow = useCallback(
+ (windowId: string, href: string): void => {
+ const tabId = crypto.randomUUID();
+ const input = {
+ windowId,
+ tabId,
+ href,
+ viewState: null,
+ dashboardId: null,
+ taskId: null,
+ channelId: null,
+ channelSection: null,
+ appView: null,
+ };
+ applyLocalTransform(
+ (snapshot) =>
+ openTab(snapshot, {
+ ...input,
+ makeId: () => tabId,
+ now: Date.now,
+ }).snapshot,
+ );
+ pushTabHistoryEntry(router.history, href, tabId);
+ void persistWrite(() => client.openTab(input));
+ },
+ [client, router.history],
+ );
+
+ return useCallback(
+ (href: string): void => {
+ const window = primaryWindow(readMirror());
+ if (window) {
+ openInWindow(window.id, href);
+ return;
+ }
+
+ void reseedMirror()
+ .then((server) => {
+ const seededWindow = primaryWindow(server ?? readMirror());
+ if (seededWindow) {
+ openInWindow(seededWindow.id, href);
+ return;
+ }
+ logger.error("browser-tabs: open found no window after reseed");
+ })
+ .catch((error) => {
+ logger.error("browser-tabs: open reseed failed", { error });
+ });
+ },
+ [logger, openInWindow],
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/AGENTS.md b/products/desktop/packages/ui/src/features/canvas/AGENTS.md
index 9f002fc76524..523893cbe95b 100644
--- a/products/desktop/packages/ui/src/features/canvas/AGENTS.md
+++ b/products/desktop/packages/ui/src/features/canvas/AGENTS.md
@@ -45,12 +45,11 @@ changing breadcrumbs, canvas naming, or the canvas generation harness. The root
Only Spaces and Activity own the column beside the rail; the rest are
whole-screen, so no route under them may draw a second nav.
- **A rail pick returns you to where that destination was**, not to its index.
- `RailHistorySync` records the settled route per destination in
- `railHistoryStore` (session-scoped; `startupLocation` already owns relaunch),
- and `pickRailDestination` replays it. Only Spaces carries sidebar state on top
- of its href, so `RailVisit.spaces` is the one pane-shaped field. Clicking the
- destination you are already on never restores — it runs `onReclick`, which for
- Spaces means the list.
+ `BrowserTabStrip` records the settled route per destination in the active
+ tab's `viewState.lastByPane`, and `pickRailDestination` replays it. Only Spaces
+ carries sidebar state on top of its href. Clicking the destination you are
+ already on never restores — it runs `onReclick`, which for Spaces means the
+ list.
Anything a destination does besides navigating must live in its route
component, not its `onPick`: the restore path navigates by href and never
reaches the navigation bridge.
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ActivityDetailPane.tsx b/products/desktop/packages/ui/src/features/canvas/components/ActivityDetailPane.tsx
index ed4cfe7ad644..a4d48985ce30 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ActivityDetailPane.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ActivityDetailPane.tsx
@@ -7,14 +7,14 @@ import {
EmptyTitle,
} from "@posthog/quill";
import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";
-import { useActivityDetailStore } from "@posthog/ui/features/canvas/stores/activityDetailStore";
+import { useActivitySelection } from "@posthog/ui/features/canvas/stores/activityDetailStore";
import { TaskDetail } from "@posthog/ui/features/task-detail/components/TaskDetail";
import { useResolvedTask } from "@posthog/ui/features/tasks/useResolvedTask";
import { TaskDetailSkeleton } from "@posthog/ui/router/routeSkeletons";
/** What the Activity destination shows beside its feed. */
export function ActivityDetailPane() {
- const selected = useActivityDetailStore((s) => s.selected);
+ const selected = useActivitySelection();
const task = useResolvedTask(selected?.taskId);
const { channels } = useChannels();
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.test.tsx
index 696c78a39813..d46e4f6812b4 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.test.tsx
@@ -3,6 +3,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
channelsLayout: true,
+ /** With tabs on, ⌘1-9 switches tabs and this component yields the keys. */
+ spacesTabs: false,
slots: [] as { id: string; name: string; path: string }[],
navigateToChannel: vi.fn(),
}));
@@ -10,6 +12,9 @@ const mocks = vi.hoisted(() => ({
vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({
useChannelsLayout: () => mocks.channelsLayout,
}));
+vi.mock("@posthog/ui/features/feature-flags/useSpacesTabs", () => ({
+ useSpacesTabs: () => mocks.spacesTabs,
+}));
vi.mock("@posthog/ui/features/canvas/hooks/useStarredChannelSlots", () => ({
useStarredChannelSlots: () => ({
slots: mocks.slots,
@@ -40,6 +45,7 @@ function press(digit: string, modifiers: Partial<KeyboardEventInit> = {}) {
describe("ChannelHotkeys", () => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.spacesTabs = false;
mocks.channelsLayout = true;
mocks.slots = [
{ id: "me-id", name: "me", path: "/me" },
@@ -87,6 +93,16 @@ describe("ChannelHotkeys", () => {
expect(mocks.navigateToChannel).not.toHaveBeenCalled();
});
+ it("yields the keys to the tab strip when tabs are on", () => {
+ mocks.spacesTabs = true;
+ mocks.slots = [{ id: "personal", name: "me", path: "/spaces/personal" }];
+ render(<ChannelHotkeys />);
+
+ press("1");
+
+ expect(mocks.navigateToChannel).not.toHaveBeenCalled();
+ });
+
it("stays out of the way when the layout is off", () => {
mocks.channelsLayout = false;
render(<ChannelHotkeys />);
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.tsx
index 9d9a2abe0890..788de5995b41 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.tsx
@@ -8,14 +8,16 @@ import {
import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";
import { requestSpaceSearchFocus } from "@posthog/ui/features/canvas/stores/spaceTreeStore";
import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";
+import { useSpacesTabs } from "@posthog/ui/features/feature-flags/useSpacesTabs";
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import { navigateToChannel } from "@posthog/ui/router/navigationBridge";
import { track } from "@posthog/ui/shell/analytics";
import { useHotkeys } from "react-hotkeys-hook";
/**
- * Renders nothing — the unconditional owner of ⌘1-9 (switch channel) under the
- * channels layout.
+ * Renders nothing — the owner of ⌘1-9 (switch channel) under the channels
+ * layout, wherever the tab strip is not. With tabs on, those keys switch tabs
+ * (the browser meaning) and this yields them, so a press has one owner.
*
* Mounted from the root rather than from the sidebar: the sidebar only renders
* its channel pane once a channel is already scoped, so binding there left the
@@ -26,6 +28,7 @@ import { useHotkeys } from "react-hotkeys-hook";
*/
export function ChannelHotkeys() {
const channelsLayout = useChannelsLayout();
+ const spacesTabs = useSpacesTabs();
const { slots } = useStarredChannelSlots();
const setCurrentChannel = useCurrentChannelStore((s) => s.setCurrentChannel);
@@ -52,7 +55,7 @@ export function ChannelHotkeys() {
});
},
{
- enabled: channelsLayout,
+ enabled: channelsLayout && !spacesTabs,
enableOnFormTags: true,
enableOnContentEditable: true,
preventDefault: true,
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx
index 7b811ab9ef3a..5f923255730d 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx
@@ -25,6 +25,7 @@ import {
} from "@posthog/ui/features/command/keyboard-shortcuts";
import { isContentEmpty } from "@posthog/ui/features/message-editor/content";
import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";
+import { isTaskInputSessionId } from "@posthog/ui/features/task-detail/taskInputSession";
import { openTaskInput } from "@posthog/ui/router/useOpenTask";
import { track } from "@posthog/ui/shell/analytics";
import { useState } from "react";
@@ -40,8 +41,11 @@ import { useState } from "react";
export function ChannelsFab({ channelId }: { channelId?: string }) {
const channelsLayout = useChannelsLayout();
const [modalOpen, setModalOpen] = useState(false);
- const hasDraft = useDraftStore(
- (s) => !isContentEmpty(s.drafts["task-input"]),
+ const hasDraft = useDraftStore((state) =>
+ Object.entries(state.drafts).some(
+ ([sessionId, draft]) =>
+ isTaskInputSessionId(sessionId) && !isContentEmpty(draft),
+ ),
);
const newTask = () => {
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx
index afce19ede71d..056b1e9f709f 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx
@@ -17,7 +17,7 @@ import { useRailSurface } from "@posthog/ui/features/canvas/hooks/useRailSurface
import { useTrackChannelsSpaceViewed } from "@posthog/ui/features/canvas/hooks/useTrackChannelsSpaceViewed";
import {
selectActivityItem,
- useActivityDetailStore,
+ useActivitySelection,
} from "@posthog/ui/features/canvas/stores/activityDetailStore";
import {
showChannelList,
@@ -185,7 +185,7 @@ export function ChannelsSidebar() {
// (route and main pane unchanged) while you look around. With no channel to
// slide to there's only the list.
const { showsActivityDetail } = useRailSurface();
- const selectedActivityId = useActivityDetailStore((s) => s.selected?.id);
+ const selectedActivityId = useActivitySelection()?.id;
const { feedId } = useParams({ strict: false });
const pane = useChannelPaneStore((s) => s.pane);
const showList = pane === "list" || currentChannelId == null;
diff --git a/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsx
index 288e4d57ff8a..ca70aba6443a 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/NavRail.test.tsx
@@ -1,16 +1,20 @@
-import { act, render, screen } from "@testing-library/react";
+import { act, fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
featureFlags: new Map<string, boolean>(),
fullPath: "/",
+ /** The settled location, so a pick can tell "where I was" from "where I am". */
+ href: "/",
navigate: vi.fn(),
navigateToActivity: vi.fn(),
navigateToSpaces: vi.fn(),
navigateToChannel: vi.fn(),
navigateToHome: vi.fn(),
navigateToInbox: vi.fn(),
+ openSettings: vi.fn(),
+ openBrowserTab: vi.fn(),
}));
vi.mock("@tanstack/react-router", () => ({
@@ -21,7 +25,10 @@ vi.mock("@tanstack/react-router", () => ({
}) => select({ matches: [{ fullPath: mocks.fullPath }] }),
}));
vi.mock("@posthog/ui/router/routerRef", () => ({
- getRouterOrNull: () => ({ navigate: mocks.navigate }),
+ getRouterOrNull: () => ({
+ navigate: mocks.navigate,
+ state: { resolvedLocation: { href: mocks.href } },
+ }),
}));
vi.mock("@posthog/ui/features/canvas/hooks/useTaskActivity", () => ({
@@ -34,6 +41,9 @@ vi.mock(
vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
useFeatureFlag: (key: string) => mocks.featureFlags.get(key) ?? false,
}));
+vi.mock("@posthog/ui/features/feature-flags/useSpacesTabs", () => ({
+ useSpacesTabs: () => true,
+}));
vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({
useChannelsLayout: () => true,
}));
@@ -41,7 +51,17 @@ vi.mock("@posthog/ui/features/inbox/hooks/useInboxAllReports", () => ({
useInboxAllReports: () => ({ counts: { pulls: 0 } }),
}));
vi.mock("@posthog/ui/features/sidebar/components/ProjectSwitcher", () => ({
- ProjectSwitcher: () => null,
+ ProjectSwitcher: () => (
+ <button type="button" aria-label="Project switcher">
+ Project switcher
+ </button>
+ ),
+}));
+vi.mock("@posthog/ui/features/browser-tabs/useOpenBrowserTab", () => ({
+ useOpenBrowserTab: () => mocks.openBrowserTab,
+}));
+vi.mock("@posthog/ui/features/settings/hooks/useOpenSettings", () => ({
+ openSettings: mocks.openSettings,
}));
vi.mock("@posthog/ui/router/navigationBridge", () => ({
getCurrentMatches: () => [{ fullPath: mocks.fullPath }],
@@ -59,27 +79,56 @@ vi.mock("@posthog/ui/features/canvas/components/ActivityHoverCard", () => ({
ActivityHoverCard: () => <div>Recent activity card</div>,
}));
-import { DESKTOP_HOME_FLAG } from "@posthog/shared";
+import { browserTabsStore } from "@posthog/core/browser-tabs/browserTabsStore";
+import { DESKTOP_HOME_FLAG, type RailVisit } from "@posthog/shared";
import {
clearKeepListForRoute,
shouldKeepListForRoute,
useChannelPaneStore,
} from "@posthog/ui/features/canvas/stores/channelPaneStore";
import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";
-import { useRailHistoryStore } from "@posthog/ui/features/canvas/stores/railHistoryStore";
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import { NavRail } from "./NavRail";
+/**
+ * Seed where each destination was, as the ACTIVE TAB remembers it. Rail memory
+ * lives on the tab rather than the window, so a pick in one tab can never
+ * restore an href another tab established.
+ */
+function rememberVisits(lastByPane: Record<string, RailVisit>): void {
+ browserTabsStore.getState().setSnapshot({
+ windows: [{ id: "w1", isPrimary: true, bounds: null, activeTabId: "t1" }],
+ tabs: [
+ {
+ id: "t1",
+ windowId: "w1",
+ href: null,
+ viewState: { lastByPane },
+ dashboardId: null,
+ taskId: null,
+ channelId: null,
+ channelSection: null,
+ appView: null,
+ position: 1000,
+ scrollState: null,
+ createdAt: 0,
+ lastActiveAt: 0,
+ },
+ ],
+ });
+}
+
describe("NavRail", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.featureFlags.clear();
mocks.featureFlags.set(DESKTOP_HOME_FLAG, true);
mocks.fullPath = "/";
+ mocks.href = "/";
useSidebarStore.setState({ navItemOverrides: {}, navItemOrder: [] });
useCurrentChannelStore.setState({ currentChannelId: null });
useChannelPaneStore.setState({ pane: "channel" });
- useRailHistoryStore.setState({ lastByPane: {} });
+ rememberVisits({});
clearKeepListForRoute();
});
@@ -91,6 +140,20 @@ describe("NavRail", () => {
expect(screen.queryByLabelText("Home")).not.toBeInTheDocument();
});
+ it("keeps Search directly above Settings at the bottom of the rail", () => {
+ render(<NavRail />);
+
+ const buttonLabels = screen
+ .getAllByRole("button")
+ .map((button) => button.getAttribute("aria-label"));
+
+ expect(buttonLabels.slice(-3)).toEqual([
+ "Search",
+ "Settings",
+ "Project switcher",
+ ]);
+ });
+
// The route is the whole answer, so a destination can never be lit over a
// screen that isn't it.
it.each([
@@ -113,6 +176,25 @@ describe("NavRail", () => {
});
describe("with nothing remembered", () => {
+ it("opens a destination in a new tab on Cmd-click", () => {
+ render(<NavRail />);
+
+ fireEvent.click(screen.getByLabelText("Inbox"), { metaKey: true });
+
+ expect(mocks.openBrowserTab).toHaveBeenCalledWith("/inbox");
+ expect(mocks.navigateToInbox).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it("keeps Settings in the current window on Cmd-click", () => {
+ render(<NavRail />);
+
+ fireEvent.click(screen.getByLabelText("Settings"), { metaKey: true });
+
+ expect(mocks.openSettings).toHaveBeenCalledOnce();
+ expect(mocks.openBrowserTab).not.toHaveBeenCalled();
+ });
+
it("routes to Activity from a screen that has no column for it", async () => {
const user = userEvent.setup();
mocks.fullPath = "/inbox";
@@ -151,12 +233,11 @@ describe("NavRail", () => {
describe("returning to where you were", () => {
it("reopens the page the destination was left on", async () => {
const user = userEvent.setup();
- useRailHistoryStore.setState({
- lastByPane: {
- spaces: {
- href: "/spaces/chan-1/loops",
- spaces: { listOpen: false, spaceId: "chan-1" },
- },
+ rememberVisits({
+ spaces: {
+ href: "/spaces/chan-1/loops",
+ listOpen: false,
+ spaceId: "chan-1",
},
});
render(<NavRail />);
@@ -174,12 +255,11 @@ describe("NavRail", () => {
// The sidebar pane is view state, so the href alone cannot bring it back.
it("puts the space list back if that is what was on screen", async () => {
const user = userEvent.setup();
- useRailHistoryStore.setState({
- lastByPane: {
- spaces: {
- href: "/spaces/chan-1/tasks/task-1",
- spaces: { listOpen: true, spaceId: "chan-1" },
- },
+ rememberVisits({
+ spaces: {
+ href: "/spaces/chan-1/tasks/task-1",
+ listOpen: true,
+ spaceId: "chan-1",
},
});
render(<NavRail />);
@@ -196,10 +276,8 @@ describe("NavRail", () => {
const user = userEvent.setup();
mocks.fullPath = "/inbox";
useChannelPaneStore.setState({ pane: "channel" });
- useRailHistoryStore.setState({
- lastByPane: {
- spaces: { href: "/spaces", spaces: { listOpen: true } },
- },
+ rememberVisits({
+ spaces: { href: "/spaces", listOpen: true },
});
render(<NavRail />);
@@ -211,12 +289,11 @@ describe("NavRail", () => {
it("returns to the space pane when the list was not open", async () => {
const user = userEvent.setup();
useChannelPaneStore.setState({ pane: "list" });
- useRailHistoryStore.setState({
- lastByPane: {
- spaces: {
- href: "/spaces/chan-1",
- spaces: { listOpen: false, spaceId: "chan-1" },
- },
+ rememberVisits({
+ spaces: {
+ href: "/spaces/chan-1",
+ listOpen: false,
+ spaceId: "chan-1",
},
});
render(<NavRail />);
@@ -226,14 +303,27 @@ describe("NavRail", () => {
expect(useChannelPaneStore.getState().pane).toBe("channel");
});
+ // A memory equal to the current page restores nothing, so the click would
+ // look dead and there would be no way off the page by rail.
+ it("goes to the root when the memory is the page we are on", async () => {
+ const user = userEvent.setup();
+ mocks.fullPath = "/activity";
+ mocks.href = "/activity";
+ rememberVisits({ home: { href: "/activity" } });
+ render(<NavRail />);
+
+ await user.click(screen.getByLabelText("Home"));
+
+ expect(mocks.navigateToHome).toHaveBeenCalledOnce();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
it("remembers each destination separately", async () => {
const user = userEvent.setup();
mocks.fullPath = "/";
- useRailHistoryStore.setState({
- lastByPane: {
- inbox: { href: "/inbox/pulls/42" },
- loops: { href: "/loops/abc" },
- },
+ rememberVisits({
+ inbox: { href: "/inbox/pulls/42" },
+ loops: { href: "/loops/abc" },
});
render(<NavRail />);
@@ -249,13 +339,8 @@ describe("NavRail", () => {
const user = userEvent.setup();
mocks.fullPath = "/spaces/$channelId/loops";
useCurrentChannelStore.setState({ currentChannelId: "chan-1" });
- useRailHistoryStore.setState({
- lastByPane: {
- spaces: {
- href: "/spaces/chan-1",
- spaces: { listOpen: false, spaceId: "chan-1" },
- },
- },
+ rememberVisits({
+ spaces: { href: "/spaces/chan-1", listOpen: false, spaceId: "chan-1" },
});
render(<NavRail />);
@@ -271,9 +356,7 @@ describe("NavRail", () => {
it("goes up to the index rather than restoring", async () => {
const user = userEvent.setup();
mocks.fullPath = "/inbox/pulls/$reportId";
- useRailHistoryStore.setState({
- lastByPane: { inbox: { href: "/inbox/pulls/42" } },
- });
+ rememberVisits({ inbox: { href: "/inbox/pulls/42" } });
render(<NavRail />);
await user.click(screen.getByLabelText("Inbox"));
@@ -338,9 +421,11 @@ describe("NavRail", () => {
});
const { container } = render(<NavRail />);
- const labels = [...container.querySelectorAll("button")].map((button) =>
- button.getAttribute("aria-label"),
- );
+ // Search leads the rail and is not a destination, so it sits outside the
+ // customizable order.
+ const labels = [...container.querySelectorAll("button")]
+ .map((button) => button.getAttribute("aria-label"))
+ .filter((label) => label !== "Search");
expect(labels.slice(0, 5)).toEqual([
"Home",
"Spaces",
diff --git a/products/desktop/packages/ui/src/features/canvas/components/NavRail.tsx b/products/desktop/packages/ui/src/features/canvas/components/NavRail.tsx
index adfe70c26053..92b8495af6e0 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/NavRail.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/NavRail.tsx
@@ -1,4 +1,4 @@
-import { BellIcon, GearSix } from "@phosphor-icons/react";
+import { BellIcon, GearSix, MagnifyingGlass } from "@phosphor-icons/react";
import {
Button,
cn,
@@ -12,6 +12,7 @@ import {
} from "@posthog/quill";
import { DESKTOP_HOME_FLAG, LOOPS_FLAG } from "@posthog/shared";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import { useOpenBrowserTab } from "@posthog/ui/features/browser-tabs/useOpenBrowserTab";
import { ActivityHoverCard } from "@posthog/ui/features/canvas/components/ActivityHoverCard";
import {
pickRailDestination,
@@ -21,9 +22,14 @@ import {
} from "@posthog/ui/features/canvas/components/railDestinations";
import { useRailPane } from "@posthog/ui/features/canvas/hooks/useRailSurface";
import { useTaskActivity } from "@posthog/ui/features/canvas/hooks/useTaskActivity";
+import {
+ formatHotkey,
+ SHORTCUTS,
+} from "@posthog/ui/features/command/keyboard-shortcuts";
import { useCommandCenterActiveCount } from "@posthog/ui/features/command-center/useCommandCenterActiveCount";
import { useContextLayerFlag } from "@posthog/ui/features/feature-flags/useContextLayerFlag";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+import { useSpacesTabs } from "@posthog/ui/features/feature-flags/useSpacesTabs";
import { useInboxAllReports } from "@posthog/ui/features/inbox/hooks/useInboxAllReports";
import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";
import { ProjectSwitcher } from "@posthog/ui/features/sidebar/components/ProjectSwitcher";
@@ -34,8 +40,10 @@ import {
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import { CountBadge } from "@posthog/ui/primitives/CountBadge";
import { track } from "@posthog/ui/shell/analytics";
+import { useCommandMenuStore } from "@posthog/ui/shell/commandMenuStore";
import {
type ComponentPropsWithRef,
+ type MouseEventHandler,
type ReactElement,
type ReactNode,
useState,
@@ -58,7 +66,7 @@ function NavIcon({
label: string;
shortcut?: string;
isActive: boolean;
- onClick: () => void;
+ onClick: MouseEventHandler<HTMLButtonElement>;
badge?: ReactNode;
}) {
return (
@@ -151,7 +159,7 @@ function ActivityNavItem({
}: {
isActive: boolean;
badge: ReactNode;
- onClick: () => void;
+ onClick: MouseEventHandler<HTMLButtonElement>;
}) {
const bell = (
<NavButton
@@ -175,6 +183,8 @@ export function NavRail() {
const homeEnabled = useFeatureFlag(DESKTOP_HOME_FLAG);
const loopsEnabled = useFeatureFlag(LOOPS_FLAG, import.meta.env.DEV);
const contextEnabled = useContextLayerFlag();
+ const tabsEnabled = useSpacesTabs();
+ const openBrowserTab = useOpenBrowserTab();
const { counts: inboxCounts } = useInboxAllReports({
ignoreFilters: true,
@@ -190,6 +200,7 @@ export function NavRail() {
// The route is the only thing that says where you are, so the rail cannot
// light a destination the screen isn't on.
const railPane = useRailPane();
+ const toggleCommandMenu = useCommandMenuStore((s) => s.toggle);
const navItemOverrides = useSidebarStore((s) => s.navItemOverrides);
const navItemOrder = useSidebarStore((s) => s.navItemOrder);
const destinations = visibleRailDestinations({
@@ -201,14 +212,21 @@ export function NavRail() {
});
const settingsVisible = isNavItemVisible(navItemOverrides, "configure");
- const pick = (destination: RailDestination) => () => {
- track(ANALYTICS_EVENTS.SIDEBAR_NAV_ITEM_CLICKED, {
- item: destination.analyticsId,
- in_more: false,
- layout: "channels",
- });
- pickRailDestination(destination, railPane);
- };
+ const pick =
+ (destination: RailDestination): MouseEventHandler<HTMLButtonElement> =>
+ (event) => {
+ track(ANALYTICS_EVENTS.SIDEBAR_NAV_ITEM_CLICKED, {
+ item: destination.analyticsId,
+ in_more: false,
+ layout: "channels",
+ });
+ if (tabsEnabled && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ openBrowserTab(destination.href);
+ return;
+ }
+ pickRailDestination(destination, railPane);
+ };
return (
// One provider for the whole rail: the tooltip skip window is provider
@@ -253,6 +271,13 @@ export function NavRail() {
);
})}
<div className="mt-auto flex flex-col items-center gap-1.5">
+ <NavIcon
+ icon={<MagnifyingGlass size={16} />}
+ label="Search"
+ shortcut={formatHotkey(SHORTCUTS.COMMAND_MENU)}
+ isActive={false}
+ onClick={toggleCommandMenu}
+ />
{settingsVisible && (
<NavIcon
icon={<GearSix size={16} />}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/RailHistorySync.tsx b/products/desktop/packages/ui/src/features/canvas/components/RailHistorySync.tsx
deleted file mode 100644
index b2820eec1af0..000000000000
--- a/products/desktop/packages/ui/src/features/canvas/components/RailHistorySync.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
-import { railPaneForMatches } from "@posthog/ui/features/canvas/railPane";
-import { useChannelPaneStore } from "@posthog/ui/features/canvas/stores/channelPaneStore";
-import { useRailHistoryStore } from "@posthog/ui/features/canvas/stores/railHistoryStore";
-import { useRouterState } from "@tanstack/react-router";
-import { useEffect } from "react";
-
-/**
- * Renders nothing — records where each rail destination was when you left it.
- *
- * One writer, on every settled navigation, rather than a note the rail takes as
- * you click away: a destination is also left by hotkeys, deep links and links
- * in the content, and a pick that only remembered its own departures would
- * return you somewhere you had already moved on from.
- */
-export function RailHistorySync() {
- const channelsLayout = useChannelsLayout();
- // Destination, href and space each read off the router snapshot. They settle
- // together, so three selectors cannot disagree within a render.
- //
- // `resolvedLocation`, not `location`: during a pending navigation `location`
- // is already the destination while `matches` still describes the page being
- // left, and that pair records the old destination against the new href — so
- // every pick sends you to the page you were walking away from.
- const pane = useRouterState({ select: (s) => railPaneForMatches(s.matches) });
- const href = useRouterState({
- select: (s) => (s.resolvedLocation ?? s.location).href,
- });
- const spaceId = useRouterState({
- select: (s) =>
- (
- s.matches[s.matches.length - 1]?.params as
- | { channelId?: string }
- | undefined
- )?.channelId,
- });
- const listOpen = useChannelPaneStore((s) => s.pane === "list");
- const record = useRailHistoryStore((s) => s.record);
-
- useEffect(() => {
- if (!channelsLayout) return;
- record(pane, {
- href,
- spaces: pane === "spaces" ? { listOpen, spaceId } : undefined,
- });
- }, [channelsLayout, pane, href, spaceId, listOpen, record]);
-
- return null;
-}
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.tsx
index f2118eb67919..2887f52f13f4 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
@@ -39,12 +39,25 @@ vi.mock("@tanstack/react-router", () => ({
}: {
select: (s: {
location: { pathname: string };
- matches: { routeId: string }[];
+ matches: {
+ routeId: string;
+ fullPath: string;
+ search: Record<string, unknown>;
+ }[];
}) => unknown;
}) =>
select({
location: { pathname: "/spaces/chan-1/tasks/task-1" },
- matches: [{ routeId: "/spaces/$channelId/tasks/$taskId" }],
+ matches: [
+ {
+ routeId: "/spaces/$channelId/tasks/$taskId",
+ // Activity's pane reads its selection off `/activity`'s search, which
+ // this route is not — the pane renders its empty state, which is all
+ // this test needs from it.
+ fullPath: "/spaces/$channelId/tasks/$taskId",
+ search: {},
+ },
+ ],
}),
}));
vi.mock(
@@ -116,16 +129,12 @@ vi.mock("@posthog/ui/features/task-detail/components/TaskDetail", () => ({
},
}));
-import { useActivityDetailStore } from "@posthog/ui/features/canvas/stores/activityDetailStore";
import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";
import { ActivityDetailPane } from "./ActivityDetailPane";
import { ShellLayout } from "./ShellLayout";
describe("SpaceHeaderRow", () => {
it("keeps the header store off the layout that renders its writer", () => {
- useActivityDetailStore.setState({
- selected: { id: "a1", taskId: "task-1", channelId: "chan-1" },
- });
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.test.tsx
index 77c5b54e0d2f..c938df7cb433 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.test.tsx
@@ -115,12 +115,14 @@ vi.mock("@tanstack/react-router", () => ({
}: {
select: (s: {
matches: { routeId: string; params: Record<string, string> }[];
+ location: { state: { tabId: string } };
}) => unknown;
}) =>
select({
matches: [
{ routeId: "/spaces/$channelId/new", params: { channelId: "chan-1" } },
],
+ location: { state: { tabId: "tab-1" } },
}),
}));
@@ -209,6 +211,7 @@ describe("SpaceNewTask context panel", () => {
expect.objectContaining({
channelId: "chan-1",
channelContextId: "chan-1",
+ sessionId: "task-input:tab-1",
}),
);
});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.tsx b/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.tsx
index c63c1d7934f3..c12fade02228 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.tsx
@@ -11,15 +11,14 @@ import { useTaskChannels } from "@posthog/ui/features/canvas/hooks/useTaskChanne
import { useChannelWikiContext } from "@posthog/ui/features/context-wiki/hooks/useContextWiki";
import { useContextLayerFlag } from "@posthog/ui/features/feature-flags/useContextLayerFlag";
import { TaskInput } from "@posthog/ui/features/task-detail/components/TaskInput";
-import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";
+import { getTaskInputSessionId } from "@posthog/ui/features/task-detail/taskInputSession";
import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";
import { ResizableSidebar } from "@posthog/ui/primitives/ResizableSidebar";
import { toast } from "@posthog/ui/primitives/toast";
import { useAppView } from "@posthog/ui/router/useAppView";
import { track } from "@posthog/ui/shell/analytics";
import { Flex } from "@radix-ui/themes";
-import { useQueryClient } from "@tanstack/react-query";
-import { useNavigate } from "@tanstack/react-router";
+import { useNavigate, useRouterState } from "@tanstack/react-router";
import { useCallback, useMemo, useState } from "react";
// A space's "New task" view. Reuses the shared TaskInput, but routes the
@@ -30,7 +29,10 @@ export function SpaceNewTask({ channelId }: { channelId: string }) {
const spacesLayout = useChannelsLayout();
const navigate = useNavigate();
const view = useAppView();
- const queryClient = useQueryClient();
+ const tabId = useRouterState({
+ select: (state) => state.location.state.tabId,
+ });
+ const taskInputSessionId = getTaskInputSessionId(tabId);
const { fileTask } = useChannelTaskMutations();
// The raw channel row also carries the space's repository defaults.
const { channels } = useTaskChannels();
@@ -79,11 +81,8 @@ export function SpaceNewTask({ channelId }: { channelId: string }) {
}
}, [channelId, contextPanelOpen]);
- const onTaskCreated = useCallback(
+ const onTaskCreatedEffect = useCallback(
(task: Task) => {
- // Seed the detail cache so the destination route resolves instantly
- // (mirrors openTask), then file to the channel + navigate.
- queryClient.setQueryData(taskDetailQuery(task.id).queryKey, task);
void fileTask(channelId, task.id)
.then(() => {
track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
@@ -106,17 +105,13 @@ export function SpaceNewTask({ channelId }: { channelId: string }) {
description: error instanceof Error ? error.message : String(error),
});
});
- void navigate({
- to: "/spaces/$channelId/tasks/$taskId",
- params: { channelId, taskId: task.id },
- });
},
- [channelId, fileTask, navigate, queryClient],
+ [channelId, fileTask],
);
- // Retargeting navigates to that space's own new-task route; the composer's
- // draft lives in the shared "task-input" draft store, so text typed before
- // switching survives the navigation.
+ // Retargeting navigates to that space's own new-task route. The draft is
+ // scoped to the browser tab, so it survives this route change without
+ // leaking into another new-task tab.
const handleSpaceChange = useCallback(
(nextChannelId: string) => {
track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
@@ -136,6 +131,8 @@ export function SpaceNewTask({ channelId }: { channelId: string }) {
<Flex className="h-full min-w-0 flex-1">
<div className="min-w-0 flex-1">
<TaskInput
+ key={taskInputSessionId}
+ sessionId={taskInputSessionId}
// Beside the Cloud/Local chip: which space the task files into.
// Arriving from a space's own "+" this is pre-filled; the global
// new-task entry points land on #me.
@@ -146,7 +143,7 @@ export function SpaceNewTask({ channelId }: { channelId: string }) {
disabled={disabled}
/>
)}
- onTaskCreated={onTaskCreated}
+ onTaskCreatedEffect={onTaskCreatedEffect}
channelContext={channelContext}
channelContextPath={wiki.path}
channelContextBlocked={wiki.blocked}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/railDestinations.ts b/products/desktop/packages/ui/src/features/canvas/components/railDestinations.ts
index 05ed113d633c..3246ad70ed0c 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/railDestinations.ts
+++ b/products/desktop/packages/ui/src/features/canvas/components/railDestinations.ts
@@ -6,18 +6,16 @@ import {
type IconProps,
Lightning,
} from "@phosphor-icons/react";
+import type { RailVisit } from "@posthog/shared";
import type { SidebarNavItem } from "@posthog/shared/analytics-events";
+import { readMirror } from "@posthog/ui/features/browser-tabs/tabsSync";
import { SpacesIcon } from "@posthog/ui/features/canvas/components/SpacesIcon";
import type { NavRailPane } from "@posthog/ui/features/canvas/railPane";
import {
+ applyTabViewState,
showChannelList,
- showChannelPane,
} from "@posthog/ui/features/canvas/stores/channelPaneStore";
import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";
-import {
- type RailVisit,
- useRailHistoryStore,
-} from "@posthog/ui/features/canvas/stores/railHistoryStore";
import {
formatHotkey,
SHORTCUTS,
@@ -53,6 +51,8 @@ export interface RailDestination {
label: string;
analyticsId: SidebarNavItem;
Icon: ComponentType<IconProps>;
+ /** Root opened by an explicit Cmd/Ctrl-click. */
+ href: string;
/** Where the destination lands with nothing remembered. */
onPick: () => void;
/**
@@ -87,15 +87,34 @@ export function showSpaces(): void {
navigateToChannel(channelId);
}
-/** Put a destination back the way you left it, sidebar pane included. */
+/**
+ * Where each rail destination was when the ACTIVE TAB last left it. Per tab, so
+ * a pick in one tab can never restore an href another tab established, and so
+ * two tabs can sit on the same destination in different places.
+ */
+function lastVisitForActiveTab(pane: NavRailPane): RailVisit | undefined {
+ const snapshot = readMirror();
+ const window =
+ snapshot.windows.find((w) => w.isPrimary) ?? snapshot.windows[0];
+ const active = window?.activeTabId
+ ? snapshot.tabs.find((t) => t.id === window.activeTabId)
+ : undefined;
+ return active?.viewState?.lastByPane?.[pane];
+}
+
+function currentHref(): string | undefined {
+ const state = getRouterOrNull()?.state;
+ return (state?.resolvedLocation ?? state?.location)?.href;
+}
+
+/**
+ * Put a destination back the way you left it, sidebar pane included. Shares
+ * `applyTabViewState` with the tab switch, which restores the same two facts:
+ * an unscoped space route (the index, an unfiled task) has no channel to hold
+ * the list across, but the list was open and stays open.
+ */
function restoreVisit(visit: RailVisit): void {
- const spaces = visit.spaces;
- if (spaces) {
- if (!spaces.listOpen) showChannelPane();
- // An unscoped space route (the index, an unfiled task) has no channel to
- // hold the list across, but the list was open and stays open.
- else showChannelList(spaces.spaceId);
- }
+ applyTabViewState(visit);
void getRouterOrNull()?.navigate({ href: visit.href });
}
@@ -112,8 +131,11 @@ export function pickRailDestination(
(destination.onReclick ?? destination.onPick)();
return;
}
- const visit = useRailHistoryStore.getState().lastByPane[destination.pane];
- if (visit) restoreVisit(visit);
+ const visit = lastVisitForActiveTab(destination.pane);
+ // A remembered visit that IS where we already are restores nothing, and the
+ // click would look dead. Fall through to the destination's root instead, so
+ // a pick always goes somewhere.
+ if (visit && visit.href !== currentHref()) restoreVisit(visit);
else destination.onPick();
}
@@ -123,6 +145,7 @@ export const RAIL_DESTINATIONS: readonly RailDestination[] = [
label: "Home",
analyticsId: "home",
Icon: HouseSimple,
+ href: "/",
onPick: navigateToHome,
enabled: (flags) => flags.home,
},
@@ -131,6 +154,7 @@ export const RAIL_DESTINATIONS: readonly RailDestination[] = [
label: "Spaces",
analyticsId: "spaces",
Icon: SpacesIcon,
+ href: "/spaces",
onPick: showSpaces,
// Already in Spaces, so the pick is asking for the one thing above the
// space you are in: the list.
@@ -142,6 +166,7 @@ export const RAIL_DESTINATIONS: readonly RailDestination[] = [
label: "Activity",
analyticsId: "activity",
Icon: BellIcon,
+ href: "/activity",
onPick: navigateToActivity,
count: (counts) => counts.activity,
},
@@ -151,6 +176,7 @@ export const RAIL_DESTINATIONS: readonly RailDestination[] = [
label: "Inbox",
analyticsId: "inbox",
Icon: EnvelopeSimple,
+ href: "/inbox",
onPick: navigateToInbox,
shortcut: formatHotkey(SHORTCUTS.INBOX),
count: (counts) => counts.inbox,
@@ -161,6 +187,7 @@ export const RAIL_DESTINATIONS: readonly RailDestination[] = [
label: "Command Center",
analyticsId: "command_center",
Icon: Lightning,
+ href: "/command-center",
onPick: navigateToCommandCenter,
count: (counts) => counts.commandCenter,
countTone: "neutral",
@@ -171,6 +198,7 @@ export const RAIL_DESTINATIONS: readonly RailDestination[] = [
label: "Loops",
analyticsId: "loops",
Icon: LoopIcon,
+ href: "/loops",
onPick: () => navigateToLoops(),
enabled: (flags) => flags.loops,
},
@@ -180,6 +208,7 @@ export const RAIL_DESTINATIONS: readonly RailDestination[] = [
label: "Context",
analyticsId: "contexts",
Icon: BookOpenTextIcon,
+ href: "/spaces/context",
onPick: navigateToSpacesContext,
enabled: (flags) => flags.context,
},
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/activityDetailStore.ts b/products/desktop/packages/ui/src/features/canvas/stores/activityDetailStore.ts
index 33517f8dc52e..f4bc8fc8efee 100644
--- a/products/desktop/packages/ui/src/features/canvas/stores/activityDetailStore.ts
+++ b/products/desktop/packages/ui/src/features/canvas/stores/activityDetailStore.ts
@@ -1,5 +1,6 @@
import type { TaskActivityItem } from "@posthog/core/canvas/taskActivity";
-import { create } from "zustand";
+import { getRouterOrNull } from "@posthog/ui/router/routerRef";
+import { useRouterState } from "@tanstack/react-router";
export interface ActivitySelection {
id: string;
@@ -7,22 +8,75 @@ export interface ActivitySelection {
channelId: string | null;
}
-interface ActivityDetailState {
- /** Held here rather than in the URL: routing away from Activity would take
- * the feed off the screen you are reading it from. */
- selected: ActivitySelection | null;
- select: (selection: ActivitySelection | null) => void;
+/**
+ * What Activity is showing beside its feed, carried in `/activity`'s search
+ * params.
+ *
+ * It used to be a window-global store, kept out of the URL so that picking an
+ * item could not route you off the feed you were reading it from. A search
+ * param does not: you stay on `/activity`, the feed stays beside you. Putting it
+ * in the location is what lets a tab name the session it is showing, restore it
+ * on relaunch, and let two Activity tabs hold different items — none of which a
+ * global store can do.
+ *
+ * All three fields ride along rather than resolving the item from the feed,
+ * because the chrome (breadcrumb, tab label) reads them before the feed loads.
+ */
+export interface ActivitySearch {
+ item?: string;
+ session?: string;
+ space?: string;
}
-export const useActivityDetailStore = create<ActivityDetailState>()((set) => ({
- selected: null,
- select: (selected) => set({ selected }),
-}));
+export function parseActivitySearch(
+ search: Record<string, unknown>,
+): ActivitySearch {
+ const str = (v: unknown) => (typeof v === "string" && v ? v : undefined);
+ return {
+ item: str(search.item),
+ session: str(search.session),
+ space: str(search.space),
+ };
+}
+
+function toSelection(
+ search: ActivitySearch | undefined,
+): ActivitySelection | null {
+ if (!search?.item || !search.session) return null;
+ return {
+ id: search.item,
+ taskId: search.session,
+ channelId: search.space ?? null,
+ };
+}
+
+/** The selection, or null when nothing is picked. */
+export function useActivitySelection(): ActivitySelection | null {
+ return useRouterState({
+ select: (s) => {
+ const match = s.matches.find((m) => m.fullPath === "/activity");
+ if (!match) return null;
+ return toSelection(match.search as ActivitySearch);
+ },
+ });
+}
+
+/** Read the selection outside React (the chrome's imperative paths). */
+export function getActivitySelection(): ActivitySelection | null {
+ const router = getRouterOrNull();
+ if (!router) return null;
+ const match = router.state.matches.find((m) => m.fullPath === "/activity");
+ if (!match) return null;
+ return toSelection(match.search as ActivitySearch);
+}
export function selectActivityItem(item: TaskActivityItem): void {
- useActivityDetailStore.getState().select({
- id: item.id,
- taskId: item.taskId,
- channelId: item.channelId,
+ void getRouterOrNull()?.navigate({
+ to: "/activity",
+ search: {
+ item: item.id,
+ session: item.taskId,
+ ...(item.channelId ? { space: item.channelId } : {}),
+ },
});
}
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.test.ts b/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.test.ts
new file mode 100644
index 000000000000..e8debe46398b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.test.ts
@@ -0,0 +1,25 @@
+import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";
+import { beforeEach, describe, expect, it } from "vitest";
+import { applyTabViewState } from "./channelPaneStore";
+
+describe("applyTabViewState", () => {
+ beforeEach(() => {
+ useCurrentChannelStore.setState({
+ currentChannelId: "space-from-prev-tab",
+ });
+ });
+
+ it.each([
+ ["null clears the scoped channel", null, null],
+ ["a string scopes to that space", "space-b", "space-b"],
+ [
+ "undefined leaves the scoped channel untouched",
+ undefined,
+ "space-from-prev-tab",
+ ],
+ ] as const)("restores spaceId: %s", (_name, spaceId, expected) => {
+ applyTabViewState({ spaceId });
+
+ expect(useCurrentChannelStore.getState().currentChannelId).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.ts b/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.ts
index 3576db6c40da..e9597fa7b3cd 100644
--- a/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.ts
+++ b/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.ts
@@ -1,3 +1,4 @@
+import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";
import { create } from "zustand";
/**
@@ -60,3 +61,26 @@ export function showChannelPane(): void {
keepListForChannelId = null;
useChannelPaneStore.getState().setPane("channel");
}
+
+/**
+ * Put the sidebar back the way a tab left it.
+ *
+ * The pane and the scoped space are window-global stores, but each tab has its
+ * own. Switching tabs has to restore them, or the next navigation effect reads
+ * the tab you *left* and writes that over the tab you arrived at.
+ *
+ * `showChannelList` arms the keep-list latch, so an in-flight navigation into
+ * the space does not immediately slide the list away again.
+ */
+export function applyTabViewState(view: {
+ listOpen?: boolean;
+ spaceId?: string | null;
+}): void {
+ // A stored null explicitly clears the space; only an absent value is skipped.
+ if (view.spaceId !== undefined) {
+ useCurrentChannelStore.getState().setCurrentChannel(view.spaceId);
+ }
+ if (view.listOpen === undefined) return;
+ if (view.listOpen) showChannelList(view.spaceId ?? undefined);
+ else showChannelPane();
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/railHistoryStore.test.ts b/products/desktop/packages/ui/src/features/canvas/stores/railHistoryStore.test.ts
deleted file mode 100644
index 98d6601e8bc3..000000000000
--- a/products/desktop/packages/ui/src/features/canvas/stores/railHistoryStore.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { beforeEach, expect, it } from "vitest";
-import { resetRailHistory, useRailHistoryStore } from "./railHistoryStore";
-
-beforeEach(() => resetRailHistory());
-
-it("forgets every remembered destination on reset", () => {
- // A project or account switch calls this; without it a later rail pick would
- // restore a page — or re-scope the app to a space — from the old project.
- useRailHistoryStore.getState().record("spaces", {
- href: "/spaces/old-space",
- spaces: { listOpen: true, spaceId: "old-space" },
- });
- useRailHistoryStore.getState().record("inbox", { href: "/inbox/pulls/1" });
- expect(useRailHistoryStore.getState().lastByPane).not.toEqual({});
-
- resetRailHistory();
-
- expect(useRailHistoryStore.getState().lastByPane).toEqual({});
-});
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/railHistoryStore.ts b/products/desktop/packages/ui/src/features/canvas/stores/railHistoryStore.ts
deleted file mode 100644
index cfc38d5219db..000000000000
--- a/products/desktop/packages/ui/src/features/canvas/stores/railHistoryStore.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import type { NavRailPane } from "@posthog/ui/features/canvas/railPane";
-import { create } from "zustand";
-
-/**
- * The sidebar state a space visit has on top of its route: whether the space
- * list was drawn over the space pane, and the space it was drawn over. That is
- * view state rather than a route, so the href alone cannot bring it back.
- */
-export interface SpacesVisitView {
- listOpen: boolean;
- /** Absent on the space index and other unscoped routes. */
- spaceId?: string;
-}
-
-export interface RailVisit {
- /** The concrete href, so a pick returns to the page, not the destination. */
- href: string;
- /** Set only for Spaces — no other destination has a sidebar pane to restore. */
- spaces?: SpacesVisitView;
-}
-
-interface RailHistoryState {
- lastByPane: Partial<Record<NavRailPane, RailVisit>>;
- record: (pane: NavRailPane, visit: RailVisit) => void;
-}
-
-/**
- * Where each rail destination was when you last left it.
- *
- * Session-scoped on purpose: `startupLocation` already reopens the app on the
- * route you quit, so persisting this would compete with it on launch and hand
- * you a week-old inbox report behind a destination you had moved on from.
- */
-export const useRailHistoryStore = create<RailHistoryState>()((set) => ({
- lastByPane: {},
- record: (pane, visit) =>
- set((state) => ({ lastByPane: { ...state.lastByPane, [pane]: visit } })),
-}));
-
-/**
- * Forget every remembered destination. Called on logout and project switch
- * (beside `resetCurrentChannel`) because a visit holds hrefs and space ids from
- * the current project; without this a rail pick after a switch would restore a
- * page — or re-scope the app to a space — from the project the user just left.
- */
-export function resetRailHistory(): void {
- useRailHistoryStore.setState({ lastByPane: {} });
-}
diff --git a/products/desktop/packages/ui/src/features/command/CommandSearchBar.tsx b/products/desktop/packages/ui/src/features/command/CommandSearchBar.tsx
deleted file mode 100644
index 5906f830e60b..000000000000
--- a/products/desktop/packages/ui/src/features/command/CommandSearchBar.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import { MagnifyingGlass } from "@phosphor-icons/react";
-import { Kbd } from "@posthog/quill";
-import {
- formatHotkey,
- SHORTCUTS,
-} from "@posthog/ui/features/command/keyboard-shortcuts";
-
-/**
- * The search field over the content pane — a target you aim at, not an icon you
- * hunt for. It opens the command menu rather than typing into anything, so it is
- * a button wearing a field's clothes: the placeholder and the shortcut hint are
- * what tell you the menu is behind it.
- *
- * It fills the title bar's middle, which is the content column's width, and caps
- * itself so a wide window leaves it centred rather than stretched.
- */
-export function CommandSearchBar({ onClick }: { onClick: () => void }) {
- return (
- // The row is a window-drag region; the field has to opt out of it or the
- // press that should open the menu drags the window instead.
- <div className="mt-px min-w-0 flex-1 px-3">
- <button
- type="button"
- aria-label="Search"
- onClick={onClick}
- className="no-drag mx-auto flex h-7 w-full max-w-120 items-center gap-2 rounded-sm bg-fill-hover pr-1 pl-2 hover:bg-fill-selected dark:hover:bg-input/80"
- >
- <MagnifyingGlass size={14} className="shrink-0" />
- <span className="min-w-0 flex-1 truncate text-left text-[13px]">
- Search
- </span>
- <Kbd className="shrink-0 rounded-xs opacity-60">
- {formatHotkey(SHORTCUTS.COMMAND_MENU)}
- </Kbd>
- </button>
- </div>
- );
-}
diff --git a/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.test.ts b/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.test.ts
index 103a75c53be7..dc2906d103a3 100644
--- a/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.test.ts
+++ b/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
getShortcutsByCategory,
KEYBOARD_SHORTCUTS,
+ panelTabShortcut,
SHORTCUTS,
} from "./keyboard-shortcuts";
@@ -12,9 +13,9 @@ function idsFor(channelsLayout: boolean): string[] {
}
describe("getShortcutsByCategory", () => {
- it("advertises channel switching only in the channels layout", () => {
- expect(idsFor(true)).toContain("switch-starred-channel");
- expect(idsFor(false)).not.toContain("switch-starred-channel");
+ it("advertises tab switching only in the channels layout", () => {
+ expect(idsFor(true)).toContain("switch-browser-tab");
+ expect(idsFor(false)).not.toContain("switch-browser-tab");
});
it.each(["switch-task", "new-tab"])(
@@ -68,4 +69,13 @@ describe("SHORTCUTS", () => {
it("offers nine channel slots", () => {
expect(SHORTCUTS.SWITCH_STARRED_CHANNEL.split(",")).toHaveLength(9);
});
+
+ it("keeps browser and inner-panel tab shortcuts distinct off macOS", () => {
+ expect(panelTabShortcut(true)).toBe(
+ "ctrl+1,ctrl+2,ctrl+3,ctrl+4,ctrl+5,ctrl+6,ctrl+7,ctrl+8,ctrl+9",
+ );
+ expect(panelTabShortcut(false)).toBe(
+ "alt+1,alt+2,alt+3,alt+4,alt+5,alt+6,alt+7,alt+8,alt+9",
+ );
+ });
});
diff --git a/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts b/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts
index 52bd370fb1ac..b37d254c00c9 100644
--- a/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts
+++ b/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts
@@ -1,5 +1,13 @@
import { isMac } from "@posthog/ui/utils/platform";
+export function panelTabShortcut(macPlatform: boolean): string {
+ const modifier = macPlatform ? "ctrl" : "alt";
+ return Array.from(
+ { length: 9 },
+ (_, index) => `${modifier}+${index + 1}`,
+ ).join(",");
+}
+
export const SHORTCUTS = {
COMMAND_MENU: "mod+k",
NEW_TASK: "mod+n",
@@ -19,13 +27,17 @@ export const SHORTCUTS = {
NEXT_TASK: "mod+shift+],ctrl+tab",
ARCHIVE_TASK: "mod+shift+a",
CLOSE_TAB: "mod+w",
- SWITCH_TAB: "ctrl+1,ctrl+2,ctrl+3,ctrl+4,ctrl+5,ctrl+6,ctrl+7,ctrl+8,ctrl+9",
+ SWITCH_TAB: panelTabShortcut(isMac),
SWITCH_TASK: "mod+1,mod+2,mod+3,mod+4,mod+5,mod+6,mod+7,mod+8,mod+9",
// No mod+0: the Electron View menu owns CmdOrCtrl+0 for "Actual Size", and a
// renderer preventDefault can't reliably beat a main-process accelerator. The
// personal space takes slot 1 instead.
SWITCH_STARRED_CHANNEL:
"mod+1,mod+2,mod+3,mod+4,mod+5,mod+6,mod+7,mod+8,mod+9",
+ // Same keys as SWITCH_STARRED_CHANNEL / SWITCH_TASK, claimed by the tab strip
+ // wherever it is shown; those two are disabled there so the keys have one
+ // owner at a time.
+ SWITCH_BROWSER_TAB: "mod+1,mod+2,mod+3,mod+4,mod+5,mod+6,mod+7,mod+8,mod+9",
FOCUS_SPACE_SEARCH: "mod+shift+s",
TOGGLE_FOCUS: "mod+r",
PASTE_AS_FILE: "mod+shift+v",
@@ -139,11 +151,11 @@ export const KEYBOARD_SHORTCUTS: KeyboardShortcut[] = [
availability: "no-channels-layout",
},
{
- id: "switch-starred-channel",
+ id: "switch-browser-tab",
keys: "mod+1-9",
- description: "Switch to space (⌘1 = personal, ⌘2-9 = starred)",
+ description: "Switch to tab (9 = last tab)",
category: "navigation",
- context: "Spaces",
+ context: "Tabs",
availability: "channels-layout",
},
{
@@ -223,7 +235,7 @@ export const KEYBOARD_SHORTCUTS: KeyboardShortcut[] = [
},
{
id: "switch-tab",
- keys: "ctrl+1-9",
+ keys: isMac ? "ctrl+1-9" : "alt+1-9",
description: "Switch to tab 1-9",
category: "panels",
context: "Task detail",
diff --git a/products/desktop/packages/ui/src/features/feature-flags/useSpacesTabs.ts b/products/desktop/packages/ui/src/features/feature-flags/useSpacesTabs.ts
new file mode 100644
index 000000000000..d0f39d6d2d0e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/feature-flags/useSpacesTabs.ts
@@ -0,0 +1,17 @@
+import { SPACES_TABS_FLAG } from "@posthog/shared";
+import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+
+/**
+ * Whether the tab strip is shown inside the spaces layout. Read this rather
+ * than the raw flag, so the spaces-layout requirement lives in one place.
+ *
+ * Only the strip is gated. The per-tab model underneath it is unconditional:
+ * with the strip hidden the window simply holds one tab, which behaves the way
+ * the window-global state did before it.
+ */
+export function useSpacesTabs(): boolean {
+ const spacesLayout = useChannelsLayout();
+ const enabled = useFeatureFlag(SPACES_TABS_FLAG, import.meta.env.DEV);
+ return spacesLayout && enabled;
+}
diff --git a/products/desktop/packages/ui/src/features/navigation/useActiveSession.ts b/products/desktop/packages/ui/src/features/navigation/useActiveSession.ts
index 718bcb2e79c2..a7af74c53686 100644
--- a/products/desktop/packages/ui/src/features/navigation/useActiveSession.ts
+++ b/products/desktop/packages/ui/src/features/navigation/useActiveSession.ts
@@ -1,5 +1,5 @@
import { useRailSurface } from "@posthog/ui/features/canvas/hooks/useRailSurface";
-import { useActivityDetailStore } from "@posthog/ui/features/canvas/stores/activityDetailStore";
+import { useActivitySelection } from "@posthog/ui/features/canvas/stores/activityDetailStore";
import { useTaskFeedSelectionStore } from "@posthog/ui/features/canvas/stores/taskFeedSelectionStore";
import { useParams } from "@tanstack/react-router";
@@ -14,7 +14,7 @@ export interface ActiveSession {
*/
export function useActiveSession(): ActiveSession {
const { showsActivityDetail } = useRailSurface();
- const selected = useActivityDetailStore((s) => s.selected);
+ const selected = useActivitySelection();
const feedSelected = useTaskFeedSelectionStore((s) => s.selected);
const params = useParams({ strict: false });
diff --git a/products/desktop/packages/ui/src/features/navigation/useReviewInRightPanel.test.ts b/products/desktop/packages/ui/src/features/navigation/useReviewInRightPanel.test.ts
index 4e92cb9a349e..9ced22f44821 100644
--- a/products/desktop/packages/ui/src/features/navigation/useReviewInRightPanel.test.ts
+++ b/products/desktop/packages/ui/src/features/navigation/useReviewInRightPanel.test.ts
@@ -5,6 +5,8 @@ const mocks = vi.hoisted(() => ({
channelsLayout: true,
routeParams: {} as { taskId?: string; channelId?: string },
fullPath: "/spaces/$channelId/tasks/$taskId",
+ /** Activity's picked item, which now rides in the route's search. */
+ search: {} as Record<string, unknown>,
}));
vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({
@@ -15,11 +17,15 @@ vi.mock("@tanstack/react-router", () => ({
useRouterState: ({
select,
}: {
- select: (s: { matches: { fullPath: string }[] }) => unknown;
- }) => select({ matches: [{ fullPath: mocks.fullPath }] }),
+ select: (s: {
+ matches: { fullPath: string; search: Record<string, unknown> }[];
+ }) => unknown;
+ }) =>
+ select({
+ matches: [{ fullPath: mocks.fullPath, search: mocks.search }],
+ }),
}));
-import { useActivityDetailStore } from "@posthog/ui/features/canvas/stores/activityDetailStore";
import { useReviewInRightPanel } from "./useReviewInRightPanel";
describe("useReviewInRightPanel", () => {
@@ -27,7 +33,7 @@ describe("useReviewInRightPanel", () => {
mocks.channelsLayout = true;
mocks.routeParams = {};
mocks.fullPath = "/spaces/$channelId/tasks/$taskId";
- useActivityDetailStore.setState({ selected: null });
+ mocks.search = {};
});
it("hands the review to the panel for a task opened through a space", () => {
@@ -39,9 +45,7 @@ describe("useReviewInRightPanel", () => {
// The regression: no channel in the URL left both surfaces drawing the diff.
it("hands it over for a task read from the activity feed too", () => {
mocks.fullPath = "/activity";
- useActivityDetailStore.setState({
- selected: { id: "a1", taskId: "task-1", channelId: null },
- });
+ mocks.search = { item: "a1", session: "task-1" };
expect(renderHook(() => useReviewInRightPanel()).result.current).toBe(true);
});
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/ProjectSwitcher.tsx b/products/desktop/packages/ui/src/features/sidebar/components/ProjectSwitcher.tsx
index 0d4994e425be..75ef685f5033 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/ProjectSwitcher.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/ProjectSwitcher.tsx
@@ -209,10 +209,10 @@ export function ProjectSwitcher({
render={
isIcon ? (
<Button
- variant="default"
+ variant="outline"
size="icon"
aria-label={projectName}
- className="shrink-0 bg-fill-hover font-semibold text-[11px] text-muted-foreground uppercase hover:bg-fill-selected aria-expanded:bg-fill-active"
+ className="shrink-0 font-semibold text-[11px] text-muted-foreground uppercase hover:bg-fill-selected aria-expanded:bg-fill-active"
>
{projectInitials}
</Button>
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx
index c45065aedd7c..b99d4b2434e8 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx
@@ -1,6 +1,6 @@
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { Theme } from "@radix-ui/themes";
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -22,6 +22,8 @@ const {
navigateToCommandCenter,
navigateToActivity,
openCommandMenu,
+ openSettings,
+ openBrowserTab,
} = vi.hoisted(() => ({
track: vi.fn(),
useAppView: vi.fn(),
@@ -32,6 +34,8 @@ const {
navigateToCommandCenter: vi.fn(),
navigateToActivity: vi.fn(),
openCommandMenu: vi.fn(),
+ openSettings: vi.fn(),
+ openBrowserTab: vi.fn(),
}));
vi.mock("@posthog/ui/shell/analytics", () => ({ track }));
@@ -59,6 +63,12 @@ vi.mock("@posthog/ui/router/navigationBridge", () => ({
navigateToWebsiteSkills: vi.fn(),
}));
vi.mock("@posthog/ui/router/useOpenTask", () => ({ openTaskInput: vi.fn() }));
+vi.mock("@posthog/ui/features/browser-tabs/useOpenBrowserTab", () => ({
+ useOpenBrowserTab: () => openBrowserTab,
+}));
+vi.mock("@posthog/ui/features/settings/hooks/useOpenSettings", () => ({
+ openSettings,
+}));
vi.mock("@posthog/ui/shell/commandMenuStore", () => ({
useCommandMenuStore: (selector: (s: { open: () => void }) => unknown) =>
selector({ open: openCommandMenu }),
@@ -153,6 +163,28 @@ describe("SidebarNavSection", () => {
);
});
+ it("opens a destination in a new tab on Cmd-click", () => {
+ renderNav();
+
+ fireEvent.click(screen.getByRole("button", { name: /Inbox/ }), {
+ metaKey: true,
+ });
+
+ expect(openBrowserTab).toHaveBeenCalledWith("/inbox");
+ expect(navigateToInbox).not.toHaveBeenCalled();
+ });
+
+ it("keeps Settings in the current window on Cmd-click", () => {
+ renderNav();
+
+ fireEvent.click(screen.getByRole("button", { name: /Settings/ }), {
+ metaKey: true,
+ });
+
+ expect(openSettings).toHaveBeenCalledOnce();
+ expect(openBrowserTab).not.toHaveBeenCalled();
+ });
+
it("does not render the Channels mode toggle in navigation", () => {
renderNav();
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx
index e7d1d4a3926b..2fa7fc1d843b 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx
@@ -3,6 +3,7 @@ import {
ANALYTICS_EVENTS,
type SidebarNavItem,
} from "@posthog/shared/analytics-events";
+import { useOpenBrowserTab } from "@posthog/ui/features/browser-tabs/useOpenBrowserTab";
import { useCommandCenterActiveCount } from "@posthog/ui/features/command-center/useCommandCenterActiveCount";
import { useContextLayerFlag } from "@posthog/ui/features/feature-flags/useContextLayerFlag";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
@@ -29,7 +30,7 @@ import { track } from "@posthog/ui/shell/analytics";
import { useCommandMenuStore } from "@posthog/ui/shell/commandMenuStore";
import { Box, Flex } from "@radix-ui/themes";
import { useRouterState } from "@tanstack/react-router";
-import type { ReactNode } from "react";
+import type { MouseEventHandler, ReactNode } from "react";
import { ActivityItem } from "./items/ActivityItem";
import { CommandCenterItem } from "./items/CommandCenterItem";
import { ConfigureItem } from "./items/ConfigureItem";
@@ -63,6 +64,7 @@ export function SidebarNavSection({
commandCenterActiveCount: providedActiveCount,
}: SidebarNavSectionProps = {}) {
const view = useAppView();
+ const openBrowserTab = useOpenBrowserTab();
// Loops stays behind the loops flag; default on in dev so local builds
// keep the nav item. Also gates the per-channel Loops tab (see ChannelTabs).
const loopsEnabled = useFeatureFlag(LOOPS_FLAG, import.meta.env.DEV);
@@ -113,13 +115,24 @@ export function SidebarNavSection({
// depth 1 means the row was clicked inside the expanded More section.
const withNavTrack =
- (item: SidebarNavItem, action: () => void, depth: 0 | 1 = 0) =>
- () => {
+ (
+ item: SidebarNavItem,
+ action: () => void,
+ depth: 0 | 1 = 0,
+ newTab?: { href: string; prepare?: () => void },
+ ): MouseEventHandler<Element> =>
+ (event) => {
track(ANALYTICS_EVENTS.SIDEBAR_NAV_ITEM_CLICKED, {
item,
in_more: depth === 1,
layout: "code",
});
+ if (newTab && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ newTab.prepare?.();
+ openBrowserTab(newTab.href);
+ return;
+ }
action();
};
@@ -150,7 +163,9 @@ export function SidebarNavSection({
<InboxItem
depth={depth}
isActive={isInboxActive}
- onClick={withNavTrack("inbox", navigateToInbox, depth)}
+ onClick={withNavTrack("inbox", navigateToInbox, depth, {
+ href: "/inbox",
+ })}
pullRequestCount={inboxPullRequestCount}
/>
),
@@ -158,7 +173,12 @@ export function SidebarNavSection({
<CommandCenterItem
depth={depth}
isActive={isCommandCenterActive}
- onClick={withNavTrack("command_center", navigateToCommandCenter, depth)}
+ onClick={withNavTrack(
+ "command_center",
+ navigateToCommandCenter,
+ depth,
+ { href: "/command-center" },
+ )}
activeCount={commandCenterActiveCount}
/>
),
@@ -166,7 +186,9 @@ export function SidebarNavSection({
<ActivityItem
depth={depth}
isActive={isActivityActive}
- onClick={withNavTrack("activity", navigateToActivity, depth)}
+ onClick={withNavTrack("activity", navigateToActivity, depth, {
+ href: "/activity",
+ })}
/>
),
configure: (depth) => (
@@ -179,7 +201,9 @@ export function SidebarNavSection({
<LoopsItem
depth={depth}
isActive={isLoopsActive}
- onClick={withNavTrack("loops", navigateToLoops, depth)}
+ onClick={withNavTrack("loops", navigateToLoops, depth, {
+ href: "/loops",
+ })}
/>
),
contexts: (depth) => (
@@ -199,7 +223,7 @@ export function SidebarNavSection({
<Box mb="2">
<NewTaskItem
isActive={isHomeActive}
- onClick={withNavTrack("new_task", goNewTask)}
+ onClick={withNavTrack("new_task", goNewTask, 0, { href: "/new" })}
/>
</Box>
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/ActivityItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/ActivityItem.tsx
index 3e7144bbdb13..6b7df3316099 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/items/ActivityItem.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/ActivityItem.tsx
@@ -2,13 +2,13 @@ import { BellIcon } from "@phosphor-icons/react";
import { Popover, PopoverTrigger } from "@posthog/quill";
import { ActivityHoverCard } from "@posthog/ui/features/canvas/components/ActivityHoverCard";
import { useTaskActivity } from "@posthog/ui/features/canvas/hooks/useTaskActivity";
-import { useRef, useState } from "react";
+import { type MouseEventHandler, useRef, useState } from "react";
import { SidebarItem } from "../SidebarItem";
import { SidebarCountBadge } from "./SidebarCountBadge";
interface ActivityItemProps {
isActive: boolean;
- onClick: () => void;
+ onClick: MouseEventHandler<Element>;
depth?: number;
}
@@ -37,10 +37,10 @@ export function ActivityItem({
</>
}
isActive={isActive}
- onClick={() => {
+ onClick={(event) => {
suppressClickOpenRef.current = true;
setOpen(false);
- onClick();
+ onClick(event);
}}
/>
);
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/CommandCenterItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/CommandCenterItem.tsx
index fe09950ca4af..8181b6310999 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/items/CommandCenterItem.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/CommandCenterItem.tsx
@@ -1,10 +1,11 @@
import { SquaresFourIcon } from "@phosphor-icons/react";
import { CountBadge } from "@posthog/ui/primitives/CountBadge";
+import type { MouseEventHandler } from "react";
import { SidebarItem } from "../SidebarItem";
interface CommandCenterItemProps {
isActive: boolean;
- onClick: () => void;
+ onClick: MouseEventHandler<Element>;
activeCount?: number;
depth?: number;
}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/ConfigureItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/ConfigureItem.tsx
index ba42b595dcc8..789a025fa964 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/items/ConfigureItem.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/ConfigureItem.tsx
@@ -1,8 +1,9 @@
import { GearSix } from "@phosphor-icons/react";
+import type { MouseEventHandler } from "react";
import { SidebarItem } from "../SidebarItem";
interface ConfigureItemProps {
- onClick: () => void;
+ onClick: MouseEventHandler<Element>;
depth?: number;
}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/ContextItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/ContextItem.tsx
index bef60c226336..f1c177d3daf1 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/items/ContextItem.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/ContextItem.tsx
@@ -1,9 +1,10 @@
import { BookOpenTextIcon } from "@phosphor-icons/react";
+import type { MouseEventHandler } from "react";
import { SidebarItem } from "../SidebarItem";
interface ContextItemProps {
isActive: boolean;
- onClick: () => void;
+ onClick: MouseEventHandler<Element>;
depth?: number;
}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/InboxItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/InboxItem.tsx
index b121e69f4413..e182e6908473 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/items/InboxItem.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/InboxItem.tsx
@@ -2,13 +2,14 @@ import { EnvelopeSimple } from "@phosphor-icons/react";
import { Badge } from "@posthog/quill";
import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";
import { Tooltip } from "@posthog/ui/primitives/Tooltip";
+import type { MouseEventHandler } from "react";
import { SidebarItem } from "../SidebarItem";
import { SidebarCountBadge } from "./SidebarCountBadge";
import { SidebarKbdHint } from "./SidebarKbdHint";
interface InboxItemProps {
isActive: boolean;
- onClick: () => void;
+ onClick: MouseEventHandler<Element>;
pullRequestCount?: number;
depth?: number;
}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/LoopsItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/LoopsItem.tsx
index 644a21726801..ef8d204be696 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/items/LoopsItem.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/LoopsItem.tsx
@@ -1,10 +1,11 @@
import { Badge } from "@posthog/quill";
import { LoopIcon } from "@posthog/ui/primitives/LoopIcon";
+import type { MouseEventHandler } from "react";
import { SidebarItem } from "../SidebarItem";
interface LoopsItemProps {
isActive: boolean;
- onClick: () => void;
+ onClick: MouseEventHandler<Element>;
depth?: number;
}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/NewTaskItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/NewTaskItem.tsx
index d232a5c407e1..dd9858ab57a5 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/items/NewTaskItem.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/NewTaskItem.tsx
@@ -3,17 +3,22 @@ import { Badge } from "@posthog/quill";
import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";
import { isContentEmpty } from "@posthog/ui/features/message-editor/content";
import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";
+import { isTaskInputSessionId } from "@posthog/ui/features/task-detail/taskInputSession";
+import type { MouseEventHandler } from "react";
import { SidebarItem } from "../SidebarItem";
import { SidebarKbdHint } from "./SidebarKbdHint";
interface NewTaskItemProps {
isActive: boolean;
- onClick: () => void;
+ onClick: MouseEventHandler<Element>;
}
export function NewTaskItem({ isActive, onClick }: NewTaskItemProps) {
- const hasDraft = useDraftStore(
- (s) => !isContentEmpty(s.drafts["task-input"]),
+ const hasDraft = useDraftStore((state) =>
+ Object.entries(state.drafts).some(
+ ([sessionId, draft]) =>
+ isTaskInputSessionId(sessionId) && !isContentEmpty(draft),
+ ),
);
return (
<SidebarItem
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/SearchItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/SearchItem.tsx
index 6b3c7692d0e3..d33b2cb212dd 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/items/SearchItem.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/SearchItem.tsx
@@ -1,10 +1,11 @@
import { MagnifyingGlass } from "@phosphor-icons/react";
import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";
+import type { MouseEventHandler } from "react";
import { SidebarItem } from "../SidebarItem";
import { SidebarKbdHint } from "./SidebarKbdHint";
interface SearchItemProps {
- onClick: () => void;
+ onClick: MouseEventHandler<Element>;
depth?: number;
}
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/NewTaskScreen.tsx b/products/desktop/packages/ui/src/features/task-detail/components/NewTaskScreen.tsx
index 1c24123f0b9c..8956f07ce14c 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/NewTaskScreen.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/NewTaskScreen.tsx
@@ -1,7 +1,9 @@
import { CHANNEL_TASK_SUGGESTIONS } from "@posthog/ui/features/canvas/channelTaskSuggestions";
import { useChannelsWorld } from "@posthog/ui/features/canvas/hooks/useChannelsWorld";
import { TaskInput } from "@posthog/ui/features/task-detail/components/TaskInput";
+import { getTaskInputSessionId } from "@posthog/ui/features/task-detail/taskInputSession";
import { useAppView } from "@posthog/ui/router/useAppView";
+import { useRouterState } from "@tanstack/react-router";
/**
* The unscoped new-task screen, wired to the router's prefill. Two routes reach
@@ -11,9 +13,15 @@ import { useAppView } from "@posthog/ui/router/useAppView";
export function NewTaskScreen() {
const view = useAppView();
const channelsWorld = useChannelsWorld();
+ const tabId = useRouterState({
+ select: (state) => state.location.state.tabId,
+ });
+ const sessionId = getTaskInputSessionId(tabId);
return (
<TaskInput
+ key={sessionId}
+ sessionId={sessionId}
initialPrompt={view.initialPrompt}
initialPromptKey={view.taskInputRequestId}
initialCloudRepository={view.initialCloudRepository}
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
index f33c8b077cab..3325dc1200b3 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
@@ -123,6 +123,7 @@ import { type WorkspaceMode, WorkspaceModeSelect } from "./WorkspaceModeSelect";
interface TaskInputProps {
sessionId?: string;
onTaskCreated?: (task: Task) => void;
+ onTaskCreatedEffect?: (task: Task) => void;
initialPrompt?: string;
initialPromptKey?: string;
initialCloudRepository?: string;
@@ -190,6 +191,7 @@ interface TaskInputProps {
export function TaskInput({
sessionId = "task-input",
onTaskCreated,
+ onTaskCreatedEffect,
initialPrompt,
initialPromptKey,
initialCloudRepository,
@@ -993,6 +995,14 @@ export function TaskInput({
[autoresearchService],
);
+ const handleTaskCreatedEffect = useCallback(
+ (task: Task) => {
+ handleAutoresearchTaskCreated(task);
+ onTaskCreatedEffect?.(task);
+ },
+ [handleAutoresearchTaskCreated, onTaskCreatedEffect],
+ );
+
const {
isCreatingTask,
isExitingComposer,
@@ -1021,7 +1031,7 @@ export function TaskInput({
contextWindow: runtime === "pi" ? undefined : currentContextWindow,
fastMode: runtime === "pi" ? undefined : currentFastMode,
onTaskCreated,
- onTaskCreatedEffect: handleAutoresearchTaskCreated,
+ onTaskCreatedEffect: handleTaskCreatedEffect,
environmentId: selectedEnvironment,
sandboxEnvironmentId:
effectiveWorkspaceMode === "cloud" && selectedCloudEnvId
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
index 17cafd434cf7..d4af940f1458 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
@@ -20,13 +20,17 @@ import {
type WorkspaceMode,
} from "@posthog/shared";
import type { ExecutionMode, Task } from "@posthog/shared/domain-types";
+import {
+ getCurrentBrowserTabId,
+ navigateBrowserTab,
+} from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
import { useTaskChannels } from "@posthog/ui/features/canvas/hooks/useTaskChannels";
import { useTaskRepositoryDraftStore } from "@posthog/ui/features/canvas/stores/taskRepositoryDraftStore";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import { waitForComposerExit } from "@posthog/ui/features/task-detail/newTaskComposerTransition";
import { useTaskInputPrefillStore } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";
import { navigateToTaskPending } from "@posthog/ui/router/navigationBridge";
-import { openTask, openTaskInput } from "@posthog/ui/router/useOpenTask";
+import { openTask } from "@posthog/ui/router/useOpenTask";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useState } from "react";
import { useConnectivity } from "../../../hooks/useConnectivity";
@@ -63,6 +67,7 @@ import { useTourStore } from "../../tour/tourStore";
import { createFirstTaskTour } from "../../tour/tours/createFirstTaskTour";
import { useExistingWorktreeConfirmStore } from "../stores/existingWorktreeConfirmStore";
import { useRemoteBranchConfirmStore } from "../stores/remoteBranchConfirmStore";
+import { restoreTaskInputTab } from "../taskInputTab";
const log = logger.scope("task-creation");
@@ -267,6 +272,15 @@ export function useTaskCreation({
const allowSubmit = contentOverride ? canSubmitBase : canSubmit;
if (!allowSubmit) return false;
+ // Capture everything owned by the mounted composer before the first
+ // await. Switching tabs unmounts it, but task creation must continue with
+ // the exact prompt and tab that the user submitted.
+ const originTabId = getCurrentBrowserTabId();
+ const content = contentOverride ?? editor.getContent();
+ const plainPromptText = contentToPlainText(content).trim();
+ const serializedContent = contentToXml(content).trim();
+ const filePaths = extractFilePaths(content);
+
// Held for the whole submit, pre-flight awaits included, so a second
// Enter lands after `canSubmitBase` has already gone false.
setIsCreatingTask(true);
@@ -335,11 +349,6 @@ export function useTaskCreation({
}
}
- const content = contentOverride ?? editor.getContent();
- const plainPromptText = contentToPlainText(content).trim();
- const serializedContent = contentToXml(content).trim();
- const filePaths = extractFilePaths(content);
-
const shouldShowPendingView = !onTaskCreated && !!plainPromptText;
const pendingTaskKey = shouldShowPendingView
? generatePendingTaskKey()
@@ -357,19 +366,22 @@ export function useTaskCreation({
// hand over instead of cutting.
setIsExitingComposer(true);
await waitForComposerExit();
- navigateToTaskPending(pendingTaskKey);
- if (!contentOverride) {
- editor.clear();
- }
+ navigateBrowserTab(
+ originTabId,
+ {
+ href: `/tasks/pending/${pendingTaskKey}`,
+ title: "New task",
+ },
+ () => navigateToTaskPending(pendingTaskKey),
+ );
}
let createdTaskId: string | undefined;
try {
if (!contentOverride) {
- const plainText = editor.getText()?.trim() ?? plainPromptText;
- if (plainText) {
- useTaskInputHistoryStore.getState().addPrompt(plainText);
+ if (plainPromptText) {
+ useTaskInputHistoryStore.getState().addPrompt(plainPromptText);
}
}
@@ -455,11 +467,16 @@ export function useTaskCreation({
if (pendingTaskKey) {
pendingTaskPromptStoreApi.move(pendingTaskKey, output.task.id);
}
- // Clear the draft BEFORE navigating away. When onTaskCreated
- // navigates (e.g. channels), it can synchronously unmount/destroy
- // the editor; clearing afterwards would throw in clearContent()
- // before the persisted draft is wiped, leaving stale text behind.
- if (!pendingTaskKey && !contentOverride) {
+ // Clear only the editor that submitted. The same component can
+ // render another browser tab before this callback runs; clearing
+ // it would erase that tab's draft. The origin's persisted draft
+ // is cleared by session id after task creation succeeds.
+ if (
+ !pendingTaskKey &&
+ !contentOverride &&
+ editorRef.current === editor &&
+ getCurrentBrowserTabId() === originTabId
+ ) {
editor.clear();
}
if (defaultedChannelId) {
@@ -475,7 +492,10 @@ export function useTaskCreation({
if (onTaskCreated) {
onTaskCreated(output.task);
} else {
- void openTask(output.task);
+ void openTask(output.task, {
+ channelId,
+ tabId: originTabId,
+ });
}
useTourStore.getState().completeTour(createFirstTaskTour.id);
// Pre-flight already ran above for cloud; skip the service's duplicate check.
@@ -555,7 +575,7 @@ export function useTaskCreation({
if (createdTaskId) {
pendingTaskPromptStoreApi.clear(createdTaskId);
}
- openTaskInput({ initialPrompt: plainPromptText });
+ restoreTaskInputTab(originTabId, channelContextId ?? channelId);
}
}
return result.success;
@@ -570,7 +590,7 @@ export function useTaskCreation({
if (createdTaskId) {
pendingTaskPromptStoreApi.clear(createdTaskId);
}
- openTaskInput({ initialPrompt: plainPromptText });
+ restoreTaskInputTab(originTabId, channelContextId ?? channelId);
}
return false;
}
diff --git a/products/desktop/packages/ui/src/features/task-detail/taskInputSession.test.ts b/products/desktop/packages/ui/src/features/task-detail/taskInputSession.test.ts
new file mode 100644
index 000000000000..3a49ddcf02c5
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/task-detail/taskInputSession.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+import {
+ getTaskInputSessionId,
+ isTaskInputSessionId,
+} from "./taskInputSession";
+
+describe("task input sessions", () => {
+ it("gives each browser tab an independent draft session", () => {
+ const first = getTaskInputSessionId("tab-a");
+ const second = getTaskInputSessionId("tab-b");
+
+ expect(first).not.toBe(second);
+ expect(isTaskInputSessionId(first)).toBe(true);
+ expect(isTaskInputSessionId(second)).toBe(true);
+ expect(getTaskInputSessionId(null)).toBe("task-input");
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/task-detail/taskInputSession.ts b/products/desktop/packages/ui/src/features/task-detail/taskInputSession.ts
new file mode 100644
index 000000000000..0314d5a2fe2e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/task-detail/taskInputSession.ts
@@ -0,0 +1,16 @@
+export const DEFAULT_TASK_INPUT_SESSION_ID = "task-input";
+
+export function getTaskInputSessionId(
+ tabId: string | null | undefined,
+): string {
+ return tabId
+ ? `${DEFAULT_TASK_INPUT_SESSION_ID}:${tabId}`
+ : DEFAULT_TASK_INPUT_SESSION_ID;
+}
+
+export function isTaskInputSessionId(sessionId: string): boolean {
+ return (
+ sessionId === DEFAULT_TASK_INPUT_SESSION_ID ||
+ sessionId.startsWith(`${DEFAULT_TASK_INPUT_SESSION_ID}:`)
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/task-detail/taskInputTab.test.ts b/products/desktop/packages/ui/src/features/task-detail/taskInputTab.test.ts
new file mode 100644
index 000000000000..ce640f5efd02
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/task-detail/taskInputTab.test.ts
@@ -0,0 +1,51 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ navigateBrowserTab: vi.fn(),
+ openTaskInput: vi.fn(),
+}));
+
+vi.mock("@posthog/ui/features/browser-tabs/imperativeTabNavigation", () => ({
+ navigateBrowserTab: mocks.navigateBrowserTab,
+}));
+vi.mock("@posthog/ui/router/useOpenTask", () => ({
+ openTaskInput: mocks.openTaskInput,
+}));
+
+import { restoreTaskInputTab } from "./taskInputTab";
+
+describe("restoreTaskInputTab", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("restores a failed space task to its original space", () => {
+ restoreTaskInputTab("tab-1", "space-1");
+
+ expect(mocks.navigateBrowserTab).toHaveBeenCalledWith(
+ "tab-1",
+ {
+ href: "/spaces/space-1/new",
+ title: "New task",
+ channelId: "space-1",
+ },
+ expect.any(Function),
+ );
+
+ const navigateActiveTab = mocks.navigateBrowserTab.mock.calls[0]?.[2];
+ navigateActiveTab();
+ expect(mocks.openTaskInput).toHaveBeenCalledWith({ channelId: "space-1" });
+ });
+
+ it("restores an unscoped task to the Code composer", () => {
+ restoreTaskInputTab("tab-1");
+
+ const [, destination, navigateActiveTab] =
+ mocks.navigateBrowserTab.mock.calls[0];
+ expect(destination).toEqual({
+ href: "/new",
+ title: "New task",
+ channelId: undefined,
+ });
+ navigateActiveTab();
+ expect(mocks.openTaskInput).toHaveBeenCalledWith({ unscoped: true });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/task-detail/taskInputTab.ts b/products/desktop/packages/ui/src/features/task-detail/taskInputTab.ts
new file mode 100644
index 000000000000..bcae5ca798a3
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/task-detail/taskInputTab.ts
@@ -0,0 +1,17 @@
+import { navigateBrowserTab } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
+import { openTaskInput } from "@posthog/ui/router/useOpenTask";
+
+export function restoreTaskInputTab(
+ tabId: string | null,
+ spaceId?: string,
+): void {
+ navigateBrowserTab(
+ tabId,
+ {
+ href: spaceId ? `/spaces/${spaceId}/new` : "/new",
+ title: "New task",
+ channelId: spaceId,
+ },
+ () => openTaskInput(spaceId ? { channelId: spaceId } : { unscoped: true }),
+ );
+}
diff --git a/products/desktop/packages/ui/src/router/routes/__root.tsx b/products/desktop/packages/ui/src/router/routes/__root.tsx
index 7b28265e5c9d..30badd2a723b 100644
--- a/products/desktop/packages/ui/src/router/routes/__root.tsx
+++ b/products/desktop/packages/ui/src/router/routes/__root.tsx
@@ -14,22 +14,18 @@ import { useServerArchiveSync } from "@posthog/ui/features/archive/useServerArch
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
import { UsageButton } from "@posthog/ui/features/billing/UsageButton";
import { UsageLimitModal } from "@posthog/ui/features/billing/UsageLimitModal";
-import { BlankTabView } from "@posthog/ui/features/browser-tabs/BlankTabView";
import { BrowserTabStrip } from "@posthog/ui/features/browser-tabs/BrowserTabStrip";
import { BrowserTabsDndProvider } from "@posthog/ui/features/browser-tabs/BrowserTabsDnd";
import { TabShortcutFallback } from "@posthog/ui/features/browser-tabs/TabShortcutFallback";
-import { useActiveTabIsBlank } from "@posthog/ui/features/browser-tabs/useBrowserTabs";
import { isBluebirdOnlyPath } from "@posthog/ui/features/canvas/bluebirdRoutes";
import { ChannelHotkeys } from "@posthog/ui/features/canvas/components/ChannelHotkeys";
import { ChannelRouteSync } from "@posthog/ui/features/canvas/components/ChannelRouteSync";
import { ChannelsSidebar } from "@posthog/ui/features/canvas/components/ChannelsSidebar";
-import { useChannelsSidebarStore } from "@posthog/ui/features/canvas/components/channelsSidebarStore";
import {
FeedbackModal,
type FeedbackModalMode,
} from "@posthog/ui/features/canvas/components/FeedbackModal";
import { NavRail } from "@posthog/ui/features/canvas/components/NavRail";
-import { RailHistorySync } from "@posthog/ui/features/canvas/components/RailHistorySync";
import { useCanvasDeepLink } from "@posthog/ui/features/canvas/hooks/useCanvasDeepLink";
import { useChannelDeepLink } from "@posthog/ui/features/canvas/hooks/useChannelDeepLink";
import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
@@ -39,7 +35,6 @@ import { useShareLinkInterceptor } from "@posthog/ui/features/canvas/hooks/useSh
import { useShellOwnsHeader } from "@posthog/ui/features/canvas/hooks/useShellOwnsHeader";
import { usePostHogWebFeedbackStore } from "@posthog/ui/features/canvas/stores/posthogWebFeedbackStore";
import { CommandMenu } from "@posthog/ui/features/command/CommandMenu";
-import { CommandSearchBar } from "@posthog/ui/features/command/CommandSearchBar";
import { GlobalFilePicker } from "@posthog/ui/features/command/GlobalFilePicker";
import { KeyboardShortcutsSheet } from "@posthog/ui/features/command/KeyboardShortcutsSheet";
import { ConnectivityBanner } from "@posthog/ui/features/connectivity/ConnectivityBanner";
@@ -47,12 +42,12 @@ import { useNewTaskDeepLink } from "@posthog/ui/features/deep-links/useNewTaskDe
import { useOpenTargetDeepLink } from "@posthog/ui/features/deep-links/useOpenTargetDeepLink";
import { useTaskDeepLink } from "@posthog/ui/features/deep-links/useTaskDeepLink";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+import { useSpacesTabs } from "@posthog/ui/features/feature-flags/useSpacesTabs";
import { useInboxDeepLink } from "@posthog/ui/features/inbox/hooks/useInboxDeepLink";
import { useIntegrations } from "@posthog/ui/features/integrations/useIntegrations";
import { useLoopDeepLink } from "@posthog/ui/features/loops/hooks/useLoopDeepLink";
import { useScoutDeepLink } from "@posthog/ui/features/scouts/hooks/useScoutDeepLink";
import { useSetupDiscovery } from "@posthog/ui/features/setup/useSetupDiscovery";
-import { NAV_RAIL_WIDTH } from "@posthog/ui/features/sidebar/constants";
import {
beginSidebarPeek,
cancelSidebarPeek,
@@ -118,9 +113,6 @@ function RootLayout() {
// Cloud-only hosts (web) run in a real browser tab that already provides
// native back/forward chrome, so the in-app history buttons are redundant.
const { localWorkspaces } = useHostCapabilities();
- // Width of the Channels sidebar below — used to right-align the back/forward
- // buttons in the title bar with the sidebar's (and project switcher's) right edge.
- const channelsSidebarWidth = useChannelsSidebarStore((state) => state.width);
// Forward availability isn't exposed by the router (and history.length counts
// pre-app entries, so it can't be compared to __TSR_index). Track the newest
// index we've reached: only a PUSH wipes the forward stack, so it resets the
@@ -212,6 +204,10 @@ function RootLayout() {
// The new channels layout has exactly one gate: its feature flag (no
// sidebar toggle). When on it subsumes the channels alpha entirely.
const channelsLayout = useChannelsLayout();
+ // Tabs exist in the legacy layout already; the flag gates only bringing them
+ // into the spaces layout.
+ const spacesTabs = useSpacesTabs();
+ const showTabStrip = channelsLayout ? spacesTabs : true;
const { hasSidebar } = useRailSurface();
// When the sidebar is collapsed (Cmd+B) the title bar's left block shrinks to
// fit its own controls so the tab strip flushes left with the content pane.
@@ -310,16 +306,6 @@ function RootLayout() {
}
}, [flagsLoaded, bluebirdEnabled, onBluebirdOnlyPath]);
- // A blank browser tab (the "+" new-tab page) shows an empty placeholder — but
- // ONLY on the spaces index. Inside a space (`/spaces/$channelId…`) the route
- // owns the content (space feed, artifacts, a canvas, …), so the placeholder
- // must never replace it, otherwise space navigation looks dead.
- const onSpacesIndex = useRouterState({
- select: (s) => s.location.pathname === "/spaces",
- });
- const activeTabBlank = useActiveTabIsBlank();
- const showBlankTab = onSpacesIndex && activeTabBlank;
-
if (isSettingsRoute) {
return (
<Flex direction="column" height="100%">
@@ -357,11 +343,10 @@ function RootLayout() {
<BrowserTabsDndProvider>
<Flex direction="column" height="100%" className="bg-chrome">
{/* Full-width title bar: a window-drag region carrying the PostHog
- mark. The left section matches the sidebar width so the tab strip
- starts flush with the content pane; its padding clears the macOS
- stoplights via env(titlebar-area-x), the system-reported right
- edge of the traffic-light strip (see titleBarOverlay in
- window.ts). */}
+ mark. The left section sizes to its controls so the tab strip sits
+ beside the history buttons; its padding clears the macOS stoplights
+ via env(titlebar-area-x), the system-reported right edge of the
+ traffic-light strip (see titleBarOverlay in window.ts). */}
<Flex
align="center"
className="drag h-10 shrink-0"
@@ -380,9 +365,6 @@ function RootLayout() {
// over- or under-shoots; the env var fallback covers hosts
// without Window Controls Overlay.
paddingLeft: isMac ? "env(titlebar-area-x, 78px)" : "78px",
- width: sidebarDocked
- ? channelsSidebarWidth + (channelsLayout ? NAV_RAIL_WIDTH : 0)
- : undefined,
}}
>
<Flex align="center" gap="2" className="no-drag">
@@ -427,18 +409,11 @@ function RootLayout() {
</ButtonGroup>
)}
</Flex>
- {/* The new layout has no global tab strip (tabs live inside the
- task view); inbox/activity live in the sidebar nav. The strip is
- also the only global owner of Cmd+W, so something has to keep
- holding that key when it isn't mounted. */}
- {channelsLayout ? (
- <>
- <TabShortcutFallback enabled />
- <CommandSearchBar onClick={toggleCommandMenu} />
- </>
- ) : (
- <BrowserTabStrip />
- )}
+ {/* The strip owns the title bar's middle in both layouts. Search
+ moved to the rail to make room for it (see NavRail). The strip is
+ also the only global owner of Cmd+W, so the fallback has to hold
+ that key wherever the strip isn't mounted. */}
+ {showTabStrip ? <BrowserTabStrip /> : <TabShortcutFallback enabled />}
{/* Gated so an empty right-side group can't claim a no-drag rect
in the title bar for nothing — every pixel without controls
should drag the window. */}
@@ -504,7 +479,7 @@ function RootLayout() {
and, on a task, its action row. */}
{!shellOwnsHeader && <ContentHeader />}
<Box flexGrow="1" overflow="hidden">
- {showBlankTab ? <BlankTabView /> : <Outlet />}
+ <Outlet />
</Box>
</Flex>
</Box>
@@ -530,9 +505,6 @@ function RootLayout() {
but the rail can take that column away and the scoping still has to
happen. */}
<ChannelRouteSync />
- {/* Renders nothing — remembers where each rail destination was, so a
- pick returns you there rather than to its index. */}
- <RailHistorySync />
{/* Renders nothing — wires the ⌥↑/⌥↓ task-cycling shortcuts. */}
<SpaceSwitcher
tasks={visualTaskOrder}
diff --git a/products/desktop/packages/ui/src/router/routes/_shell/activity.tsx b/products/desktop/packages/ui/src/router/routes/_shell/activity.tsx
index eb6938c59f39..ccb0765d9369 100644
--- a/products/desktop/packages/ui/src/router/routes/_shell/activity.tsx
+++ b/products/desktop/packages/ui/src/router/routes/_shell/activity.tsx
@@ -1,11 +1,19 @@
import { ActivityDetailPane } from "@posthog/ui/features/canvas/components/ActivityDetailPane";
import { ActivityView } from "@posthog/ui/features/canvas/components/ActivityView";
import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
+import {
+ type ActivitySearch,
+ parseActivitySearch,
+} from "@posthog/ui/features/canvas/stores/activityDetailStore";
import { createFileRoute } from "@tanstack/react-router";
// Activity: every task the viewer is involved in — created, @-mentioned in, or
// messaged in — across spaces. The rail's Activity badge counts what's new here.
export const Route = createFileRoute("/_shell/activity")({
+ // The picked item lives in the search rather than a store, so the location
+ // says what the pane is showing: a tab can then name it and restore it.
+ validateSearch: (search: Record<string, unknown>): ActivitySearch =>
+ parseActivitySearch(search),
component: ActivityRoute,
});
diff --git a/products/desktop/packages/ui/src/router/useOpenTask.ts b/products/desktop/packages/ui/src/router/useOpenTask.ts
index 723eb2528684..c84f03f15e79 100644
--- a/products/desktop/packages/ui/src/router/useOpenTask.ts
+++ b/products/desktop/packages/ui/src/router/useOpenTask.ts
@@ -1,6 +1,7 @@
import { resolveService, resolveServiceOptional } from "@posthog/di/container";
import { ANALYTICS_EVENTS } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
+import { navigateBrowserTab } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";
import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";
import {
NAVIGATION_TASK_BINDER,
@@ -32,7 +33,7 @@ import * as nav from "./navigationBridge";
*/
export async function openTask(
task: Task,
- opts?: { channelId?: string },
+ opts?: { channelId?: string; tabId?: string | null },
): Promise<void> {
// Seed the detail cache so the route loader resolves from cache and never
// fetches — critical for optimistic/local/cloud-pending tasks that the API
@@ -41,19 +42,43 @@ export async function openTask(
taskDetailQuery(task.id).queryKey,
task,
);
- if (opts?.channelId) {
- nav.navigateToChannelTask(opts.channelId, task.id);
- } else {
- nav.navigateToTaskDetail(task.id);
+ const href = opts?.channelId
+ ? `/spaces/${opts.channelId}/tasks/${task.id}`
+ : `/tasks/${task.id}`;
+ const navigationResult = navigateBrowserTab(
+ opts?.tabId ?? null,
+ {
+ href,
+ title: task.title,
+ taskId: task.id,
+ channelId: opts?.channelId ?? null,
+ },
+ () => {
+ if (opts?.channelId) {
+ nav.navigateToChannelTask(opts.channelId, task.id);
+ } else {
+ nav.navigateToTaskDetail(task.id);
+ }
+ },
+ );
+ if (navigationResult === "active") {
+ setActiveTaskContext(task);
+ track(ANALYTICS_EVENTS.TASK_VIEWED, { task_id: task.id });
}
- setActiveTaskContext(task);
- track(ANALYTICS_EVENTS.TASK_VIEWED, { task_id: task.id });
const result = await resolveServiceOptional<NavigationTaskBinder>(
NAVIGATION_TASK_BINDER,
)?.ensureWorkspaceForTask(task);
- if (result?.staleFolderId) {
- nav.navigateToFolderSettings(result.staleFolderId);
+ const staleFolderId = result?.staleFolderId;
+ if (staleFolderId) {
+ navigateBrowserTab(
+ opts?.tabId ?? null,
+ {
+ href: `/folders/${staleFolderId}`,
+ title: "Folder settings",
+ },
+ () => nav.navigateToFolderSettings(staleFolderId),
+ );
}
}
diff --git a/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx b/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx
index 53c1541f52f7..bc062b0e29a8 100644
--- a/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx
+++ b/products/desktop/packages/ui/src/shell/GlobalEventHandlers.tsx
@@ -14,6 +14,7 @@ import { getDefaultReviewMode } from "@posthog/ui/features/code-review/getDefaul
import { useReviewNavigationStore } from "@posthog/ui/features/code-review/reviewNavigationStore";
import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+import { useSpacesTabs } from "@posthog/ui/features/feature-flags/useSpacesTabs";
import { useFolders } from "@posthog/ui/features/folders/useFolders";
import { toggleRightPanel } from "@posthog/ui/features/navigation/rightPanelSide";
import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";
@@ -80,7 +81,7 @@ export function GlobalEventHandlers({
);
const isWorktreeTask = currentWorkspace?.mode === "worktree";
- // mod+N belongs to the browser tab strip with channels on, and to the
+ // mod+1-9 belongs to the browser tab strip with tabs mounted, and to the
// starred channels in the new layout (ChannelHotkeys, mounted from __root so
// the keys always have an owner), so task-switching only owns those keys in
// the Code nav.
@@ -91,6 +92,8 @@ export function GlobalEventHandlers({
const channelsEnabled =
useSidebarStore((s) => s.channelsEnabled) && bluebirdEnabled;
const channelsLayout = useChannelsLayout();
+ const spacesTabs = useSpacesTabs();
+ const browserTabStripMounted = channelsLayout ? spacesTabs : true;
const taskById = useMemo(() => {
const map = new Map<string, Task>();
@@ -238,8 +241,8 @@ export function GlobalEventHandlers({
[handleToggleFocus],
);
- // Task switching with mod+1-9 — off when channels are on (the browser tab
- // strip / starred-channel shortcuts claim those keys).
+ // Task switching with mod+1-9 — off when the browser tab strip or starred
+ // channel shortcuts claim those keys.
useHotkeys(
SHORTCUTS.SWITCH_TASK,
(event, handler) => {
@@ -250,7 +253,10 @@ export function GlobalEventHandlers({
const index = parseInt(keyPressed, 10);
handleSwitchTask(index);
},
- { ...globalOptions, enabled: !channelsEnabled && !channelsLayout },
+ {
+ ...globalOptions,
+ enabled: !channelsEnabled && !browserTabStripMounted,
+ },
[handleSwitchTask],
);
diff --git a/products/desktop/packages/ui/src/shell/startupLocation.test.ts b/products/desktop/packages/ui/src/shell/startupLocation.test.ts
index b99c55be0e8a..4a1e3ff7003f 100644
--- a/products/desktop/packages/ui/src/shell/startupLocation.test.ts
+++ b/products/desktop/packages/ui/src/shell/startupLocation.test.ts
@@ -1,3 +1,4 @@
+import { rewriteSavedLocation } from "@posthog/shared";
import type { ProvisionedTaskChannels } from "@posthog/shared/domain-types";
import { stateStorage } from "@posthog/ui/shell/rendererStorage";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -26,6 +27,36 @@ const general = {
let identityCounter = 0;
let identity = "project";
+describe("rewriteSavedLocation", () => {
+ // A saved location is a raw href, so an install that last quit before the
+ // routes were flattened would otherwise reopen on a route that is gone.
+ it.each([
+ ["/website", "/spaces"],
+ ["/website/eng", "/spaces/eng"],
+ ["/website/eng/loops", "/spaces/eng/loops"],
+ ["/website/home", "/"],
+ ["/website/activity", "/activity"],
+ ["/website/activity?taskId=task-1", "/activity?taskId=task-1"],
+ ["/website/home#recent", "/#recent"],
+ ["/website/command-center", "/command-center"],
+ ["/website/new", "/new"],
+ ["/code", "/new"],
+ ["/code/inbox/pulls/42", "/inbox/pulls/42"],
+ ["/code/inbox?filter=mine", "/inbox?filter=mine"],
+ ["/code/loops/abc/edit", "/loops/abc/edit"],
+ ["/code/tasks/t1", "/tasks/t1"],
+ ])("moves %s to %s", (saved, expected) => {
+ expect(rewriteSavedLocation(saved)).toBe(expected);
+ });
+
+ it.each(["/spaces/eng", "/inbox", "/settings/general", "/"])(
+ "leaves %s alone",
+ (href) => {
+ expect(rewriteSavedLocation(href)).toBe(href);
+ },
+ );
+});
+
describe("startup location", () => {
beforeEach(() => {
identityCounter += 1;
diff --git a/products/desktop/packages/workspace-server/src/db/migrate.test.ts b/products/desktop/packages/workspace-server/src/db/migrate.test.ts
index 279aa2314077..439b76fae7eb 100644
--- a/products/desktop/packages/workspace-server/src/db/migrate.test.ts
+++ b/products/desktop/packages/workspace-server/src/db/migrate.test.ts
@@ -62,6 +62,9 @@ describe("runMigrations", () => {
runMigrations(sqlite, MIGRATIONS_FOLDER);
expect(hasColumn(sqlite, "workspaces", "pr_urls")).toBe(true);
+ // A migration whose journal entry is missing or mismatched applies no
+ // statements and fails silently; the column it adds is how that shows up.
+ expect(hasColumn(sqlite, "browser_tabs", "href")).toBe(true);
expect(ledgerMax(sqlite)).not.toBeNull();
});
diff --git a/products/desktop/packages/workspace-server/src/db/migrations/0023_browser_tab_href.sql b/products/desktop/packages/workspace-server/src/db/migrations/0023_browser_tab_href.sql
new file mode 100644
index 000000000000..03b0da154bc9
--- /dev/null
+++ b/products/desktop/packages/workspace-server/src/db/migrations/0023_browser_tab_href.sql
@@ -0,0 +1,3 @@
+ALTER TABLE `browser_tabs` ADD `href` text;
+--> statement-breakpoint
+ALTER TABLE `browser_tabs` ADD `view_state` text;
diff --git a/products/desktop/packages/workspace-server/src/db/migrations/meta/_journal.json b/products/desktop/packages/workspace-server/src/db/migrations/meta/_journal.json
index c36e3f08f01d..4a009af979d1 100644
--- a/products/desktop/packages/workspace-server/src/db/migrations/meta/_journal.json
+++ b/products/desktop/packages/workspace-server/src/db/migrations/meta/_journal.json
@@ -162,6 +162,13 @@
"when": 1784804000000,
"tag": "0022_archive_task_details",
"breakpoints": true
+ },
+ {
+ "idx": 23,
+ "version": "6",
+ "when": 1785600000000,
+ "tag": "0023_browser_tab_href",
+ "breakpoints": true
}
]
}
diff --git a/products/desktop/packages/workspace-server/src/db/repositories/browser-tabs-repository.ts b/products/desktop/packages/workspace-server/src/db/repositories/browser-tabs-repository.ts
index 84bb44488f5b..4b334437e773 100644
--- a/products/desktop/packages/workspace-server/src/db/repositories/browser-tabs-repository.ts
+++ b/products/desktop/packages/workspace-server/src/db/repositories/browser-tabs-repository.ts
@@ -1,4 +1,4 @@
-import type { TabsSnapshot } from "@posthog/shared";
+import { rewriteSavedLocation, type TabsSnapshot } from "@posthog/shared";
import { asc } from "drizzle-orm";
import { inject, injectable } from "inversify";
import { DATABASE_SERVICE } from "../identifiers";
@@ -44,6 +44,11 @@ export class BrowserTabsRepository implements IBrowserTabsRepository {
tabs: tabRows.map((t) => ({
id: t.id,
windowId: t.windowId,
+ // Rewritten on the way out: a snapshot written before the routes were
+ // flattened holds `/website/*` hrefs, and restoring one lands the tab
+ // on a route that no longer exists.
+ href: t.href ? rewriteSavedLocation(t.href) : null,
+ viewState: t.viewState ?? null,
dashboardId: t.dashboardId,
taskId: t.taskId ?? null,
channelId: t.channelId ?? null,
@@ -85,6 +90,8 @@ export class BrowserTabsRepository implements IBrowserTabsRepository {
snapshot.tabs.map((t) => ({
id: t.id,
windowId: t.windowId,
+ href: t.href ?? null,
+ viewState: t.viewState ?? null,
dashboardId: t.dashboardId,
taskId: t.taskId ?? null,
channelId: t.channelId ?? null,
diff --git a/products/desktop/packages/workspace-server/src/db/schema.ts b/products/desktop/packages/workspace-server/src/db/schema.ts
index 6168b2990cde..c4d0e5f809f3 100644
--- a/products/desktop/packages/workspace-server/src/db/schema.ts
+++ b/products/desktop/packages/workspace-server/src/db/schema.ts
@@ -1,3 +1,4 @@
+import type { TabViewState } from "@posthog/shared";
import { sql } from "drizzle-orm";
import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
@@ -231,8 +232,9 @@ export const browserWindows = sqliteTable("browser_windows", {
});
/**
- * Open tabs in the Channels canvas surface. A tab references a canvas
- * (dashboard) and the channel it belongs to; display is resolved at render.
+ * Open tabs. A tab stores the `href` it is on plus the nav state that href
+ * cannot express (`viewState`); the reference columns below are a label/icon
+ * cache resolved at render, not the source of truth for where a tab is.
* `scrollState` is reserved/unwired for later per-tab state (scroll restore).
*/
export const browserTabs = sqliteTable(
@@ -242,6 +244,10 @@ export const browserTabs = sqliteTable(
windowId: text()
.notNull()
.references(() => browserWindows.id, { onDelete: "cascade" }),
+ /** Where this tab is. The source of truth for restoring it. */
+ href: text(),
+ /** Nav state the href cannot express (sidebar pane, scoped space, rail memory). */
+ viewState: text({ mode: "json" }).$type<TabViewState>(),
/** Canvas this tab shows. Null for a task tab or a blank tab. */
dashboardId: text(),
/** Task this tab shows. Null for a canvas tab or a blank tab. */
diff --git a/products/desktop/packages/workspace-server/src/services/browser-tabs/schemas.ts b/products/desktop/packages/workspace-server/src/services/browser-tabs/schemas.ts
index e565a1b89ab7..0961d3e515d2 100644
--- a/products/desktop/packages/workspace-server/src/services/browser-tabs/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/browser-tabs/schemas.ts
@@ -1,34 +1,44 @@
-import { type TabsSnapshot, tabsSnapshotSchema } from "@posthog/shared";
+import {
+ type TabsSnapshot,
+ tabsSnapshotSchema,
+ tabViewStateSchema,
+} from "@posthog/shared";
import { z } from "zod";
+/**
+ * Where `+` lands, and where an empty strip reseeds. The space index is the
+ * app's "pick something" screen, so a new tab shows the spaces rather than an
+ * empty placeholder.
+ */
+export const NEW_TAB_HREF = "/spaces";
+
/** tRPC output: the full durable tab/window snapshot. */
export const browserTabsSnapshotOutput = tabsSnapshotSchema;
-export const openOrFocusTabInput = z.object({
- windowId: z.string(),
+/** The location a tab is on, plus the route-derived label/icon cache. */
+const tabLocationFields = {
+ href: z.string().nullable().default(null),
+ viewState: tabViewStateSchema.nullable().default(null),
dashboardId: z.string().nullable().default(null),
taskId: z.string().nullable().default(null),
channelId: z.string().nullable().default(null),
channelSection: z.string().nullable().default(null),
appView: z.string().nullable().default(null),
- // Renderer-minted id for a tab this call may create, so the optimistic local
- // apply and the persisted state agree on the id (local-first tab sync).
- tabId: z.string().optional(),
-});
+};
-export const newBlankTabInput = z.object({
+export const openTabInput = z.object({
windowId: z.string(),
- // Renderer-minted id (see openOrFocusTabInput.tabId).
+ ...tabLocationFields,
+ // Renderer-minted id for the tab this call creates, so the optimistic local
+ // apply and the persisted state agree on the id (local-first tab sync), and
+ // a replayed call is idempotent.
tabId: z.string().optional(),
});
export const setTabTargetInput = z.object({
tabId: z.string(),
- dashboardId: z.string().nullable().default(null),
- taskId: z.string().nullable().default(null),
- channelId: z.string().nullable().default(null),
- channelSection: z.string().nullable().default(null),
- appView: z.string().nullable().default(null),
+ ...tabLocationFields,
+ activate: z.boolean().optional(),
});
export const closeTabInput = z.object({ tabId: z.string() });
diff --git a/products/desktop/packages/workspace-server/src/services/browser-tabs/service.test.ts b/products/desktop/packages/workspace-server/src/services/browser-tabs/service.test.ts
index b050510152a0..e5aa68f18b2b 100644
--- a/products/desktop/packages/workspace-server/src/services/browser-tabs/service.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/browser-tabs/service.test.ts
@@ -1,11 +1,14 @@
import type { BrowserTab, TabsSnapshot } from "@posthog/shared";
import { describe, expect, it } from "vitest";
import type { IBrowserTabsRepository } from "../../db/repositories/browser-tabs-repository";
+import { NEW_TAB_HREF } from "./schemas";
import { BrowserTabsService } from "./service";
const blankTab = (overrides: Partial<BrowserTab> = {}): BrowserTab => ({
id: "tab-1",
windowId: "win-1",
+ href: null,
+ viewState: null,
dashboardId: null,
taskId: null,
channelId: null,
@@ -22,7 +25,7 @@ class FakeRepository implements IBrowserTabsRepository {
saved: TabsSnapshot | null = null;
constructor(private readonly initial: TabsSnapshot) {}
load(): TabsSnapshot {
- return this.initial;
+ return this.saved ?? this.initial;
}
save(snapshot: TabsSnapshot): void {
this.saved = snapshot;
@@ -54,6 +57,8 @@ describe("BrowserTabsService boot invariants", () => {
expect(primary).toBeDefined();
expect(snapshot.tabs.length).toBeGreaterThanOrEqual(1);
expect(snapshot.tabs[0]?.windowId).toBe(primary?.id);
+ // On the new-tab page, not a location-less tab that would render nothing.
+ expect(snapshot.tabs[0]?.href).toBe(NEW_TAB_HREF);
// The healed snapshot is persisted so the invariant survives a restart.
expect(repo.saved).toEqual(snapshot);
},
@@ -72,37 +77,115 @@ describe("BrowserTabsService boot invariants", () => {
expect(service.getSnapshot()).toBe(initial);
expect(repo.saved).toBeNull();
});
-});
-describe("BrowserTabsService window-id healing", () => {
- it("newBlankTab lands in the primary window when the given id is unknown", () => {
- const repo = new FakeRepository({ windows: [], tabs: [] });
+ it("restores a resolved tab title after the service is recreated", () => {
+ const repo = new FakeRepository({
+ windows: [
+ { id: "win-1", isPrimary: true, bounds: null, activeTabId: "tab-1" },
+ ],
+ tabs: [blankTab()],
+ });
const service = new BrowserTabsService(repo);
- const primaryId = service.getPrimaryWindowId();
- const snapshot = service.newBlankTab({
- windowId: "stale-window-id",
- tabId: "tab-new",
+ service.openTab({
+ windowId: "win-1",
+ tabId: "tab-2",
+ href: "/tasks/task-2",
+ viewState: { title: "Investigate checkout drop-off" },
+ dashboardId: null,
+ taskId: "task-2",
+ channelId: null,
});
- const created = snapshot.tabs.find((t) => t.id === "tab-new");
- expect(created?.windowId).toBe(primaryId);
+ const restarted = new BrowserTabsService(repo);
+ expect(
+ restarted.getSnapshot().tabs.find((tab) => tab.id === "tab-2")?.viewState
+ ?.title,
+ ).toBe("Investigate checkout drop-off");
});
- it("openOrFocus lands in the primary window when the given id is unknown", () => {
+ it("clears persisted locations and titles when the auth scope changes", () => {
+ const initial: TabsSnapshot = {
+ windows: [
+ { id: "win-1", isPrimary: true, bounds: null, activeTabId: "tab-1" },
+ ],
+ tabs: [
+ blankTab({
+ href: "/tasks/private-task",
+ viewState: {
+ title: "Private task title",
+ lastByPane: {
+ inbox: { href: "/inbox/private-report" },
+ },
+ },
+ taskId: "private-task",
+ appView: "inbox",
+ }),
+ ],
+ };
+ const repo = new FakeRepository(initial);
+ const service = new BrowserTabsService(repo);
+
+ const reset = service.reset();
+
+ expect(reset.windows).toEqual([
+ expect.objectContaining({ id: "win-1", activeTabId: expect.any(String) }),
+ ]);
+ expect(reset.tabs).toEqual([
+ expect.objectContaining({
+ windowId: "win-1",
+ href: NEW_TAB_HREF,
+ viewState: null,
+ taskId: null,
+ appView: null,
+ }),
+ ]);
+ expect(repo.saved).toEqual(reset);
+ });
+});
+
+describe("BrowserTabsService window-id healing", () => {
+ // A mirror seeded before a schema repair, or another window's since-closed
+ // id, must not append into a window that does not exist.
+ it("opens into the primary window when the given id is unknown", () => {
const repo = new FakeRepository({ windows: [], tabs: [] });
const service = new BrowserTabsService(repo);
const primaryId = service.getPrimaryWindowId();
- const snapshot = service.openOrFocus({
+ const snapshot = service.openTab({
windowId: "stale-window-id",
- dashboardId: "dash-1",
+ href: "/inbox",
+ viewState: null,
+ dashboardId: null,
taskId: null,
channelId: null,
tabId: "tab-open",
});
- const created = snapshot.tabs.find((t) => t.id === "tab-open");
- expect(created?.windowId).toBe(primaryId);
+ expect(snapshot.tabs.find((t) => t.id === "tab-open")?.windowId).toBe(
+ primaryId,
+ );
+ });
+
+ // Without dedup there is nothing to absorb a replayed open, so the minted id
+ // is what keeps it from appending a second copy.
+ it("is idempotent on a replayed open", () => {
+ const repo = new FakeRepository({ windows: [], tabs: [] });
+ const service = new BrowserTabsService(repo);
+ const open = () =>
+ service.openTab({
+ windowId: service.getPrimaryWindowId(),
+ href: "/inbox",
+ viewState: null,
+ dashboardId: null,
+ taskId: null,
+ channelId: null,
+ tabId: "tab-open",
+ });
+
+ open();
+ const snapshot = open();
+
+ expect(snapshot.tabs.filter((t) => t.id === "tab-open")).toHaveLength(1);
});
});
diff --git a/products/desktop/packages/workspace-server/src/services/browser-tabs/service.ts b/products/desktop/packages/workspace-server/src/services/browser-tabs/service.ts
index 3b3e33e813f4..eeb04cbe2f31 100644
--- a/products/desktop/packages/workspace-server/src/services/browser-tabs/service.ts
+++ b/products/desktop/packages/workspace-server/src/services/browser-tabs/service.ts
@@ -2,11 +2,12 @@ import {
type BrowserWindow,
closeTab,
closeTabs,
- newBlankTab,
- openOrFocusTab,
+ openTab,
+ resetTabs,
setTabOrder,
setTabTarget,
setWindowActiveTab,
+ type TabLocation,
type TabsSnapshot,
type TabTarget,
TypedEventEmitter,
@@ -14,7 +15,11 @@ import {
import { inject, injectable } from "inversify";
import { BROWSER_TABS_REPOSITORY } from "../../db/identifiers";
import type { IBrowserTabsRepository } from "../../db/repositories/browser-tabs-repository";
-import { BrowserTabsEvent, type BrowserTabsEvents } from "./schemas";
+import {
+ BrowserTabsEvent,
+ type BrowserTabsEvents,
+ NEW_TAB_HREF,
+} from "./schemas";
const makeId = () => crypto.randomUUID();
const now = () => Date.now();
@@ -22,23 +27,26 @@ const now = () => Date.now();
export interface IBrowserTabsService {
getSnapshot(): TabsSnapshot;
getPrimaryWindowId(): string;
- openOrFocus(
- input: TabTarget & {
- windowId: string;
- channelId: string | null;
- channelSection?: string | null;
- appView?: string | null;
- tabId?: string;
- },
+ reset(): TabsSnapshot;
+ openTab(
+ input: TabTarget &
+ TabLocation & {
+ windowId: string;
+ channelId: string | null;
+ channelSection?: string | null;
+ appView?: string | null;
+ tabId?: string;
+ },
): TabsSnapshot;
- newBlankTab(input: { windowId: string; tabId?: string }): TabsSnapshot;
setTabTarget(
- input: TabTarget & {
- tabId: string;
- channelId: string | null;
- channelSection?: string | null;
- appView?: string | null;
- },
+ input: TabTarget &
+ TabLocation & {
+ tabId: string;
+ channelId: string | null;
+ channelSection?: string | null;
+ appView?: string | null;
+ activate?: boolean;
+ },
): TabsSnapshot;
close(tabId: string): TabsSnapshot;
closeMany(tabIds: string[], focusTabId?: string | null): TabsSnapshot;
@@ -87,13 +95,25 @@ export class BrowserTabsService
return { ...snapshot, windows: [primary, ...snapshot.windows] };
}
- /** The strip must never boot empty: seed a blank tab when none survived. */
+ /**
+ * The strip must never boot empty: seed a tab on the space index when none
+ * survived. That page is also what `+` opens, so an empty strip and a fresh
+ * tab land on the same screen.
+ */
private ensureAtLeastOneTab(snapshot: TabsSnapshot): TabsSnapshot {
if (snapshot.tabs.length > 0) return snapshot;
const primary = snapshot.windows.find((w) => w.isPrimary);
if (!primary) return snapshot;
- return newBlankTab(snapshot, { windowId: primary.id, makeId, now })
- .snapshot;
+ return openTab(snapshot, {
+ windowId: primary.id,
+ href: NEW_TAB_HREF,
+ viewState: null,
+ dashboardId: null,
+ taskId: null,
+ channelId: null,
+ makeId,
+ now,
+ }).snapshot;
}
/** Creation targets heal a stale window id (a mirror seeded before a schema
@@ -120,36 +140,31 @@ export class BrowserTabsService
return primary.id;
}
- openOrFocus(
- input: TabTarget & {
- windowId: string;
- channelId: string | null;
- channelSection?: string | null;
- appView?: string | null;
- tabId?: string;
- },
- ): TabsSnapshot {
- // Honor a renderer-minted id so the caller's optimistic apply and this
- // persisted state agree on the id. Dedup-by-identity still applies first,
- // so a replay of the same open focuses the existing tab.
- const providedId = input.tabId;
- const { snapshot } = openOrFocusTab(this.snapshot, {
- ...input,
- windowId: this.resolveWindowId(input.windowId),
- makeId: providedId ? () => providedId : makeId,
- now,
- });
- return this.commit(snapshot);
+ reset(): TabsSnapshot {
+ return this.commit(
+ resetTabs(this.snapshot, { href: NEW_TAB_HREF, makeId, now }),
+ );
}
- newBlankTab(input: { windowId: string; tabId?: string }): TabsSnapshot {
+ openTab(
+ input: TabTarget &
+ TabLocation & {
+ windowId: string;
+ channelId: string | null;
+ channelSection?: string | null;
+ appView?: string | null;
+ tabId?: string;
+ },
+ ): TabsSnapshot {
const providedId = input.tabId;
- // Idempotent on the renderer-minted id: a replay of the same call (blank
- // tabs have no identity to dedup on) must not append a second tab.
+ // Idempotent on the renderer-minted id. There is no dedup to fall back on
+ // (opening never focuses an existing tab), so a replayed call would
+ // otherwise append a second copy.
if (providedId && this.snapshot.tabs.some((t) => t.id === providedId)) {
return this.snapshot;
}
- const { snapshot } = newBlankTab(this.snapshot, {
+ const { snapshot } = openTab(this.snapshot, {
+ ...input,
windowId: this.resolveWindowId(input.windowId),
makeId: providedId ? () => providedId : makeId,
now,
@@ -158,12 +173,13 @@ export class BrowserTabsService
}
setTabTarget(
- input: TabTarget & {
- tabId: string;
- channelId: string | null;
- channelSection?: string | null;
- appView?: string | null;
- },
+ input: TabTarget &
+ TabLocation & {
+ tabId: string;
+ channelId: string | null;
+ channelSection?: string | null;
+ appView?: string | null;
+ },
): TabsSnapshot {
return this.commit(setTabTarget(this.snapshot, { ...input, now }));
}