Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(issues): MUL-5362 return to the source list after deleting an issue (#5997)
Bohan Jiangceba14a22776
diff --git a/apps/desktop/src/renderer/src/platform/navigation.test.tsx b/apps/desktop/src/renderer/src/platform/navigation.test.tsxindex e8e7bc7d56..fddac07b6b 100644--- a/apps/desktop/src/renderer/src/platform/navigation.test.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.test.tsx@@ -219,6 +219,44 @@ describe("back", () => {});});+// Consumed by `useBackOrReplace` — a page whose subject was deleted steps back+// only when this says there is somewhere to step back to.+describe("canGoBack", () => {+ it("is false on a tab sitting at the start of its history", () => {+ const getAdapter = renderProvider();++ expect(getActiveTab(useTabStore.getState())!.history.index).toBe(0);+ expect(getAdapter().canGoBack!()).toBe(false);+ });++ it("is true once the tab has navigated in place", () => {+ const getAdapter = renderProvider();++ getAdapter().push("/acme/projects");++ expect(getActiveTab(useTabStore.getState())!.history.index).toBe(1);+ expect(getAdapter().canGoBack!()).toBe(true);+ });++ it("is false again after stepping back to the start", () => {+ const getAdapter = renderProvider();+ getAdapter().push("/acme/projects");++ getAdapter().back!();++ expect(getAdapter().canGoBack!()).toBe(false);+ });++ it("is false for a freshly opened tab, which starts its own history", () => {+ const getAdapter = renderProvider();+ getAdapter().push("/acme/projects");++ getAdapter().openInNewTab!("/acme/agents", "Agents", { activate: true });++ expect(getAdapter().canGoBack!()).toBe(false);+ });+});+describe("routeContentLinkPath (links inside content — MUL-5208)", () => {it("opens a same-workspace path in a foreground tab of its own", () => {routeContentLinkPath("/acme/issues/MUL-1");diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsxindex 9a72e6f5c7..48e7e6e4d9 100644--- a/apps/desktop/src/renderer/src/platform/navigation.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx@@ -195,6 +195,13 @@ export function DesktopNavigationProvider({back: () => {useTabStore.getState().goBack();},+ // The active tab's virtual history, same source the shell's back button+ // reads. A tab opened straight onto a destination sits at index 0 and+ // has nothing behind it.+ canGoBack: () => {+ const active = getActiveTab(useTabStore.getState());+ return (active?.history.index ?? 0) > 0;+ },pathname: location.pathname,searchParams: new URLSearchParams(location.search),openInNewTab: (diff --git a/apps/web/platform/in-app-history.test.ts b/apps/web/platform/in-app-history.test.tsnew file mode 100644index 0000000000..66ccf33a74--- /dev/null+++ b/apps/web/platform/in-app-history.test.ts@@ -0,0 +1,47 @@+import { afterEach, describe, expect, it } from "vitest";+import { canGoBackInApp } from "./in-app-history";++const win = window as unknown as { navigation?: unknown };++function withNavigationApi(navigation: unknown) {+ win.navigation = navigation;+}++afterEach(() => {+ delete win.navigation;+});++describe("canGoBackInApp", () => {+ it("reports the Navigation API's answer when the browser has one", () => {+ withNavigationApi({ canGoBack: true });++ expect(canGoBackInApp()).toBe(true);+ });++ // Not "nothing was pushed yet" — arriving from an external site leaves the+ // same-origin run empty, which is the whole reason we ask the browser.+ it("reports false when the Navigation API says there is no same-origin entry", () => {+ withNavigationApi({ canGoBack: false });++ expect(canGoBackInApp()).toBe(false);+ });++ // jsdom ships no `window.navigation`. Callers then take their fallback path,+ // which is what these browsers did before any of this existed — deliberately+ // no guessing, because a wrong `true` walks the user out of the app.+ it("reports false when the browser has no Navigation API", () => {+ expect(canGoBackInApp()).toBe(false);+ });++ it("reports false for a `navigation` global that is not the Navigation API", () => {+ withNavigationApi({ somethingElse: true });++ expect(canGoBackInApp()).toBe(false);+ });++ it("reports false for a non-boolean canGoBack", () => {+ withNavigationApi({ canGoBack: "yes" });++ expect(canGoBackInApp()).toBe(false);+ });+});diff --git a/apps/web/platform/in-app-history.ts b/apps/web/platform/in-app-history.tsnew file mode 100644index 0000000000..57fbf17886--- /dev/null+++ b/apps/web/platform/in-app-history.ts@@ -0,0 +1,39 @@+/**+ * "Is there a Multica page behind this one?" for the web navigation adapter.+ *+ * Callers that want to step back (deleting an issue returns the user to the+ * list they opened it from) must not step back off the app when the current+ * page was opened cold — a shared link, a pasted URL, a new tab.+ *+ * Only the browser can answer this, and exactly one API does: the Navigation+ * API's `entries()` spans just the contiguous same-origin run around the+ * current entry, so arriving from an external site reports `canGoBack` false+ * even though the browser technically has somewhere to go. `history.length`+ * is no substitute — it counts other origins' entries too.+ *+ * Nothing else here is a guess. Counting the adapter's own `router.push`+ * calls looks like a workable fallback and is not: a push is a request, not a+ * committed history entry. Next drops it to `replaceState` when the canonical+ * URL is unchanged (`app-router.js`, the `pendingPush && href !== canonicalUrl`+ * branch), and pushes can also be superseded or abandoned mid-transition. Any+ * count derived from calls can therefore claim history that does not exist,+ * and a wrong `true` walks the user out of Multica — the precise failure this+ * exists to prevent. So where the browser cannot answer we report `false`,+ * and callers take their fallback path.+ */++/** Minimal shape of the Navigation API — not in TypeScript's DOM lib yet. */+type NavigationApi = { canGoBack: boolean };++/**+ * Whether a step back stays inside the app. `false` whenever the browser has+ * no Navigation API: the caller then navigates to its fallback, which is the+ * behaviour those browsers had before any of this existed.+ */+export function canGoBackInApp(): boolean {+ if (typeof window === "undefined") return false;+ const navigation = (window as { navigation?: unknown }).navigation as+ | NavigationApi+ | undefined;+ return navigation?.canGoBack === true;+}diff --git a/apps/web/platform/navigation.test.tsx b/apps/web/platform/navigation.test.tsxindex 1d7b4a1f6a..92ea813c51 100644--- a/apps/web/platform/navigation.test.tsx+++ b/apps/web/platform/navigation.test.tsx@@ -6,7 +6,7 @@* deployment's own origin. Desktop answers it by opening a tab; the web must* answer it with a router push, or those links silently do nothing.*/-import { describe, expect, it, vi, beforeEach } from "vitest";+import { describe, expect, it, vi, afterEach, beforeEach } from "vitest";import { render } from "@testing-library/react";const router = vi.hoisted(() => ({@@ -23,6 +23,7 @@ vi.mock("next/navigation", () => ({}));import { WebNavigationProvider } from "./navigation";+import { useNavigation, type NavigationAdapter } from "@multica/views/navigation";function navigate(path: string) {window.dispatchEvent(@@ -30,6 +31,20 @@ function navigate(path: string) {);}+function renderAdapter(): () => NavigationAdapter {+ let adapter: NavigationAdapter | null = null;+ function Probe() {+ adapter = useNavigation();+ return null;+ }+ render(+ <WebNavigationProvider>+ <Probe />+ </WebNavigationProvider>,+ );+ return () => adapter!;+}+beforeEach(() => {router.push.mockReset();});@@ -62,3 +77,49 @@ describe("WebNavigationProvider internal link bridge", () => {expect(router.push).not.toHaveBeenCalled();});});++/**+ * `canGoBack` decides whether a page whose subject was just deleted steps back+ * or replaces with a fallback. A wrong `true` walks the user out of Multica,+ * so the adapter must expose the browser's own answer and nothing derived.+ */+describe("WebNavigationProvider canGoBack", () => {+ const win = window as unknown as { navigation?: unknown };++ afterEach(() => {+ delete win.navigation;+ });++ it("passes through the Navigation API's answer", () => {+ win.navigation = { canGoBack: true };++ expect(renderAdapter()().canGoBack!()).toBe(true);+ });++ it("reads the answer live rather than freezing it at render", () => {+ win.navigation = { canGoBack: true };+ const adapter = renderAdapter();++ win.navigation = { canGoBack: false };++ expect(adapter().canGoBack!()).toBe(false);+ });++ // Regression (PR review, twice): a count of `push` calls stood in for real+ // history here. It could not — Next drops a push to `replaceState` when the+ // canonical URL is unchanged, so a push that committed no entry still made+ // this claim `true`. Calling push must not move this answer at all.+ it("is unmoved by a push that committed no history entry", () => {+ win.navigation = { canGoBack: false };+ const adapter = renderAdapter();++ adapter().push("/acme/issues");++ expect(router.push).toHaveBeenCalledWith("/acme/issues");+ expect(adapter().canGoBack!()).toBe(false);+ });++ it("reports false where the browser cannot answer, so callers use the fallback", () => {+ expect(renderAdapter()().canGoBack!()).toBe(false);+ });+});diff --git a/apps/web/platform/navigation.tsx b/apps/web/platform/navigation.tsxindex f840a8cd98..b682b688d2 100644--- a/apps/web/platform/navigation.tsx+++ b/apps/web/platform/navigation.tsx@@ -6,6 +6,7 @@ import {NavigationProvider,type NavigationAdapter,} from "@multica/views/navigation";+import { canGoBackInApp } from "./in-app-history";/*** Web half of the `multica:navigate` bridge — the event shared content@@ -40,6 +41,7 @@ function NavigationProviderInner({push: router.push,replace: router.replace,back: router.back,+ canGoBack: canGoBackInApp,pathname,searchParams: new URLSearchParams(searchParams.toString()),getShareableUrl: (path: string) =>diff --git a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsxindex e2c9e6c4b7..c92a52111d 100644--- a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx+++ b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx@@ -238,7 +238,7 @@ describe("IssueActionsDropdown", () => {<IssueActionsDropdownissue={mockIssue}trigger={<button data-testid="trigger">Menu</button>}- onDeletedNavigateTo="/test/issues"+ onDeletedFallbackPath="/test/issues"/>,),);@@ -250,7 +250,7 @@ describe("IssueActionsDropdown", () => {expect(mockOpenModal).toHaveBeenCalledWith("issue-delete-confirm", {issueId: "issue-1",identifier: "TES-1",- onDeletedNavigateTo: "/test/issues",+ onDeletedFallbackPath: "/test/issues",});});});diff --git a/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx b/packages/views/issues/actions/__tests__/use-issue-actions.test.tsxindex 536b5d719e..544883fc2d 100644--- a/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx+++ b/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx@@ -226,12 +226,12 @@ describe("useIssueActions", () => {});act(() => {- result.current.openDeleteConfirm({ onDeletedNavigateTo: "/test/issues" });+ result.current.openDeleteConfirm({ onDeletedFallbackPath: "/test/issues" });});expect(mockOpenModal).toHaveBeenLastCalledWith("issue-delete-confirm", {issueId: "issue-1",identifier: "TES-1",- onDeletedNavigateTo: "/test/issues",+ onDeletedFallbackPath: "/test/issues",});});diff --git a/packages/views/issues/actions/issue-actions-dropdown.tsx b/packages/views/issues/actions/issue-actions-dropdown.tsxindex ff574142ae..c65d635d27 100644--- a/packages/views/issues/actions/issue-actions-dropdown.tsx+++ b/packages/views/issues/actions/issue-actions-dropdown.tsx@@ -19,15 +19,16 @@ interface IssueActionsDropdownProps {/** A single React element cloned by Base UI as the trigger (via `render` prop). */trigger: ReactElement;align?: "start" | "end" | "center";- /** If set, navigate here after the issue is deleted. */- onDeletedNavigateTo?: string;+ /** If set, leave the page after the issue is deleted — back to wherever the+ * user came from, or to this path when there is no in-app history. */+ onDeletedFallbackPath?: string;}export function IssueActionsDropdown({issue,trigger,align = "end",- onDeletedNavigateTo,+ onDeletedFallbackPath,}: IssueActionsDropdownProps) {const actions = useIssueActions(issue);const [assigneeOpen, setAssigneeOpen] = useState(false);@@ -46,7 +47,7 @@ export function IssueActionsDropdown({actions={actions}primitives={dropdownPrimitives}onOpenAssignee={() => setAssigneeOpen(true)}- onDeletedNavigateTo={onDeletedNavigateTo}+ onDeletedFallbackPath={onDeletedFallbackPath}/></DropdownMenuContent></DropdownMenu>diff --git a/packages/views/issues/actions/issue-actions-menu-items.tsx b/packages/views/issues/actions/issue-actions-menu-items.tsxindex fe7a5396b6..c266df2ad6 100644--- a/packages/views/issues/actions/issue-actions-menu-items.tsx+++ b/packages/views/issues/actions/issue-actions-menu-items.tsx@@ -86,8 +86,11 @@ interface IssueActionsMenuItemsProps {* Decoupled this way so the same item can drive both the dropdown* (3-dot button) and the context menu (right-click) wrappers. */onOpenAssignee: () => void;- /** If set, navigate here after the issue is deleted (used by the detail page). */- onDeletedNavigateTo?: string;+ /** If set, leave the page after the issue is deleted (used by the detail+ * page, which renders the issue being deleted). The delete modal goes back+ * to the list the user came from and only falls back to this path when+ * there is no in-app history. List surfaces leave it unset and stay put. */+ onDeletedFallbackPath?: string;}export function IssueActionsMenuItems({@@ -95,7 +98,7 @@ export function IssueActionsMenuItems({actions,primitives: P,onOpenAssignee,- onDeletedNavigateTo,+ onDeletedFallbackPath,}: IssueActionsMenuItemsProps) {const { t } = useT("issues");const {@@ -305,7 +308,7 @@ export function IssueActionsMenuItems({<P.Itemvariant="destructive"- onClick={() => openDeleteConfirm({ onDeletedNavigateTo })}+ onClick={() => openDeleteConfirm({ onDeletedFallbackPath })}><Trash2 className="h-3.5 w-3.5" />{t(($) => $.actions.delete_issue)}diff --git a/packages/views/issues/actions/use-issue-actions.ts b/packages/views/issues/actions/use-issue-actions.tsindex e443fc0ed2..8a597f0348 100644--- a/packages/views/issues/actions/use-issue-actions.ts+++ b/packages/views/issues/actions/use-issue-actions.ts@@ -24,7 +24,7 @@ export interface UseIssueActionsResult {openSetParent: () => void;removeParent: () => void;openAddChild: () => void;- openDeleteConfirm: (opts?: { onDeletedNavigateTo?: string }) => void;+ openDeleteConfirm: (opts?: { onDeletedFallbackPath?: string }) => void;}/**@@ -185,12 +185,12 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {}, [openModal, issueId]);const openDeleteConfirm = useCallback(- (opts?: { onDeletedNavigateTo?: string }) => {+ (opts?: { onDeletedFallbackPath?: string }) => {if (!issueId) return;openModal("issue-delete-confirm", {issueId,identifier: issueIdentifier,- onDeletedNavigateTo: opts?.onDeletedNavigateTo,+ onDeletedFallbackPath: opts?.onDeletedFallbackPath,});},[openModal, issueId, issueIdentifier],diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex d0dcab5c83..6c962c9994 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -115,6 +115,7 @@ vi.mock("../../navigation", () => ({pathname: "/issues/issue-1",getShareableUrl: (p: string) => `https://app.multica.com${p}`,}),+ useBackOrReplace: () => vi.fn(),NavigationProvider: ({ children }: { children: React.ReactNode }) => children,}));@@ -897,13 +898,13 @@ describe("IssueDetail (shared)", () => {});});- it("shows 'Back to Issues' button when issue is not found and no onDelete prop", async () => {+ it("shows 'Back' button when issue is not found and no onDelete prop", async () => {mockApiObj.getIssue.mockRejectedValue(new Error("Not found"));renderIssueDetail("nonexistent-id");await waitFor(() => {- expect(screen.getByText("Back to Issues")).toBeInTheDocument();+ expect(screen.getByText("Back")).toBeInTheDocument();});});diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 4a3aef0c39..b276810a91 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -3,8 +3,7 @@import { useState, useEffect, useCallback, useMemo, useRef, Fragment } from "react";import { Virtuoso, type VirtuosoHandle } from "react-virtuoso";import { useDefaultLayout, usePanelRef } from "react-resizable-panels";-import { AppLink } from "../../navigation";-import { useNavigation } from "../../navigation";+import { AppLink, useBackOrReplace } from "../../navigation";import {Archive,Calendar,@@ -904,7 +903,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trconst { t } = useT("issues");const timeAgo = useTimeAgo();const id = issueId;- const router = useNavigation();+ const backOrReplace = useBackOrReplace();const user = useAuthStore((s) => s.user);const paths = useWorkspacePaths();@@ -1105,7 +1104,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// Fire `onDelete` once when the issue transitions from loaded to missing.// Delete goes through a shell-level modal, so the caller (e.g. inbox) can't// be notified directly — instead, the detail page observes its own cache- // clearing and runs the callback. We navigate via `onDeletedNavigateTo` on+ // clearing and runs the callback. We navigate via `onDeletedFallbackPath` on// the actions menu when no callback is supplied (standalone routes).const hadIssueRef = useRef(false);const firedDeleteCallbackRef = useRef(false);@@ -1754,9 +1753,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr<div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-sm text-muted-foreground"><p>{t(($) => $.detail.not_found)}</p>{!onDelete && (- <Button variant="outline" size="sm" onClick={() => router.push(paths.issues())}>+ <Button variant="outline" size="sm" onClick={() => backOrReplace(paths.issues())}><ChevronLeft className="mr-1 h-3.5 w-3.5" />- {t(($) => $.detail.back_to_issues)}+ {t(($) => $.detail.back)}</Button>)}</div>@@ -2280,8 +2279,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trissue={issue}align="end"// When a parent passes `onDelete`, we detect deletion via effect- // above and skip navigation. Otherwise the modal navigates for us.- onDeletedNavigateTo={onDelete ? undefined : paths.issues()}+ // above and skip navigation. Otherwise the modal takes us back+ // to the list we came from, falling back to all issues.+ onDeletedFallbackPath={onDelete ? undefined : paths.issues()}trigger={<Button variant="ghost" size="icon-sm" className="text-muted-foreground"><MoreHorizontal />diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex c74cb5db6a..4547f51f5b 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -233,7 +233,7 @@"detail": {"not_found": "This issue does not exist or has been deleted in this workspace.","breadcrumb_project_unknown": "Unknown project",- "back_to_issues": "Back to Issues",+ "back": "Back","title_placeholder": "Issue title","desc_placeholder": "Add description...","sub_issues_label": "Sub-issues",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 55d6d28fb0..0851034561 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -231,7 +231,7 @@"detail": {"not_found": "このイシューはこのワークスペースに存在しないか、削除されています。","breadcrumb_project_unknown": "不明なプロジェクト",- "back_to_issues": "イシューに戻る",+ "back": "戻る","title_placeholder": "イシューのタイトル","desc_placeholder": "説明を追加...","sub_issues_label": "サブイシュー",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 0e872e88db..d8a6065494 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -231,7 +231,7 @@"detail": {"not_found": "이 워크스페이스에 해당 이슈가 없거나 삭제되었습니다.","breadcrumb_project_unknown": "알 수 없는 프로젝트",- "back_to_issues": "이슈로 돌아가기",+ "back": "뒤로","title_placeholder": "이슈 제목","desc_placeholder": "설명 추가...","sub_issues_label": "하위 이슈",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex e10e68f3c9..37999d66c8 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -231,7 +231,7 @@"detail": {"not_found": "这个 issue 不存在或已在该工作区被删除。","breadcrumb_project_unknown": "未知项目",- "back_to_issues": "返回 issue 列表",+ "back": "返回","title_placeholder": "issue 标题","desc_placeholder": "添加描述...","sub_issues_label": "子 issue",diff --git a/packages/views/modals/delete-issue-confirm.test.tsx b/packages/views/modals/delete-issue-confirm.test.tsxnew file mode 100644index 0000000000..f94a758eea--- /dev/null+++ b/packages/views/modals/delete-issue-confirm.test.tsx@@ -0,0 +1,129 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import { DeleteIssueConfirmModal } from "./delete-issue-confirm";+import { NavigationProvider } from "../navigation";+import type { NavigationAdapter } from "../navigation";++const mockDelete = vi.fn().mockResolvedValue(undefined);+vi.mock("@multica/core/issues/mutations", () => ({+ useDeleteIssue: () => ({ mutateAsync: mockDelete }),+}));++vi.mock("sonner", () => ({+ toast: { success: vi.fn(), error: vi.fn() },+}));++vi.mock("../i18n", () => ({+ useT: () => ({+ t: (sel: (x: Record<string, Record<string, string>>) => string) =>+ sel({+ delete_issue: {+ title: "Delete issue?",+ description: "This cannot be undone.",+ hint: "Sub-issues are deleted too.",+ cancel: "Cancel",+ confirm: "Delete",+ deleting: "Deleting...",+ toast_deleted: "Issue deleted",+ toast_delete_failed: "Delete failed",+ },+ }),+ }),+}));++function makeAdapter(+ overrides: Partial<NavigationAdapter> = {},+): NavigationAdapter {+ return {+ push: vi.fn(),+ replace: vi.fn(),+ back: vi.fn(),+ pathname: "/acme/issues/issue-1",+ searchParams: new URLSearchParams(),+ getShareableUrl: (p) => p,+ ...overrides,+ };+}++async function deleteWith(+ adapter: NavigationAdapter,+ data: Record<string, unknown> | null,+) {+ const onClose = vi.fn();+ render(+ <NavigationProvider value={adapter}>+ <DeleteIssueConfirmModal onClose={onClose} data={data} />+ </NavigationProvider>,+ );+ fireEvent.click(screen.getByText("Delete"));+ await waitFor(() => expect(mockDelete).toHaveBeenCalledWith("issue-1"));+ return onClose;+}++describe("DeleteIssueConfirmModal", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ // The bug this guards (GH #5995): deleting from an issue opened out of My+ // Issues used to hard-push the workspace Issues list, dropping the user's+ // navigation context. The same applied to project lists, search and pins.+ it("returns to the list the issue was opened from", async () => {+ const adapter = makeAdapter({ canGoBack: () => true });++ await deleteWith(adapter, {+ issueId: "issue-1",+ onDeletedFallbackPath: "/acme/issues",+ });++ await waitFor(() => expect(adapter.back).toHaveBeenCalledTimes(1));+ expect(adapter.replace).not.toHaveBeenCalled();+ expect(adapter.push).not.toHaveBeenCalled();+ });++ it("falls back to the workspace list when the issue was opened cold", async () => {+ const adapter = makeAdapter({ canGoBack: () => false });++ await deleteWith(adapter, {+ issueId: "issue-1",+ onDeletedFallbackPath: "/acme/issues",+ });++ await waitFor(() =>+ expect(adapter.replace).toHaveBeenCalledWith("/acme/issues"),+ );+ expect(adapter.back).not.toHaveBeenCalled();+ });++ // List surfaces delete in place (row context menu, batch toolbar): there is+ // no page to leave, so the modal must not navigate at all.+ it("does not navigate when no fallback path is supplied", async () => {+ const adapter = makeAdapter({ canGoBack: () => true });++ const onClose = await deleteWith(adapter, { issueId: "issue-1" });++ await waitFor(() => expect(onClose).toHaveBeenCalled());+ expect(adapter.back).not.toHaveBeenCalled();+ expect(adapter.replace).not.toHaveBeenCalled();+ expect(adapter.push).not.toHaveBeenCalled();+ });++ it("stays put when the delete fails", async () => {+ mockDelete.mockRejectedValueOnce(new Error("nope"));+ const adapter = makeAdapter({ canGoBack: () => true });++ render(+ <NavigationProvider value={adapter}>+ <DeleteIssueConfirmModal+ onClose={vi.fn()}+ data={{ issueId: "issue-1", onDeletedFallbackPath: "/acme/issues" }}+ />+ </NavigationProvider>,+ );+ fireEvent.click(screen.getByText("Delete"));++ await waitFor(() => expect(screen.getByText("Delete")).toBeInTheDocument());+ expect(adapter.back).not.toHaveBeenCalled();+ expect(adapter.replace).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/modals/delete-issue-confirm.tsx b/packages/views/modals/delete-issue-confirm.tsxindex ffe254d9de..066de4e814 100644--- a/packages/views/modals/delete-issue-confirm.tsx+++ b/packages/views/modals/delete-issue-confirm.tsx@@ -13,7 +13,7 @@ import {AlertDialogTitle,} from "@multica/ui/components/ui/alert-dialog";import { useDeleteIssue } from "@multica/core/issues/mutations";-import { useNavigation } from "../navigation";+import { useBackOrReplace } from "../navigation";import { useT } from "../i18n";export function DeleteIssueConfirmModal({@@ -25,10 +25,12 @@ export function DeleteIssueConfirmModal({}) {const { t } = useT("modals");const issueId = (data?.issueId as string) || "";- const navigateTo = (data?.onDeletedNavigateTo as string | undefined) || undefined;+ // Set only by callers that are rendering the issue we are about to delete+ // (the detail page). List surfaces leave it undefined and simply stay put.+ const fallbackPath = (data?.onDeletedFallbackPath as string | undefined) || undefined;const [deleting, setDeleting] = useState(false);const deleteIssue = useDeleteIssue();- const navigation = useNavigation();+ const backOrReplace = useBackOrReplace();const handleDelete = async () => {if (!issueId) return;@@ -37,7 +39,9 @@ export function DeleteIssueConfirmModal({await deleteIssue.mutateAsync(issueId);toast.success(t(($) => $.delete_issue.toast_deleted));onClose();- if (navigateTo) navigation.push(navigateTo);+ // Back to whichever list the user opened this issue from; `fallbackPath`+ // only kicks in when there is no in-app history to step back into.+ if (fallbackPath) backOrReplace(fallbackPath);} catch (err) {toast.error(err instanceof Error && err.messagediff --git a/packages/views/navigation/index.ts b/packages/views/navigation/index.tsindex df579ebb97..ba3cd06599 100644--- a/packages/views/navigation/index.ts+++ b/packages/views/navigation/index.ts@@ -6,4 +6,5 @@ export {export { AppLink } from "./app-link";export { useAppOrigin } from "./use-app-origin";export { useRowLink } from "./use-row-link";+export { useBackOrReplace } from "./use-back-or-replace";export type { NavigationAdapter } from "./types";diff --git a/packages/views/navigation/types.ts b/packages/views/navigation/types.tsindex 646b37e466..1edfd15032 100644--- a/packages/views/navigation/types.ts+++ b/packages/views/navigation/types.ts@@ -26,4 +26,14 @@ export interface NavigationAdapter {* already loads the whole SPA. Callers must invoke via `prefetch?.(href)`.*/prefetch?: (path: string) => void;+ /**+ * Optional: is there an in-app page behind the current one, so that `back()`+ * lands somewhere inside Multica rather than stepping off the app? Only the+ * platform can answer — web reads the browser's session history, desktop the+ * active tab's virtual history. Adapters that cannot answer leave this+ * undefined and callers must treat that as `false`.+ *+ * Read it through `useBackOrReplace()` rather than calling it directly.+ */+ canGoBack?: () => boolean;}diff --git a/packages/views/navigation/use-back-or-replace.test.tsx b/packages/views/navigation/use-back-or-replace.test.tsxnew file mode 100644index 0000000000..ccfd1fa10a--- /dev/null+++ b/packages/views/navigation/use-back-or-replace.test.tsx@@ -0,0 +1,73 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import { NavigationProvider } from "./context";+import { useBackOrReplace } from "./use-back-or-replace";+import type { NavigationAdapter } from "./types";++function makeAdapter(+ overrides: Partial<NavigationAdapter> = {},+): NavigationAdapter {+ return {+ push: vi.fn(),+ replace: vi.fn(),+ back: vi.fn(),+ pathname: "/",+ searchParams: new URLSearchParams(),+ getShareableUrl: (p) => p,+ ...overrides,+ };+}++function Probe() {+ const backOrReplace = useBackOrReplace();+ return (+ <button onClick={() => backOrReplace("/acme/issues")}>leave</button>+ );+}++function renderProbe(adapter: NavigationAdapter) {+ render(+ <NavigationProvider value={adapter}>+ <Probe />+ </NavigationProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "leave" }));+}++describe("useBackOrReplace", () => {+ it("goes back when the platform reports in-app history", () => {+ const adapter = makeAdapter({ canGoBack: () => true });++ renderProbe(adapter);++ expect(adapter.back).toHaveBeenCalledTimes(1);+ expect(adapter.replace).not.toHaveBeenCalled();+ expect(adapter.push).not.toHaveBeenCalled();+ });++ it("replaces with the fallback when there is nothing to go back to", () => {+ const adapter = makeAdapter({ canGoBack: () => false });++ renderProbe(adapter);++ expect(adapter.replace).toHaveBeenCalledWith("/acme/issues");+ expect(adapter.back).not.toHaveBeenCalled();+ });++ it("replaces with the fallback when the adapter cannot report history", () => {+ const adapter = makeAdapter();++ renderProbe(adapter);++ expect(adapter.replace).toHaveBeenCalledWith("/acme/issues");+ expect(adapter.back).not.toHaveBeenCalled();+ });++ it("never pushes — the page being left is dead and must not stay in history", () => {+ const adapter = makeAdapter({ canGoBack: () => false });++ renderProbe(adapter);++ expect(adapter.push).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/navigation/use-back-or-replace.ts b/packages/views/navigation/use-back-or-replace.tsnew file mode 100644index 0000000000..81ec056f55--- /dev/null+++ b/packages/views/navigation/use-back-or-replace.ts@@ -0,0 +1,41 @@+"use client";++import { useCallback } from "react";+import { useNavigation } from "./context";++/**+ * Leave a page whose subject no longer exists, returning the user to wherever+ * they came from.+ *+ * Deleting an issue from its detail page is the canonical case: the user may+ * have opened it from My Issues, a project's list, a search result or a pin,+ * and every one of those is a better destination than a hardcoded workspace+ * list. Going back is the only thing that knows which — no caller has to+ * thread a "source view" through the URL or a store.+ *+ * `fallback` covers the case where there is nothing to go back to: a shared+ * link opened cold, a new tab, a pasted URL. Stepping back from those would+ * leave Multica entirely, so we navigate to `fallback` instead.+ *+ * It also covers every platform that cannot answer the question — the desktop+ * issue window, test stubs, and browsers with no Navigation API. That branch+ * is the behaviour those surfaces had before this hook existed, so a platform+ * going quiet costs the user a better destination and nothing more. Only ever+ * answer `canGoBack` from something that knows; a hopeful guess here is what+ * puts a user outside the app.+ *+ * Never `push`: the page we are leaving is dead, so its URL must not be left+ * on the back stack for the back button to land on a 404. Stepping back still+ * leaves it ahead of us in forward history — that is the browser's own+ * contract, and reachable only by an explicit Forward.+ */+export function useBackOrReplace(): (fallback: string) => void {+ const { back, replace, canGoBack } = useNavigation();+ return useCallback(+ (fallback: string) => {+ if (canGoBack?.() === true) back();+ else replace(fallback);+ },+ [back, replace, canGoBack],+ );+}