Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(desktop): reuse issue tabs without stealing focus (MUL-9145) (#10480)
rawlence013be7700bb4
diff --git a/apps/desktop/src/renderer/src/components/tab-bar.test.tsx b/apps/desktop/src/renderer/src/components/tab-bar.test.tsxindex 2377dbdbc3..6dbb1d5ff1 100644--- a/apps/desktop/src/renderer/src/components/tab-bar.test.tsx+++ b/apps/desktop/src/renderer/src/components/tab-bar.test.tsx@@ -22,6 +22,7 @@ type MockTab = {const state = vi.hoisted(() => ({activeWorkspaceSlug: "acme" as string | null,+ tabAttention: null as { tabId: string; sequence: number } | null,byWorkspace: {acme: {activeTabId: "tA",@@ -39,6 +40,8 @@ const state = vi.hoisted(() => ({moveTab: vi.fn<(from: number, to: number) => void>(),addTab: vi.fn<(path: string, title: string) => string>(),updateTab: vi.fn<(tabId: string, patch: { title?: string }) => void>(),+ rememberIssueIdentity: vi.fn<(tabId: string, uuid: string, identifier: string) => void>(),+ clearTabAttention: vi.fn<(sequence: number) => void>(),openIssueWindow: vi.fn(),}));@@ -50,6 +53,9 @@ vi.mock("@/stores/tab-store", () => {get byWorkspace() {return state.byWorkspace;},+ get tabAttention() {+ return state.tabAttention;+ },togglePin: state.togglePin,closeTab: state.closeTab,closeOtherTabs: state.closeOtherTabs,@@ -58,6 +64,8 @@ vi.mock("@/stores/tab-store", () => {moveTab: state.moveTab,addTab: state.addTab,updateTab: state.updateTab,+ rememberIssueIdentity: state.rememberIssueIdentity,+ clearTabAttention: state.clearTabAttention,};const useTabStore = Object.assign((selector?: (s: typeof store) => unknown) =>@@ -91,12 +99,17 @@ vi.mock("@multica/core/paths", async (importOriginal) => ({// default `title` mirrors the persisted tab title (matching the real hook's// fallback); a test can set `pres.title` to simulate a resolved title that// differs, to exercise resolved-title persistence.-const pres = vi.hoisted(() => ({ title: null as string | null, titleResolved: true }));+const pres = vi.hoisted(() => ({+ title: null as string | null,+ titleResolved: true,+ issueIdentity: undefined as { id: string; identifier: string } | undefined,+}));vi.mock("@multica/views/layout", () => ({- useTabPresentation: vi.fn((_url: string, fallbackTitle?: string) => ({+ useTabPresentation: vi.fn((url: string, fallbackTitle?: string) => ({visual: { kind: "icon", icon: "ListTodo" },title: pres.title ?? fallbackTitle ?? "",titleResolved: pres.titleResolved,+ issueIdentity: url.includes("/issues/") ? pres.issueIdentity : undefined,})),ResourceLeadingVisual: ({ visual }: { visual: { kind: string; icon?: string } }) => (<span data-testid="tab-leading" data-visual-kind={visual.kind} data-icon={visual.icon} />@@ -127,6 +140,7 @@ function englishTabBar() {function reset() {state.activeWorkspaceSlug = "acme";+ state.tabAttention = null;state.byWorkspace = {acme: {activeTabId: "tA",@@ -144,9 +158,12 @@ function reset() {state.moveTab.mockReset();state.addTab.mockReset();state.updateTab.mockReset();+ state.rememberIssueIdentity.mockReset();+ state.clearTabAttention.mockReset();state.openIssueWindow.mockReset();pres.title = null;pres.titleResolved = true;+ pres.issueIdentity = undefined;vi.mocked(useTabPresentation).mockClear();}@@ -259,6 +276,23 @@ describe("TabBar hover action buttons", () => {});describe("TabBar title persistence", () => {+ it("remembers the identity of a restored background identifier tab", () => {+ const uuid = "01a08a00-0000-7000-8000-000000000001";+ pres.issueIdentity = { id: uuid, identifier: "ACM-1" };+ state.byWorkspace.acme.tabs[0] = {+ id: "tA", url: "/acme/issues/ACM-1", title: "ACM-1", pinned: false,+ };+ state.byWorkspace.acme.activeTabId = "tB";++ const { rerender } = render(<TabBar />);+ expect(state.rememberIssueIdentity).toHaveBeenCalledExactlyOnceWith("tA", uuid, "ACM-1");+ // A new result object for the same identity does not repeat the store write.+ pres.issueIdentity = { id: uuid, identifier: "ACM-1" };+ rerender(englishTabBar());+ expect(state.rememberIssueIdentity).toHaveBeenCalledTimes(1);+ expect(state.setActiveTab).not.toHaveBeenCalled();+ });+it("loads tab identities and persists resolved titles for background tabs too", () => {pres.title = "MUL-1: Fixed";state.byWorkspace.acme.tabs = [@@ -290,6 +324,27 @@ describe("TabBar title persistence", () => {});});+describe("TabBar background open of an open tab", () => {+ it("flashes the tab it landed on without activating it", () => {+ state.tabAttention = { tabId: "tB", sequence: 1 };+ const { container } = render(<TabBar />);++ const frame = container.querySelector('[data-tab-id="tB"]')!;+ expect(frame.querySelector("[data-tab-attention]")).not.toBeNull();+ expect(container.querySelectorAll("[data-tab-attention]")).toHaveLength(1);+ expect(state.setActiveTab).not.toHaveBeenCalled();+ });++ it("clears the signal once the flash has played", async () => {+ state.tabAttention = { tabId: "tB", sequence: 3 };+ render(<TabBar />);++ await waitFor(() => expect(state.clearTabAttention).toHaveBeenCalledWith(3), {+ timeout: 3000,+ });+ });+});+describe("TabBar pill chrome", () => {const pillOf = (label: string, getByLabelText: (text: string) => HTMLElement) =>getByLabelText(label).closest("[data-tab-frame]")?.querySelector(".rounded-lg");diff --git a/apps/desktop/src/renderer/src/components/tab-bar.tsx b/apps/desktop/src/renderer/src/components/tab-bar.tsxindex f01eb230d1..e465f1f246 100644--- a/apps/desktop/src/renderer/src/components/tab-bar.tsx+++ b/apps/desktop/src/renderer/src/components/tab-bar.tsx@@ -163,13 +163,25 @@ function SortableTabItem({const { getShareableUrl } = useNavigation();const togglePin = useTabStore((s) => s.togglePin);const updateTab = useTabStore((s) => s.updateTab);+ const rememberIssueIdentity = useTabStore((s) => s.rememberIssueIdentity);+ const attentionSequence = useTabStore((s) =>+ s.tabAttention?.tabId === tab.id ? s.tabAttention.sequence : 0,+ );+ const clearTabAttention = useTabStore((s) => s.clearTabAttention);const issueWindowPath = parseIssueWindowPath(tab.url);// The tab's leading visual and title are derived live from its URL and the// query cache — a resource's own icon/status/avatar and its real title,// updated as the cache updates. `tab.title` is only a persisted first-frame// fallback. See @multica/views useTabPresentation.- const { visual, title, titleResolved } = useTabPresentation(tab.url, tab.title, { fetch: true });+ const { visual, title, titleResolved, issueIdentity } = useTabPresentation(tab.url, tab.title, { fetch: true });+ const issueUuid = issueIdentity?.id;+ const issueIdentifier = issueIdentity?.identifier;+ useEffect(() => {+ if (issueUuid && issueIdentifier) {+ rememberIssueIdentity(tab.id, issueUuid, issueIdentifier);+ }+ }, [tab.id, issueUuid, issueIdentifier, rememberIssueIdentity]);const pinLabel = tab.pinned? t(($) => $.desktop.tab_bar.unpin): t(($) => $.desktop.tab_bar.pin);@@ -414,6 +426,19 @@ function SortableTabItem({onAnimationComplete={() => setShowAddedHighlight(false)}/>)}+ {attentionSequence > 0 && (+ // Keyed so each background open of this tab replays the flash.+ <motion.span+ key={attentionSequence}+ aria-hidden+ data-tab-attention+ className="pointer-events-none absolute inset-x-0 inset-y-1.5 rounded-lg bg-brand/20 ring-2 ring-inset ring-brand/70"+ initial={{ opacity: 0 }}+ animate={{ opacity: shouldReduceMotion ? [0.5, 0] : [0, 1, 0, 1, 0] }}+ transition={{ duration: shouldReduceMotion ? 0.2 : 0.9, ease: "easeOut" }}+ onAnimationComplete={() => clearTabAttention(attentionSequence)}+ />+ )}</motion.div></div>);@@ -590,6 +615,16 @@ export function TabBar() {tabOrder,]);+ const tabAttention = useTabStore((s) => s.tabAttention);+ useEffect(() => {+ if (!tabAttention) return;+ keepTabVisible(+ tabScrollRef.current,+ tabAttention.tabId,+ shouldReduceMotion ? "auto" : "smooth",+ );+ }, [tabAttention, shouldReduceMotion]);+useEffect(() => {const scroller = tabScrollRef.current;if (!scroller || typeof ResizeObserver === "undefined") return;diff --git a/apps/desktop/src/renderer/src/stores/tab-store.test.ts b/apps/desktop/src/renderer/src/stores/tab-store.test.tsindex a756996c67..ce7bc508ee 100644--- a/apps/desktop/src/renderer/src/stores/tab-store.test.ts+++ b/apps/desktop/src/renderer/src/stores/tab-store.test.ts@@ -383,11 +383,32 @@ describe("useTabStore actions", () => {store.addTab("/acme/projects", "B");store.addTab("/acme/skills", "C");- store.openTab("/acme/skills", "C again"); // hits C, at the far end+ store.openTab("/acme/skills", "C again", { activate: true }); // hits C, at the far endconst s = useTabStore.getState();expect(urls()).toEqual(["/acme/issues", "/acme/projects", "/acme/skills"]);expect(getActiveTab(s)?.url).toBe("/acme/skills");});++ it("a background dedupe hit keeps the active tab and flags the existing one", () => {+ const store = useTabStore.getState();+ store.switchWorkspace("acme"); // A active+ const activeId = useTabStore.getState().byWorkspace.acme.activeTabId;+ const skillsId = store.addTab("/acme/skills", "C");+ const before = useTabStore.getState().byWorkspace.acme;++ expect(store.openTab("/acme/skills", "C again")).toBe(skillsId);+ expect(store.openTab("/acme/skills", "C again")).toBe(skillsId);++ const s = useTabStore.getState();+ expect(s.byWorkspace.acme).toBe(before); // no switch, no history visit+ expect(getActiveTab(s)?.id).toBe(activeId);+ expect(s.tabAttention).toEqual({ tabId: skillsId, sequence: 2 });++ store.clearTabAttention(1); // a stale flash finishing keeps the newer signal+ expect(useTabStore.getState().tabAttention?.sequence).toBe(2);+ store.clearTabAttention(2);+ expect(useTabStore.getState().tabAttention).toBeNull();+ });});it("closeTab on the last tab in a workspace reseeds the default tab", () => {@@ -519,6 +540,213 @@ describe("useTabStore actions", () => {});});+// In-app issue links carry the UUID, and the issue page then replaces that+// URL with the identifier URL. Opening the same issue again must find the tab+// now showing it rather than add a second one.+describe("issue UUID and identifier URLs share one tab", () => {+ const ISSUE_UUID = "01a08a00-0000-7000-8000-000000000001";+ const OTHER_UUID = "01a08a00-0000-7000-8000-000000000002";+ const emptyState = (): {+ activeWorkspaceSlug: string | null;+ byWorkspace: Record<string, WorkspaceTabGroup>;+ } => ({ activeWorkspaceSlug: null, byWorkspace: {} });++ /** Open the issue from the list and let its page canonicalize the URL. */+ function openCanonicalizedIssue(): { listTabId: string; issueTabId: string } {+ const store = useTabStore.getState();+ store.switchWorkspace("acme");+ const listTabId = useTabStore.getState().byWorkspace.acme.activeTabId;+ const issueTabId = store.openTab(`/acme/issues/${ISSUE_UUID}`, "ACM-1", {+ activate: true,+ });+ store.navigateActiveSession("/acme/issues/ACM-1", { replace: true });+ store.setActiveTab(listTabId);+ return { listTabId, issueTabId };+ }++ it("openTab with the UUID URL focuses the tab showing the identifier URL", () => {+ const { issueTabId } = openCanonicalizedIssue();++ const id = useTabStore+ .getState()+ .openTab(`/acme/issues/${ISSUE_UUID}`, "ACM-1", { activate: true });++ const group = useTabStore.getState().byWorkspace.acme;+ expect(id).toBe(issueTabId);+ expect(group.tabs).toHaveLength(2);+ expect(group.activeTabId).toBe(issueTabId);+ expect(getActiveTab(useTabStore.getState())?.url).toBe("/acme/issues/ACM-1");+ });++ it("matches a deliverable link and a cross-workspace open of the same issue", () => {+ const store = useTabStore.getState();+ store.switchWorkspace("acme");+ const issueTabId = store.openTab(+ `/acme/issues/${ISSUE_UUID}/deliverables/report.pdf`,+ "ACM-1",+ { activate: true },+ );+ store.navigateActiveSession("/acme/issues/ACM-1/deliverables/report.pdf", {+ replace: true,+ });+ store.switchWorkspace("butter");++ store.switchWorkspace(+ "acme",+ `/acme/issues/${ISSUE_UUID}/deliverables/report.pdf`,+ );++ const group = useTabStore.getState().byWorkspace.acme;+ expect(group.tabs).toHaveLength(2);+ expect(group.activeTabId).toBe(issueTabId);+ });++ it("leaves other issues and identifier opens without a learned UUID alone", () => {+ openCanonicalizedIssue();+ const store = useTabStore.getState();++ store.openTab(`/acme/issues/${OTHER_UUID}`, "ACM-2");+ store.openTab("/acme/issues/ACM-3", "ACM-3");++ expect(useTabStore.getState().byWorkspace.acme.tabs).toHaveLength(4);+ });++ it("does not learn an alias when a push moves the tab to another issue", () => {+ const store = useTabStore.getState();+ store.switchWorkspace("acme");+ store.navigateActiveSession(`/acme/issues/${ISSUE_UUID}`);+ store.navigateActiveSession("/acme/issues/ACM-2");++ store.openTab(`/acme/issues/${ISSUE_UUID}`, "ACM-1");++ const group = useTabStore.getState().byWorkspace.acme;+ expect(group.issueAliases).toEqual({});+ expect(group.tabs).toHaveLength(2);+ });++ it("keeps the learned aliases across a restart", () => {+ const { issueTabId } = openCanonicalizedIssue();+ const { partialize } = useTabStore.persist.getOptions();+ const persisted = JSON.parse(+ JSON.stringify(partialize!(useTabStore.getState())),+ );++ useTabStore.getState().reset();+ useTabStore.setState(+ mergePersistedTabs(persisted, emptyState()),+ );++ expect(+ useTabStore.getState().openTab(`/acme/issues/${ISSUE_UUID}`, "ACM-1"),+ ).toBe(issueTabId);+ expect(useTabStore.getState().byWorkspace.acme.tabs).toHaveLength(2);+ });++ it.each([false, true])("reuses a resolved identifier-first tab (restored: %s)", (restored) => {+ const store = useTabStore.getState();+ store.switchWorkspace("acme");+ const listTabId = useTabStore.getState().byWorkspace.acme.activeTabId;+ const issueTabId = store.openTab("/acme/issues/ACM-1", "ACM-1");+ if (restored) {+ const persisted = JSON.parse(JSON.stringify(+ useTabStore.persist.getOptions().partialize!(useTabStore.getState()),+ ));+ // Pre-patch v5 payloads already contain identifier URLs, but no aliases.+ delete persisted.byWorkspace.acme.issueAliases;+ store.reset();+ useTabStore.setState(mergePersistedTabs(persisted, emptyState()));+ }++ // The tab strip resolves background tabs without mounting their pages.+ store.rememberIssueIdentity(issueTabId, ISSUE_UUID, "ACM-1");+ expect(useTabStore.getState().byWorkspace.acme.activeTabId).toBe(listTabId);+ expect(store.openTab(`/acme/issues/${ISSUE_UUID}`, "ACM-1", { activate: true })).toBe(issueTabId);+ expect(useTabStore.getState().byWorkspace.acme.tabs).toHaveLength(2);+ });++ it("retains an open issue's alias after 200 other issue visits and a restart", () => {+ const { listTabId, issueTabId } = openCanonicalizedIssue();+ const store = useTabStore.getState();+ store.setActiveTab(listTabId);+ for (let i = 2; i <= 201; i++) {+ store.navigateActiveSession(`/acme/issues/01a08a00-0000-7000-8000-${String(i).padStart(12, "0")}`);+ store.navigateActiveSession(`/acme/issues/ACM-${i}`, { replace: true });+ }+ expect(Object.keys(useTabStore.getState().byWorkspace.acme.issueAliases!)).toHaveLength(200);+ const persisted = JSON.parse(JSON.stringify(+ useTabStore.persist.getOptions().partialize!(useTabStore.getState()),+ ));+ store.reset();+ useTabStore.setState(mergePersistedTabs(persisted, emptyState()));++ expect(store.openTab(`/acme/issues/${ISSUE_UUID}`, "ACM-1")).toBe(issueTabId);+ expect(useTabStore.getState().byWorkspace.acme.tabs).toHaveLength(2);+ });++ it("retains identities for more than 200 open issues across a restart", () => {+ const store = useTabStore.getState();+ store.switchWorkspace("acme");+ const issueTabIds: string[] = [];+ for (let i = 1; i <= 201; i++) {+ const uuid = `01a08a00-0000-7000-8000-${String(i).padStart(12, "0")}`;+ issueTabIds.push(store.openTab(`/acme/issues/${uuid}`, `ACM-${i}`, { activate: true }));+ store.navigateActiveSession(`/acme/issues/ACM-${i}`, { replace: true });+ }+ const persisted = JSON.parse(JSON.stringify(+ useTabStore.persist.getOptions().partialize!(useTabStore.getState()),+ ));+ store.reset();+ useTabStore.setState(mergePersistedTabs(persisted, emptyState()));++ expect(store.openTab(`/acme/issues/${ISSUE_UUID}`, "ACM-1")).toBe(issueTabIds[0]);+ expect(useTabStore.getState().byWorkspace.acme.tabs).toHaveLength(202);+ });++ it("ignores a resolved identity after its tab has navigated to another issue", () => {+ const store = useTabStore.getState();+ store.switchWorkspace("acme");+ const tabId = store.openTab("/acme/issues/ACM-1", "ACM-1", { activate: true });+ store.navigateActiveSession("/acme/issues/ACM-2");+ store.rememberIssueIdentity(tabId, ISSUE_UUID, "ACM-1");++ expect(useTabStore.getState().byWorkspace.acme.issueAliases).toEqual({});+ });++ it("drops persisted aliases that are not UUID → identifier pairs", () => {+ const restored = mergePersistedTabs(+ {+ activeWorkspaceSlug: "acme",+ byWorkspace: {+ acme: {+ activeTabId: "t1",+ issueAliases: {+ [ISSUE_UUID]: "ACM-1",+ [OTHER_UUID]: ISSUE_UUID,+ "ACM-9": "ACM-1",+ constructor: "ACM-1",+ },+ tabs: [+ {+ id: "t1",+ url: "/acme/issues",+ title: "Issues",+ pinned: false,+ history: { stack: ["/acme/issues"], index: 0 },+ memento: { scroll: {} },+ },+ ],+ },+ },+ },+ emptyState(),+ );++ expect(restored.byWorkspace.acme.issueAliases).toEqual({+ [ISSUE_UUID]: "ACM-1",+ });+ });+});+describe("navigateActiveSession", () => {it("updates url, resourceKey, and pushes onto the virtual history", () => {const store = useTabStore.getState();diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.tsindex 6f2384992c..7b3c549871 100644--- a/apps/desktop/src/renderer/src/stores/tab-store.ts+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts@@ -8,6 +8,7 @@ import {} from "./tab-store-storage";import { createSafeId } from "@multica/core/utils";import { workspaceSlugForPath } from "@multica/core/paths";+import { isIssueUuid } from "@multica/core/issues/canonical-id";// Tab sessions hold serializable URLs, identity, virtual history, and view// mementos. The coordinator projects the active session onto the single router;@@ -136,6 +137,14 @@ export interface WorkspaceTabGroup {* far away from it.*/recentTabIds: string[];+ /**+ * Issue UUID → identifier (`MUL-123`), learned when a tab resolves its issue+ * or rewrites its UUID URL to the identifier URL. In-app links still carry the+ * UUID, so without this an open of an issue that already has a tab would+ * miss it and add a second one. Bounded, and persisted so that dedupe+ * still works after a restart.+ */+ issueAliases?: Record<string, string>;}interface TabStore {@@ -164,6 +173,16 @@ interface TabStore {* Deliberately NOT persisted.*/mountGeneration: number;+ /**+ * Bumped when a background open (Cmd/middle-click) lands on a tab that+ * already shows the resource. The open must not move the user, so instead+ * of activating that tab the tab bar flashes it. Not persisted; the tab+ * bar clears it once the flash has played, so a later remount or effect+ * re-run cannot replay it.+ */+ tabAttention: { tabId: string; sequence: number } | null;+ /** Drop the attention signal, unless a newer one has replaced it. */+ clearTabAttention: (sequence: number) => void;/*** Switch to a workspace.@@ -210,6 +229,8 @@ interface TabStore {setActiveTab: (tabId: string) => void;/** Patch display metadata of a tab (title-sync). Finds across groups. */updateTab: (tabId: string, patch: Partial<Pick<TabSession, "title">>) => void;+ /** Record a resolved tab's issue identity, including restored background tabs. */+ rememberIssueIdentity: (tabId: string, uuid: string, identifier: string) => void;/*** In-tab navigation: update the active session's url/resourceKey and its* virtual history. This is the ONLY way a session's url changes; the@@ -359,6 +380,93 @@ function inboxSelectionKeyForUrl(url: string): string | null {return `${pathname}?issue=${encodeURIComponent(selectedKey)}`;}+/** Historical aliases are bounded; identities of open tabs are never evicted. */+const MAX_ISSUE_ALIASES = 200;++/** The `{segment}` of a `/{ws}/issues/{segment}[/...]` URL, else null. */+function issueRouteSegment(url: string): string | null {+ const segments = splitTabUrl(url).pathname.split("/");+ return segments[2] === "issues" && segments[3] ? segments[3] : null;+}++/**+ * `key` with a learned issue UUID written as the issue's identifier, so+ * `/ws/issues/{uuid}` and `/ws/issues/MUL-123` dedupe to the same tab.+ */+function canonicalResourceKey(+ key: string,+ aliases: Record<string, string> | undefined,+): string {+ const segment = issueRouteSegment(key);+ if (!segment || !aliases || !isIssueUuid(segment)) return key;+ const identifier = aliases[segment];+ if (!identifier) return key;+ const { pathname, suffix } = splitTabUrl(key);+ const segments = pathname.split("/");+ segments[3] = identifier;+ return `${segments.join("/")}${suffix}`;+}++/** The tab in `group` showing the resource `url` opens, if any. */+function findTabForUrl(+ group: WorkspaceTabGroup,+ url: string,+): TabSession | undefined {+ const aliases = group.issueAliases;+ const key = canonicalResourceKey(resourceKeyForUrl(url), aliases);+ return group.tabs.find(+ (t) => canonicalResourceKey(t.resourceKey, aliases) === key,+ );+}++function limitIssueAliases(+ entries: [string, string][],+ tabs: TabSession[],+): Record<string, string> {+ const openIssues = new Set(tabs.map((tab) => issueRouteSegment(tab.url)));+ let toDrop = Math.max(0, entries.length - MAX_ISSUE_ALIASES);+ return Object.fromEntries(entries.filter(([uuid, identifier]) => {+ if (toDrop > 0 && !openIssues.has(uuid) && !openIssues.has(identifier)) {+ toDrop--;+ return false;+ }+ return true;+ }));+}++/** Resolved tab data and canonical URL replacements both identify an issue. */+function withIssueAlias(+ group: WorkspaceTabGroup,+ uuid: string | null,+ identifier: string | null,+): WorkspaceTabGroup {+ if (!uuid || !identifier) return group;+ if (!isIssueUuid(uuid) || isIssueUuid(identifier)) return group;+ if (group.issueAliases?.[uuid] === identifier) return group;+ const entries = Object.entries(group.issueAliases ?? {}).filter(+ ([key]) => key !== uuid,+ );+ entries.push([uuid, identifier]);+ return {+ ...group,+ issueAliases: limitIssueAliases(entries, group.tabs),+ };+}++/** Persisted aliases are untrusted: keep UUID → identifier string pairs only. */+function normalizeIssueAliases(value: unknown, tabs: TabSession[]): Record<string, string> {+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};+ const entries = Object.entries(value).filter(+ (entry): entry is [string, string] =>+ isIssueUuid(entry[0]) &&+ typeof entry[1] === "string" &&+ entry[1] !== "" &&+ !entry[1].includes("/") &&+ !isIssueUuid(entry[1]),+ );+ return limitIssueAliases(entries, tabs);+}+/*** Defensive: catch URLs that don't belong in the tab store, and normalize* the ones that do.@@ -649,6 +757,7 @@ function reconcileGroup(browsingHistory: prev?.browsingHistory ?? [],browsingHistoryTitles: prev?.browsingHistoryTitles ?? {},recentTabIds,+ issueAliases: prev?.issueAliases ?? {},};}@@ -719,6 +828,7 @@ export const useTabStore = create<TabStore>()(activeWorkspaceSlug: null,byWorkspace: {},mountGeneration: 0,+ tabAttention: null,switchWorkspace(slug, openPath) {// Defensive no-op if slug is empty/invalid — callers like the@@ -766,8 +876,7 @@ export const useTabStore = create<TabStore>()(if (desiredPath) {const clean = sanitizeTabPath(desiredPath);if (clean) {- const key = resourceKeyForUrl(clean);- const match = existing.tabs.find((t) => t.resourceKey === key);+ const match = findTabForUrl(existing, clean);if (match) {const nextGroup = withBrowsingVisit(reconcileGroup(existing, existing.tabs, match.id),@@ -823,8 +932,18 @@ export const useTabStore = create<TabStore>()(// Dedup by resourceKey: the existing tab keeps its own url (its// filters/anchor are its view state); we only focus it.- const key = resourceKeyForUrl(clean);- const existing = group.tabs.find((t) => t.resourceKey === key);+ const existing = findTabForUrl(group, clean);+ if (existing && opts?.activate !== true) {+ // A background open keeps the user where they are: point at the+ // tab already showing the resource instead of switching to it.+ set({+ tabAttention: {+ tabId: existing.id,+ sequence: (get().tabAttention?.sequence ?? 0) + 1,+ },+ });+ return existing.id;+ }if (existing) {const historyBase = withActiveSessionVisit(group,@@ -1010,6 +1129,24 @@ export const useTabStore = create<TabStore>()(});},+ rememberIssueIdentity(tabId, uuid, identifier) {+ const { byWorkspace } = get();+ const hit = findTabLocation(byWorkspace, tabId);+ if (!hit) return;+ const { slug, group, index } = hit;+ const segment = issueRouteSegment(group.tabs[index].url)?.toLowerCase();+ // A resolving tab may already have navigated away from this issue.+ if (segment !== uuid.toLowerCase() && segment !== identifier.toLowerCase()) return;+ const nextGroup = withIssueAlias(group, uuid, identifier);+ if (nextGroup === group) return;+ set({ byWorkspace: { ...byWorkspace, [slug]: nextGroup } });+ },++ clearTabAttention(sequence) {+ if (get().tabAttention?.sequence !== sequence) return;+ set({ tabAttention: null });+ },+navigateActiveSession(url, opts) {const { activeWorkspaceSlug, byWorkspace } = get();if (!activeWorkspaceSlug) return;@@ -1047,7 +1184,13 @@ export const useTabStore = create<TabStore>()(const nextTabs = [...group.tabs];nextTabs[index] = next;const nextGroup = withBrowsingNavigation(- { ...group, tabs: nextTabs },+ replace+ ? withIssueAlias(+ { ...group, tabs: nextTabs },+ issueRouteSegment(current.url),+ issueRouteSegment(clean),+ )+ : { ...group, tabs: nextTabs },activeWorkspaceSlug,current,clean,@@ -1283,7 +1426,12 @@ export const useTabStore = create<TabStore>()(},reset() {- set({ activeWorkspaceSlug: null, byWorkspace: {}, mountGeneration: 0 });+ set({+ activeWorkspaceSlug: null,+ byWorkspace: {},+ mountGeneration: 0,+ tabAttention: null,+ });},}),{@@ -1347,6 +1495,7 @@ function partializeTabs(state: PersistedTabState) {recentTabIds: group.recentTabIds,browsingHistory: group.browsingHistory,browsingHistoryTitles: group.browsingHistoryTitles,+ issueAliases: group.issueAliases,tabs: group.tabs.map((t) => ({id: t.id,url: t.url,@@ -1480,6 +1629,7 @@ export function mergePersistedTabs<T extends PersistedTabState>(browsingHistory,tabs,),+ issueAliases: normalizeIssueAliases(pGroup.issueAliases, tabs),},tabs,activeTabId,@@ -1636,6 +1786,7 @@ interface V4Persisted {interface V5PersistedGroup extends V4PersistedGroup {browsingHistory: string[];browsingHistoryTitles?: Record<string, string>;+ issueAliases?: unknown;}interface V5Persisted {diff --git a/packages/views/layout/tab-presentation.test.tsx b/packages/views/layout/tab-presentation.test.tsxindex 0b805041cf..66c585ba1b 100644--- a/packages/views/layout/tab-presentation.test.tsx+++ b/packages/views/layout/tab-presentation.test.tsx@@ -427,6 +427,7 @@ describe("useTabPresentation — restored issue tabs", () => {);await waitFor(() => expect(result.current.title).toBe("MUL-7: Restore tabs"));expect(result.current.titleResolved).toBe(true);+ expect(result.current.issueIdentity).toEqual({ id: issue.id, identifier: "MUL-7" });expect(qc.getQueryData(issueDetailOptions("ws1", issue.id).queryKey)).toEqual(issue);expect(getIssue).toHaveBeenCalledExactlyOnceWith("MUL-7");diff --git a/packages/views/layout/tab-presentation.tsx b/packages/views/layout/tab-presentation.tsxindex 363cc39243..55a58741df 100644--- a/packages/views/layout/tab-presentation.tsx+++ b/packages/views/layout/tab-presentation.tsx@@ -74,7 +74,11 @@ const PENDING_RESOURCE_KEYS: ReadonlySet<TabLabelKey> = new Set<TabLabelKey>(["runtime",]);-function useTabEntityData(subject: TabSubject, wsId: string, fetch: boolean): TabEntityData {+interface ResolvedTabEntityData extends TabEntityData {+ issue?: NonNullable<TabEntityData["issue"]> & { id: string };+}++function useTabEntityData(subject: TabSubject, wsId: string, fetch: boolean): ResolvedTabEntityData {const { t: chatT } = useT("chat");// Read both inbox lists cache-only; the archived view keeps its own list, so@@ -145,11 +149,12 @@ function useTabEntityData(subject: TabSubject, wsId: string, fetch: boolean): Taconst runtimes = useQuery({ ...runtimeListOptions(wsId), enabled: false }).data;const sessions = useQuery({ ...chatSessionsOptions(wsId), enabled: false }).data;- const data: TabEntityData = {};+ const data: ResolvedTabEntityData = {};switch (subject.kind) {case "issue":if (issue) {data.issue = {+ id: issue.id,identifier: issue.identifier,title: issue.title,status: issue.status,@@ -252,6 +257,8 @@ export interface TabPresentationResult {title: string;/** False while a resource title is only a type label or persisted fallback. */titleResolved: boolean;+ /** Also available for background tabs whose issue pages have not mounted. */+ issueIdentity?: { id: string; identifier: string };}/**@@ -311,6 +318,9 @@ export function useTabPresentation(title,titleResolved: !selectionPending &&(titleSpec.kind !== "tab" || !PENDING_RESOURCE_KEYS.has(titleSpec.tabKey)),+ issueIdentity: data.issue+ ? { id: data.issue.id, identifier: data.issue.identifier }+ : undefined,};}