Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(issues): support human-readable issue URLs using issue keys (MUL-5354) (#6117)

Bohan Jiang577018649ea1
diff --git a/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx b/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx
index d3ad064582..81e34992ca 100644
--- a/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx
+++ b/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx
@@ -1,14 +1,16 @@
import { useParams } from "react-router-dom";
-import { useQuery } from "@tanstack/react-query";
-import { IssueDetail } from "@multica/views/issues/components";
+import { IssueDetailRoute } from "@multica/views/issues/components";
import { useWorkspaceId } from "@multica/core/hooks";
-import { issueDetailOptions } from "@multica/core/issues/queries";
+import { useCanonicalIssue } from "@multica/core/issues/canonical-id";
import { useDocumentTitle } from "@/hooks/use-document-title";
export function IssueDetailPage({ onDelete }: { onDelete?: () => void }) {
const { id } = useParams<{ id: string }>();
const wsId = useWorkspaceId();
- const { data: issue } = useQuery(issueDetailOptions(wsId, id!));
+ // `id` may be an identifier (`MUL-123`); resolving here means the title
+ // watches the same UUID-keyed entry realtime events patch. Shares its
+ // queries with the IssueDetailRoute below, so it costs no extra request.
+ const { issue } = useCanonicalIssue(wsId, id ?? "");
useDocumentTitle(issue ? `${issue.identifier}: ${issue.title}` : "Issue");
@@ -16,5 +18,5 @@ export function IssueDetailPage({ onDelete }: { onDelete?: () => void }) {
// Render errors bubble to the root route errorElement (DesktopRouteErrorPage),
// which contains the crash inside the tab content pane. No page-level boundary
// here — a whole-page wrapper duplicates the route-level error UI.
- return <IssueDetail issueId={id} onDelete={onDelete} />;
+ return <IssueDetailRoute routeId={id} onDelete={onDelete} />;
}
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/page.tsx
index 6f90958db8..999948f8e1 100644
--- a/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/page.tsx
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/page.tsx
@@ -1,7 +1,7 @@
"use client";
import { use } from "react";
-import { IssueDetail } from "@multica/views/issues/components";
+import { IssueDetailRoute } from "@multica/views/issues/components";
import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";
export default function IssueDetailPage({
@@ -12,7 +12,7 @@ export default function IssueDetailPage({
const { id } = use(params);
return (
<ErrorBoundary resetKeys={[id]}>
- <IssueDetail issueId={id} />
+ <IssueDetailRoute routeId={id} />
</ErrorBoundary>
);
}
diff --git a/packages/core/issues/canonical-id.test.tsx b/packages/core/issues/canonical-id.test.tsx
new file mode 100644
index 0000000000..1abe1f1701
--- /dev/null
+++ b/packages/core/issues/canonical-id.test.tsx
@@ -0,0 +1,176 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { setApiInstance } from "../api";
+import type { ApiClient } from "../api/client";
+import type { Issue } from "../types";
+import { createQueryClient } from "../query-client";
+import { issueKeys } from "./queries";
+import { isIssueUuid, useCanonicalIssue } from "./canonical-id";
+
+const ISSUE_UUID = "cb240efb-154c-42a8-ae92-42b02676feca";
+
+const issue = {
+ id: ISSUE_UUID,
+ workspace_id: "ws-1",
+ number: 134,
+ identifier: "TRS-134",
+ title: "Example",
+ status: "todo",
+ priority: "medium",
+} as Issue;
+
+function createWrapper(qc: QueryClient) {
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
+ };
+}
+
+describe("isIssueUuid", () => {
+ it("distinguishes a UUID from an issue identifier", () => {
+ expect(isIssueUuid(ISSUE_UUID)).toBe(true);
+ expect(isIssueUuid(ISSUE_UUID.toUpperCase())).toBe(true);
+ expect(isIssueUuid("TRS-134")).toBe(false);
+ expect(isIssueUuid("trs-134")).toBe(false);
+ expect(isIssueUuid("")).toBe(false);
+ });
+});
+
+describe("useCanonicalIssue", () => {
+ let qc: QueryClient;
+ let getIssue: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ // The app's real client, NOT a bare `new QueryClient()`. Its
+ // `staleTime: Infinity` is load-bearing here: under the library default of
+ // 0 every cache entry is stale the instant it lands, so a second observer
+ // background-refetches and a request-count assertion measures the harness
+ // rather than the code.
+ qc = createQueryClient();
+ getIssue = vi.fn(async () => issue);
+ setApiInstance({ getIssue } as unknown as ApiClient);
+ });
+
+ afterEach(() => {
+ qc.clear();
+ vi.restoreAllMocks();
+ });
+
+ // A UUID segment needs no resolution step, so the only request is the detail
+ // read the issue view needs anyway — never an extra one.
+ it("passes a UUID through without a resolution request", async () => {
+ const { result } = renderHook(() => useCanonicalIssue("ws-1", ISSUE_UUID), {
+ wrapper: createWrapper(qc),
+ });
+
+ expect(result.current.canonicalId).toBe(ISSUE_UUID);
+ expect(result.current.isResolving).toBe(false);
+
+ await waitFor(() => expect(result.current.issue).toEqual(issue));
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(getIssue).toHaveBeenCalledTimes(1);
+ expect(getIssue).toHaveBeenCalledWith(ISSUE_UUID);
+ });
+
+ it("resolves an identifier to the issue UUID", async () => {
+ const { result } = renderHook(() => useCanonicalIssue("ws-1", "TRS-134"), {
+ wrapper: createWrapper(qc),
+ });
+
+ expect(result.current.isResolving).toBe(true);
+ await waitFor(() => expect(result.current.canonicalId).toBe(ISSUE_UUID));
+ expect(result.current.isResolving).toBe(false);
+ expect(result.current.issue).toEqual(issue);
+ expect(getIssue).toHaveBeenCalledWith("TRS-134");
+ });
+
+ // The whole point of `initialData` over a post-resolve cache seed: the
+ // canonical query must never observe an empty cache and start its own fetch.
+ // A seed from an effect runs after that decision.
+ it("opens an identifier URL with exactly one request", async () => {
+ const { result } = renderHook(() => useCanonicalIssue("ws-1", "TRS-134"), {
+ wrapper: createWrapper(qc),
+ });
+
+ await waitFor(() => expect(result.current.issue).toEqual(issue));
+ // Let any follow-up fetch settle before counting.
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(getIssue).toHaveBeenCalledTimes(1);
+ });
+
+ // The realtime updaters patch `issueKeys.detail(wsId, issue.id)` with the
+ // UUID from the websocket payload; the resolution response is older and must
+ // never overwrite it.
+ it("does not clobber a realtime-patched entry", async () => {
+ const patched = { ...issue, status: "done" } as Issue;
+ qc.setQueryData(issueKeys.detail("ws-1", ISSUE_UUID), patched);
+
+ const { result } = renderHook(() => useCanonicalIssue("ws-1", "TRS-134"), {
+ wrapper: createWrapper(qc),
+ });
+
+ await waitFor(() => expect(result.current.canonicalId).toBe(ISSUE_UUID));
+ expect(result.current.issue).toEqual(patched);
+ expect(qc.getQueryData(issueKeys.detail("ws-1", ISSUE_UUID))).toEqual(patched);
+ });
+
+ it("reports a nonexistent identifier as terminally not-found", async () => {
+ getIssue.mockRejectedValue(new Error("issue not found"));
+
+ const { result } = renderHook(() => useCanonicalIssue("ws-1", "ZZZ-134"), {
+ wrapper: createWrapper(qc),
+ });
+
+ // Generous timeout on purpose: the app's client retries once, so a
+ // genuinely unresolvable identifier takes a retry round-trip to settle.
+ await waitFor(() => expect(result.current.notFound).toBe(true), { timeout: 5000 });
+ expect(result.current.canonicalId).toBeNull();
+ expect(result.current.issue).toBeUndefined();
+ // Must NOT read as still-resolving: a caller that keeps showing a loading
+ // frame here re-enters the remount loop this state exists to prevent.
+ expect(result.current.isResolving).toBe(false);
+ });
+
+ // Regression: a failed resolution used to present as "not resolving, no id",
+ // so the route handed the raw identifier to IssueDetail, whose observer
+ // refetched the failed query, flipped this hook back to resolving, unmounted
+ // IssueDetail, and remounted it on the next failure — tens of thousands of
+ // requests in under a second, with the UI stuck on the skeleton.
+ it("settles a failed resolution without looping requests", async () => {
+ const noRetry = new QueryClient({
+ // Retry off isolates the loop from the app's `retry: 1`, so a count above
+ // 1 can only mean a remount refetched.
+ defaultOptions: { queries: { staleTime: Infinity, retry: false } },
+ });
+ getIssue.mockRejectedValue(new Error("issue not found"));
+
+ const { result, rerender } = renderHook(() => useCanonicalIssue("ws-1", "ZZZ-134"), {
+ wrapper: createWrapper(noRetry),
+ });
+
+ await waitFor(() => expect(result.current.notFound).toBe(true));
+ const settled = getIssue.mock.calls.length;
+ expect(settled).toBe(1);
+
+ rerender();
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(getIssue).toHaveBeenCalledTimes(settled);
+ expect(result.current.notFound).toBe(true);
+
+ noRetry.clear();
+ });
+
+ it("stays idle without a workspace id", () => {
+ const { result } = renderHook(() => useCanonicalIssue("", "TRS-134"), {
+ wrapper: createWrapper(qc),
+ });
+
+ expect(result.current.canonicalId).toBeNull();
+ expect(result.current.isResolving).toBe(false);
+ expect(getIssue).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/issues/canonical-id.ts b/packages/core/issues/canonical-id.ts
new file mode 100644
index 0000000000..bc52ec3069
--- /dev/null
+++ b/packages/core/issues/canonical-id.ts
@@ -0,0 +1,84 @@
+import { useQuery } from "@tanstack/react-query";
+import type { Issue } from "../types";
+import { issueDetailOptions } from "./queries";
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+/** True for a canonical issue UUID; false for an identifier like `MUL-123`. */
+export function isIssueUuid(value: string): boolean {
+ return UUID_RE.test(value);
+}
+
+export interface CanonicalIssue {
+ /**
+ * The issue's UUID, or `null` while an identifier is still resolving or if
+ * it resolved to nothing.
+ */
+ canonicalId: string | null;
+ /** The issue itself, read from the UUID-keyed entry. */
+ issue: Issue | undefined;
+ isResolving: boolean;
+ /**
+ * Terminal: this identifier does not name an issue in this workspace.
+ *
+ * Callers MUST branch on this and render a not-found state rather than
+ * handing the unresolved segment to a view that will query it again. A
+ * second observer mounting on the failed query refetches it
+ * (`retryOnMount`), which flips this hook back to resolving, unmounts that
+ * view, and remounts it when the refetch fails — an unbounded request loop
+ * that never settles on "not found".
+ */
+ notFound: boolean;
+}
+
+/**
+ * Resolve a raw `/{ws}/issues/{segment}` route parameter — a UUID or a
+ * human-readable identifier (`MUL-123`) — to the issue and its UUID.
+ *
+ * Why callers must key on the UUID rather than the raw segment: the realtime
+ * updaters patch `issueKeys.detail(wsId, issue.id)` with the UUID carried by
+ * the websocket payload (`ws-updaters.ts`). A view keyed on the identifier
+ * would sit on a cache entry no realtime event can ever reach, so the detail
+ * page would render fine and then silently stop updating. The identifier stays
+ * a presentation concern: it lives in the URL, never in a cache key.
+ *
+ * Resolution reuses `GET /api/issues/{id}`, which accepts either form, so it is
+ * the same request the detail view would have made anyway. Handing that
+ * response to the canonical query as `initialData` is what holds it to ONE
+ * request: `initialData` is applied while the observer is created, so the
+ * canonical query never observes an empty cache and never fires a fetch of its
+ * own. Seeding the cache from an effect instead would run after that decision
+ * and leave the single-request property resting on hook ordering.
+ */
+export function useCanonicalIssue(wsId: string, routeId: string): CanonicalIssue {
+ const isUuid = isIssueUuid(routeId);
+ const resolveEnabled = !isUuid && !!wsId && !!routeId;
+
+ const resolve = useQuery({
+ ...issueDetailOptions(wsId, routeId),
+ enabled: resolveEnabled,
+ });
+
+ const canonicalId = isUuid ? routeId : (resolve.data?.id ?? null);
+
+ const detail = useQuery({
+ ...issueDetailOptions(wsId, canonicalId ?? ""),
+ enabled: !!canonicalId && !!wsId,
+ // Ignored once the entry holds data, so a row already patched by a realtime
+ // event is never overwritten by this older resolution response.
+ initialData: isUuid ? undefined : resolve.data,
+ });
+
+ // Read the resolution query's own settled state rather than "pending and no
+ // data": a failed resolution must present as terminally not-found, never as
+ // still-resolving, or the caller flips back to a loading frame and the
+ // remount loop described on `notFound` starts.
+ const failed = resolveEnabled && resolve.isError;
+
+ return {
+ canonicalId,
+ issue: detail.data,
+ isResolving: resolveEnabled && !failed && resolve.data === undefined,
+ notFound: failed,
+ };
+}
diff --git a/packages/core/issues/index.ts b/packages/core/issues/index.ts
index 27d30d45ef..f8048761fc 100644
--- a/packages/core/issues/index.ts
+++ b/packages/core/issues/index.ts
@@ -1,4 +1,5 @@
export * from "./store";
+export * from "./canonical-id";
export * from "./queries";
export * from "./mutations";
export * from "./ws-updaters";
diff --git a/packages/core/package.json b/packages/core/package.json
index 90a0bafdbf..5aa6fe111e 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -28,6 +28,7 @@
"./workspace/avatar-url": "./workspace/avatar-url.ts",
"./issues": "./issues/index.ts",
"./issues/batch": "./issues/batch.ts",
+ "./issues/canonical-id": "./issues/canonical-id.ts",
"./issues/queries": "./issues/queries.ts",
"./issues/mutations": "./issues/mutations.ts",
"./issues/timeline-sort": "./issues/timeline-sort.ts",
diff --git a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
index 7d9ec8b211..656c1b140e 100644
--- a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
+++ b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
@@ -291,9 +291,11 @@ describe("Open in new tab", () => {
await openMenuAndClickOpenInNewTab();
// `activate: true` — an explicit CTA moves the user into the new context,
- // unlike modifier-click, which stashes a background tab.
+ // unlike modifier-click, which stashes a background tab. The path carries
+ // the identifier, matching copyLink, so the opened tab is already on the
+ // canonical URL instead of being rewritten off the UUID after it lands.
expect(openInNewTabMock).toHaveBeenCalledWith(
- "/test/issues/issue-1",
+ "/test/issues/TES-1",
"TES-1",
{ activate: true },
);
@@ -311,9 +313,9 @@ describe("Open in new tab", () => {
await openMenuAndClickOpenInNewTab();
expect(openInNewTabMock).not.toHaveBeenCalled();
- expect(getShareableUrlMock).toHaveBeenCalledWith("/test/issues/issue-1");
+ expect(getShareableUrlMock).toHaveBeenCalledWith("/test/issues/TES-1");
expect(windowOpen).toHaveBeenCalledWith(
- "https://app.example/test/issues/issue-1",
+ "https://app.example/test/issues/TES-1",
"_blank",
"noopener,noreferrer",
);
diff --git a/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx b/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx
index 544883fc2d..ed029f7815 100644
--- a/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx
+++ b/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx
@@ -188,13 +188,28 @@ describe("useIssueActions", () => {
expect(mockOpenModal).not.toHaveBeenCalled();
});
- it("copyLink writes the issue's shareable URL to the clipboard", async () => {
+ it("copyLink writes the issue's human-readable shareable URL to the clipboard", async () => {
const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });
await act(async () => {
await result.current.copyLink();
});
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ "https://app.multica.com/test/issues/TES-1",
+ );
+ });
+
+ it("copyLink falls back to the UUID when the issue has no identifier", async () => {
+ const { result } = renderHook(
+ () => useIssueActions({ ...mockIssue, identifier: "" } as Issue),
+ { wrapper },
+ );
+
+ await act(async () => {
+ await result.current.copyLink();
+ });
+
expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
"https://app.multica.com/test/issues/issue-1",
);
diff --git a/packages/views/issues/actions/use-issue-actions.ts b/packages/views/issues/actions/use-issue-actions.ts
index 74691bca0f..de53cf72ad 100644
--- a/packages/views/issues/actions/use-issue-actions.ts
+++ b/packages/views/issues/actions/use-issue-actions.ts
@@ -119,7 +119,11 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {
// back to a real browser tab via the shareable URL.
const openInNewTab = useCallback(() => {
if (!issueId) return;
- const path = paths.issueDetail(issueId);
+ // Identifier form, same as copyLink: on web this becomes a real browser
+ // tab at the shareable URL, so it is a link the user sees and may copy out
+ // of the address bar. Opening on the UUID would also make the route
+ // immediately rewrite the fresh tab's URL.
+ const path = paths.issueDetail(issueIdentifier || issueId);
if (navigation.openInNewTab) {
navigation.openInNewTab(path, issueIdentifier ?? undefined, {
activate: true,
@@ -144,13 +148,16 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {
const copyLink = useCallback(async () => {
if (!issueId) return;
- const url = navigation.getShareableUrl(paths.issueDetail(issueId));
+ // Share the identifier form (`/{ws}/issues/MUL-123`): a pasted link should
+ // say which issue it points at. The UUID form stays valid, so links copied
+ // before this still resolve.
+ const url = navigation.getShareableUrl(paths.issueDetail(issueIdentifier || issueId));
if (await copyText(url)) {
toast.success(t(($) => $.detail.link_copied));
} else {
toast.error(t(($) => $.detail.link_copy_failed));
}
- }, [paths, issueId, navigation, t]);
+ }, [paths, issueId, issueIdentifier, navigation, t]);
const openCreateSubIssue = useCallback(() => {
if (!issueId) return;
diff --git a/packages/views/issues/components/index.ts b/packages/views/issues/components/index.ts
index 5defb51fd5..b07438c40c 100644
--- a/packages/views/issues/components/index.ts
+++ b/packages/views/issues/components/index.ts
@@ -2,7 +2,8 @@ export { StatusIcon } from "./status-icon";
export { StatusHeading } from "./status-heading";
export { PriorityIcon } from "./priority-icon";
export { StatusPicker, PriorityPicker, StagePicker, AssigneePicker, canAssignAgent, StartDatePicker, DueDatePicker, LabelPicker } from "./pickers";
-export { IssueDetail } from "./issue-detail";
+export { IssueDetail, IssueDetailSkeleton } from "./issue-detail";
+export { IssueDetailRoute } from "./issue-detail-route";
export { IssuesPage } from "./issues-page";
export { CommentCard } from "./comment-card";
export { CommentInput } from "./comment-input";
diff --git a/packages/views/issues/components/issue-detail-route.test.tsx b/packages/views/issues/components/issue-detail-route.test.tsx
new file mode 100644
index 0000000000..90275944b9
--- /dev/null
+++ b/packages/views/issues/components/issue-detail-route.test.tsx
@@ -0,0 +1,149 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
+import { NavigationProvider } from "../../navigation";
+import type { NavigationAdapter } from "../../navigation";
+import { IssueDetailRoute, useCanonicalIssueUrl } from "./issue-detail-route";
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
+
+vi.mock("@multica/core/paths", async () => {
+ const actual = await vi.importActual<typeof import("@multica/core/paths")>(
+ "@multica/core/paths",
+ );
+ return {
+ ...actual,
+ useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme", slug: "acme" }),
+ useWorkspacePaths: () => actual.paths.workspace("acme"),
+ };
+});
+
+const replace = vi.fn();
+const push = vi.fn();
+
+function wrapper({ children }: { children: ReactNode }) {
+ const adapter: NavigationAdapter = {
+ push,
+ replace,
+ back: vi.fn(),
+ pathname: "/acme/issues/x",
+ searchParams: new URLSearchParams(),
+ getShareableUrl: (p: string) => `https://app.multica.com${p}`,
+ };
+ return <NavigationProvider value={adapter}>{children}</NavigationProvider>;
+}
+
+describe("useCanonicalIssueUrl", () => {
+ beforeEach(() => {
+ replace.mockClear();
+ push.mockClear();
+ });
+
+ it("rewrites a UUID URL to the identifier once the issue resolves", () => {
+ const { rerender } = renderHook(
+ ({ identifier }: { identifier?: string }) =>
+ useCanonicalIssueUrl("cb240efb-154c-42a8-ae92-42b02676feca", identifier),
+ { wrapper, initialProps: {} },
+ );
+
+ // Nothing to rewrite to while the issue is still loading.
+ expect(replace).not.toHaveBeenCalled();
+
+ rerender({ identifier: "TRS-134" });
+ expect(replace).toHaveBeenCalledWith("/acme/issues/TRS-134");
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it("leaves an already-canonical URL alone", () => {
+ renderHook(() => useCanonicalIssueUrl("TRS-134", "TRS-134"), { wrapper });
+ expect(replace).not.toHaveBeenCalled();
+ });
+
+ // `useWorkspacePaths()` returns a fresh object per call, so the effect's
+ // dependencies change identity on every commit. Without the ref guard this
+ // re-fired the replace forever.
+ it("rewrites once, not on every render", () => {
+ const { rerender } = renderHook(
+ () => useCanonicalIssueUrl("cb240efb-154c-42a8-ae92-42b02676feca", "TRS-134"),
+ { wrapper },
+ );
+
+ rerender();
+ rerender();
+ expect(replace).toHaveBeenCalledTimes(1);
+ });
+
+ // A lowercase key resolves server-side, so the URL must still be normalized
+ // to the issue's real identifier rather than left as typed.
+ it("normalizes a differently-cased identifier segment", () => {
+ renderHook(() => useCanonicalIssueUrl("trs-134", "TRS-134"), { wrapper });
+ expect(replace).toHaveBeenCalledWith("/acme/issues/TRS-134");
+ });
+});
+
+describe("IssueDetailRoute with an identifier that names no issue", () => {
+ // Regression: the route used to fall through to IssueDetail with the raw
+ // identifier. IssueDetail mounted a second observer on the query that had
+ // just failed, `retryOnMount` refetched it, the route flipped back to its
+ // skeleton and unmounted IssueDetail, then remounted it when the refetch
+ // failed — an unbounded request loop that never reached "not found".
+ // Retry is off so any count above 1 can only be a remount refetch.
+ it("settles on not-found without looping requests", async () => {
+ replace.mockClear();
+ push.mockClear();
+ const getIssue = vi.fn().mockRejectedValue(new Error("issue not found"));
+ setApiInstance({ getIssue } as unknown as ApiClient);
+ const qc = new QueryClient({
+ defaultOptions: { queries: { staleTime: Infinity, retry: false } },
+ });
+
+ const { rerender } = render(
+ <QueryClientProvider client={qc}>
+ <NavigationProvider
+ value={{
+ push,
+ replace,
+ back: vi.fn(),
+ pathname: "/acme/issues/ZZZ-134",
+ searchParams: new URLSearchParams(),
+ getShareableUrl: (p: string) => `https://app.multica.com${p}`,
+ }}
+ >
+ <IssueDetailRoute routeId="ZZZ-134" />
+ </NavigationProvider>
+ </QueryClientProvider>,
+ );
+
+ await waitFor(() => expect(getIssue).toHaveBeenCalled());
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ expect(getIssue).toHaveBeenCalledTimes(1);
+
+ rerender(
+ <QueryClientProvider client={qc}>
+ <NavigationProvider
+ value={{
+ push,
+ replace,
+ back: vi.fn(),
+ pathname: "/acme/issues/ZZZ-134",
+ searchParams: new URLSearchParams(),
+ getShareableUrl: (p: string) => `https://app.multica.com${p}`,
+ }}
+ >
+ <IssueDetailRoute routeId="ZZZ-134" />
+ </NavigationProvider>
+ </QueryClientProvider>,
+ );
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ expect(getIssue).toHaveBeenCalledTimes(1);
+
+ // A failed resolve must never rewrite the URL.
+ expect(replace).not.toHaveBeenCalled();
+ qc.clear();
+ });
+});
diff --git a/packages/views/issues/components/issue-detail-route.tsx b/packages/views/issues/components/issue-detail-route.tsx
new file mode 100644
index 0000000000..843f09036e
--- /dev/null
+++ b/packages/views/issues/components/issue-detail-route.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+import { useCanonicalIssue } from "@multica/core/issues/canonical-id";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { useNavigation } from "../../navigation";
+import { IssueDetail, IssueDetailSkeleton, IssueNotFound } from "./issue-detail";
+
+interface IssueDetailRouteProps {
+ /**
+ * Raw `/{ws}/issues/{segment}` parameter. Either a UUID (older links, and
+ * anything the app itself linked before the issue row was in hand) or a
+ * human-readable identifier such as `MUL-123`.
+ */
+ routeId: string;
+ onDelete?: () => void;
+}
+
+/**
+ * Rewrite `/{ws}/issues/{uuid}` to `/{ws}/issues/{identifier}` once the issue
+ * is known, so the address bar and any copied URL read as `MUL-123`.
+ *
+ * A replace, not a push: the UUID URL is the same page, and a history entry
+ * for it would make Back bounce the user between two spellings of one issue.
+ */
+export function useCanonicalIssueUrl(routeId: string, identifier: string | undefined) {
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const canonicalHref = identifier ? paths.issueDetail(identifier) : null;
+ // `useWorkspacePaths()` and the navigation adapter are both rebuilt on
+ // render, so this ref — not the dependency array — is what guarantees the
+ // replace runs once per target instead of on every commit.
+ const replacedRef = useRef<string | null>(null);
+
+ useEffect(() => {
+ if (!canonicalHref || routeId === identifier) return;
+ if (replacedRef.current === canonicalHref) return;
+ replacedRef.current = canonicalHref;
+ navigation.replace(canonicalHref);
+ }, [canonicalHref, identifier, routeId, navigation]);
+}
+
+/**
+ * Route-level wrapper around `IssueDetail` for `/{ws}/issues/{id}`.
+ *
+ * Two jobs the panel-embedded `IssueDetail` must not do:
+ * - resolve an identifier segment to the issue's UUID before rendering, so
+ * every cache key below stays UUID-keyed and realtime updates land (see
+ * `useCanonicalIssue`);
+ * - rewrite the address bar to the canonical identifier URL. That belongs to
+ * the route and only the route — the inbox renders `IssueDetail` in a side
+ * panel, where replacing the URL would navigate the user out of the inbox.
+ */
+export function IssueDetailRoute({ routeId, onDelete }: IssueDetailRouteProps) {
+ const wsId = useWorkspaceId();
+ const { canonicalId, issue, isResolving, notFound } = useCanonicalIssue(wsId, routeId);
+
+ useCanonicalIssueUrl(routeId, issue?.identifier);
+
+ if (isResolving) return <IssueDetailSkeleton />;
+
+ // Render not-found here rather than handing the unresolved segment down.
+ // `IssueDetail` would mount a second observer on the query that just failed,
+ // refetch it, and restart this component's resolve/remount cycle — an
+ // unbounded request loop that never settles. See `CanonicalIssue.notFound`.
+ if (notFound || !canonicalId) return <IssueNotFound showBackLink={!onDelete} />;
+
+ return <IssueDetail issueId={canonicalId} onDelete={onDelete} />;
+}
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 5f186814b8..e42ebabdfb 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -896,6 +896,95 @@ interface IssueDetailProps {
highlightCommentId?: string;
}
+// ---------------------------------------------------------------------------
+// Not found
+// ---------------------------------------------------------------------------
+
+/**
+ * Exported so `IssueDetailRoute` can render it for an identifier that names no
+ * issue. The route must NOT fall through to `IssueDetail` in that case: doing
+ * so mounts a second observer on the already-failed query, which refetches it
+ * and restarts the resolve/remount cycle indefinitely.
+ */
+export function IssueNotFound({ showBackLink = true }: { showBackLink?: boolean }) {
+ const { t } = useT("issues");
+ const backOrReplace = useBackOrReplace();
+ const paths = useWorkspacePaths();
+
+ return (
+ <div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-body text-muted-foreground">
+ <p>{t(($) => $.detail.not_found)}</p>
+ {showBackLink && (
+ <Button variant="outline" size="sm" onClick={() => backOrReplace(paths.issues())}>
+ <ChevronLeft className="mr-1 h-3.5 w-3.5" />
+ {t(($) => $.detail.back)}
+ </Button>
+ )}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Loading skeleton
+// ---------------------------------------------------------------------------
+
+/**
+ * Exported so `IssueDetailRoute` can show the identical frame while it resolves
+ * an identifier URL to its issue — the two waits are indistinguishable to the
+ * user, and rendering the same skeleton keeps them that way.
+ */
+export function IssueDetailSkeleton() {
+ return (
+ <div className="flex flex-1 min-h-0 flex-col">
+ <div className="flex h-12 shrink-0 items-center gap-2 border-b px-4">
+ <Skeleton className="h-4 w-16" />
+ <Skeleton className="h-4 w-4" />
+ <Skeleton className="h-4 w-24" />
+ </div>
+ <div className="flex flex-1 min-h-0">
+ {/* Same scrollbar-gutter as the loaded scroller below, so the skeleton
+ column doesn't shift sideways when real content mounts. */}
+ <div className="flex-1 overflow-y-auto [scrollbar-gutter:stable_both-edges]">
+ <div className="mx-auto w-full max-w-4xl px-8 py-8 space-y-6">
+ <Skeleton className="h-8 w-3/4" />
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-5/6" />
+ <Skeleton className="h-4 w-2/3" />
+ </div>
+ <Skeleton className="h-px w-full" />
+ <div className="space-y-3">
+ <Skeleton className="h-4 w-20" />
+ <div className="flex items-start gap-3">
+ <Skeleton className="h-8 w-8 shrink-0 rounded-full" />
+ <div className="flex-1 space-y-2">
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="h-16 w-full rounded-lg" />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div className="hidden md:block w-80 border-l p-4 space-y-5">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <div key={i} className="flex items-center gap-2">
+ <Skeleton className="h-3 w-16 shrink-0" />
+ <Skeleton className="h-5 w-24" />
+ </div>
+ ))}
+ <Skeleton className="h-px w-full" />
+ {Array.from({ length: 3 }).map((_, i) => (
+ <div key={i} className="flex items-center gap-2">
+ <Skeleton className="h-3 w-16 shrink-0" />
+ <Skeleton className="h-4 w-28" />
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
// ---------------------------------------------------------------------------
// IssueDetail
// ---------------------------------------------------------------------------
@@ -904,7 +993,6 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const { t } = useT("issues");
const timeAgo = useTimeAgo();
const id = issueId;
- const backOrReplace = useBackOrReplace();
const user = useAuthStore((s) => s.user);
const paths = useWorkspacePaths();
@@ -1698,69 +1786,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
});
if (loading) {
- return (
- <div className="flex flex-1 min-h-0 flex-col">
- <div className="flex h-12 shrink-0 items-center gap-2 border-b px-4">
- <Skeleton className="h-4 w-16" />
- <Skeleton className="h-4 w-4" />
- <Skeleton className="h-4 w-24" />
- </div>
- <div className="flex flex-1 min-h-0">
- {/* Same scrollbar-gutter as the loaded scroller below, so the skeleton
- column doesn't shift sideways when real content mounts. */}
- <div className="flex-1 overflow-y-auto [scrollbar-gutter:stable_both-edges]">
- <div className="mx-auto w-full max-w-4xl px-8 py-8 space-y-6">
- <Skeleton className="h-8 w-3/4" />
- <div className="space-y-2">
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-5/6" />
- <Skeleton className="h-4 w-2/3" />
- </div>
- <Skeleton className="h-px w-full" />
- <div className="space-y-3">
- <Skeleton className="h-4 w-20" />
- <div className="flex items-start gap-3">
- <Skeleton className="h-8 w-8 shrink-0 rounded-full" />
- <div className="flex-1 space-y-2">
- <Skeleton className="h-4 w-32" />
- <Skeleton className="h-16 w-full rounded-lg" />
- </div>
- </div>
- </div>
- </div>
- </div>
- <div className="hidden md:block w-80 border-l p-4 space-y-5">
- {Array.from({ length: 4 }).map((_, i) => (
- <div key={i} className="flex items-center gap-2">
- <Skeleton className="h-3 w-16 shrink-0" />
- <Skeleton className="h-5 w-24" />
- </div>
- ))}
- <Skeleton className="h-px w-full" />
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="flex items-center gap-2">
- <Skeleton className="h-3 w-16 shrink-0" />
- <Skeleton className="h-4 w-28" />
- </div>
- ))}
- </div>
- </div>
- </div>
- );
+ return <IssueDetailSkeleton />;
}
if (!issue) {
- return (
- <div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-body text-muted-foreground">
- <p>{t(($) => $.detail.not_found)}</p>
- {!onDelete && (
- <Button variant="outline" size="sm" onClick={() => backOrReplace(paths.issues())}>
- <ChevronLeft className="mr-1 h-3.5 w-3.5" />
- {t(($) => $.detail.back)}
- </Button>
- )}
- </div>
- );
+ return <IssueNotFound showBackLink={!onDelete} />;
}
const sidebarContent = (
diff --git a/packages/views/layout/tab-presentation.tsx b/packages/views/layout/tab-presentation.tsx
index bd2beb94fd..300d987b89 100644
--- a/packages/views/layout/tab-presentation.tsx
+++ b/packages/views/layout/tab-presentation.tsx
@@ -98,10 +98,20 @@ function useTabEntityData(subject: TabSubject, wsId: string): TabEntityData {
subject.kind === "issue"
? subject.id
: (inboxItem?.issue_id ?? "");
- const issue = useQuery({
+ // An issue tab's URL segment may be a human-readable identifier (`MUL-123`).
+ // The route seeds that entry when it resolves, but only the UUID-keyed entry
+ // receives realtime patches — so hop through it, or a tab opened by
+ // identifier would freeze on the title and status it had when first opened.
+ // Both reads stay cache-only, and a UUID segment resolves to itself.
+ const rawIssue = useQuery({
...issueDetailOptions(wsId, issueId || NONE),
enabled: false,
}).data;
+ const issue =
+ useQuery({
+ ...issueDetailOptions(wsId, rawIssue?.id || NONE),
+ enabled: false,
+ }).data ?? rawIssue;
const project = useQuery({
...projectDetailOptions(wsId, subject.kind === "project" ? subject.id : NONE),
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index cde075acb7..0d87ea7e35 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -7,9 +7,11 @@ import (
"encoding/json"
"errors"
"log/slog"
+ "math"
"net/http"
"net/netip"
"strconv"
+ "strings"
"time"
"github.com/go-chi/chi/v5"
@@ -813,6 +815,12 @@ func (h *Handler) loadIssueForUser(w http.ResponseWriter, r *http.Request, issue
}
// resolveIssueByIdentifier tries to look up an issue by "PREFIX-NUMBER" format.
+//
+// The prefix must match the workspace's own issue prefix, the same rule
+// `lookupIssueByIdentifier` applies to VCS webhooks. Without it every prefix
+// resolved to the same issue number, so `FOO-134` and `TRS-134` were
+// interchangeable — which makes the identifier URL `/{ws}/issues/{key}`
+// unusable as a canonical link.
func (h *Handler) resolveIssueByIdentifier(ctx context.Context, id, workspaceID string) (db.Issue, bool) {
parts := splitIdentifier(id)
if parts == nil {
@@ -825,6 +833,11 @@ func (h *Handler) resolveIssueByIdentifier(ctx context.Context, id, workspaceID
if err != nil {
return db.Issue{}, false
}
+ // Case-insensitive: a hand-typed `trs-134` should open `TRS-134`.
+ prefix := h.getIssuePrefix(ctx, wsUUID)
+ if prefix == "" || !strings.EqualFold(parts.prefix, prefix) {
+ return db.Issue{}, false
+ }
issue, err := h.Queries.GetIssueByNumber(ctx, db.GetIssueByNumberParams{
WorkspaceID: wsUUID,
Number: parts.number,
@@ -858,6 +871,12 @@ func splitIdentifier(id string) *identifierParts {
return nil
}
num = num*10 + int(c-'0')
+ // Guard the int32 conversion below: a UUID whose last group happens to
+ // be all digits ("…-421234567890") reaches here and would otherwise be
+ // truncated into a plausible-looking issue number.
+ if num > math.MaxInt32 {
+ return nil
+ }
}
if num <= 0 {
return nil
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index db0b21e4cd..72b275c5e1 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -506,6 +506,60 @@ func TestDeleteIssueByIdentifier(t *testing.T) {
}
}
+// TestGetIssueByIdentifierEnforcesPrefix covers the contract behind the
+// human-readable issue URL `/{ws}/issues/{key}`: the prefix is part of the key,
+// not decoration. Identifier resolution used to compare the number only, so
+// every prefix with the right number opened the same issue — which means no
+// identifier URL could be treated as canonical, and a mistyped or stale prefix
+// silently opened someone else's link target.
+func TestGetIssueByIdentifierEnforcesPrefix(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "Issue addressed by identifier",
+ "status": "todo",
+ "priority": "medium",
+ })
+ testHandler.CreateIssue(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var created IssueResponse
+ json.NewDecoder(w.Body).Decode(&created)
+
+ idx := strings.LastIndex(created.Identifier, "-")
+ if idx <= 0 {
+ t.Fatalf("CreateIssue: unexpected identifier %q", created.Identifier)
+ }
+ prefix, number := created.Identifier[:idx], created.Identifier[idx+1:]
+
+ // The workspace's own prefix resolves, in either case — a hand-typed
+ // lowercase key from a chat message must open the same issue.
+ for _, id := range []string{created.Identifier, strings.ToLower(created.Identifier)} {
+ w = httptest.NewRecorder()
+ req = newRequest("GET", "/api/issues/"+id, nil)
+ req = withURLParam(req, "id", id)
+ testHandler.GetIssue(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetIssue(%q): expected 200, got %d: %s", id, w.Code, w.Body.String())
+ }
+ var got IssueResponse
+ json.NewDecoder(w.Body).Decode(&got)
+ if got.ID != created.ID {
+ t.Fatalf("GetIssue(%q): resolved to %s, want %s", id, got.ID, created.ID)
+ }
+ }
+
+ // A foreign prefix carrying the right number must not resolve.
+ foreign := prefix + "X-" + number
+ w = httptest.NewRecorder()
+ req = newRequest("GET", "/api/issues/"+foreign, nil)
+ req = withURLParam(req, "id", foreign)
+ testHandler.GetIssue(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("GetIssue(%q): expected 404 for a foreign prefix, got %d: %s", foreign, w.Code, w.Body.String())
+ }
+}
+
// TestDeleteIssueRejectsInvalidUUID verifies that a path segment that is
// neither a valid UUID nor a valid identifier returns 404 (not 204) — the
// handler must never silently succeed on malformed input.