Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8658: fix(issues): show safe load errors and scoped retry (#10001)
沙雕的小鱼儿 boyfeiyu8105995e721b
diff --git a/packages/core/issues/canonical-id.test.tsx b/packages/core/issues/canonical-id.test.tsxindex 71c267152f..4c6669cbf9 100644--- a/packages/core/issues/canonical-id.test.tsx+++ b/packages/core/issues/canonical-id.test.tsx@@ -6,6 +6,7 @@ import { renderHook, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type { ReactNode } from "react";import { setApiInstance } from "../api";+import { ApiError } from "../api/client";import type { ApiClient } from "../api/client";import type { Issue } from "../types";import { createQueryClient } from "../query-client";@@ -141,7 +142,7 @@ describe("useCanonicalIssue", () => {});it("reports a nonexistent identifier as terminally not-found", async () => {- getIssue.mockRejectedValue(new Error("issue not found"));+ getIssue.mockRejectedValue(new ApiError("issue not found", 404, "Not Found"));const { result } = renderHook(() => useCanonicalIssue("ws-1", "ZZZ-134"), {wrapper: createWrapper(qc),@@ -168,7 +169,7 @@ describe("useCanonicalIssue", () => {// 1 can only mean a remount refetched.defaultOptions: { queries: { staleTime: Infinity, retry: false } },});- getIssue.mockRejectedValue(new Error("issue not found"));+ getIssue.mockRejectedValue(new ApiError("issue not found", 404, "Not Found"));const { result, rerender } = renderHook(() => useCanonicalIssue("ws-1", "ZZZ-134"), {wrapper: createWrapper(noRetry),diff --git a/packages/core/issues/canonical-id.ts b/packages/core/issues/canonical-id.tsindex d4eddcf404..51de347f67 100644--- a/packages/core/issues/canonical-id.ts+++ b/packages/core/issues/canonical-id.ts@@ -2,6 +2,7 @@ import { useEffect } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";import type { Issue } from "../types";import { issueDetailOptions, issueKeys } from "./queries";+import { useIssueReadState } from "./read-state";const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -20,7 +21,7 @@ export interface CanonicalIssue {issue: Issue | undefined;isResolving: boolean;/**- * Terminal: this identifier does not name an issue in this workspace.+ * Terminal: the primary read returned an opaque unavailable response.** 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@@ -30,6 +31,11 @@ export interface CanonicalIssue {* that never settles on "not found".*/notFound: boolean;+ loadFailed: boolean;+ /** A successful primary read completed during this mount. */+ hasLoaded: boolean;+ isRetrying: boolean;+ retry: () => Promise<void>;}/**@@ -97,16 +103,21 @@ export function useCanonicalIssue();}, [qc, wsId, loadedIdentifier, loadedIssue, routeId]);- // 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;+ // A failed identifier must settle here without mounting a second observer.+ // Once resolved, the UUID entry owns both the data and background failures.+ const readState = useIssueReadState(+ wsId,+ canonicalId ?? routeId,+ canonicalId ? detail : resolve,+ );return {canonicalId,+ hasLoaded:+ (resolve.isSuccess && resolve.isFetchedAfterMount) ||+ (detail.isSuccess && detail.isFetchedAfterMount),issue: detail.data,- isResolving: resolveEnabled && !failed && resolve.data === undefined,- notFound: failed,+ isResolving: resolveEnabled && !canonicalId && !readState.notFound && !readState.loadFailed,+ ...readState,};}diff --git a/packages/core/issues/read-state.ts b/packages/core/issues/read-state.tsnew file mode 100644index 0000000000..855f22d345--- /dev/null+++ b/packages/core/issues/read-state.ts@@ -0,0 +1,42 @@+import { useRef, useState } from "react";+import type { UseQueryResult } from "@tanstack/react-query";+import { ApiError } from "../api/client";+import type { Issue } from "../types";++/** Only authentication and opaque access/not-found refusals imply unavailable. */+function isUnavailable(error: unknown): boolean {+ return error instanceof ApiError && (error.status === 401 || error.status === 403 || error.status === 404);+}++/** Presentation and manual retry for an uncached primary issue read only. */+export function useIssueReadState(+ wsId: string,+ id: string,+ query: Pick<UseQueryResult<Issue>, "data" | "error" | "isError" | "isFetching" | "refetch">,+) {+ const scope = JSON.stringify([wsId, id]);+ const [attempt, setAttempt] = useState<{ scope: string } | null>(null);+ const pending = useRef<{ scope: string } | null>(null);+ const isRetrying = attempt?.scope === scope;+ const failed = query.data === undefined && query.isError;+ const notFound = failed && isUnavailable(query.error);+ const loadFailed = query.data === undefined && ((failed && !notFound) || isRetrying);++ const retry = async () => {+ if (!loadFailed || query.isFetching || pending.current?.scope === scope) return;+ const current = { scope };+ pending.current = current;+ setAttempt(current);+ try {+ // Reuse the existing observer; do not cancel or mount another failed read.+ await query.refetch({ cancelRefetch: false });+ } catch {+ // The query owns the error. Never expose a raw server response here.+ } finally {+ if (pending.current === current) pending.current = null;+ setAttempt((value) => value === current ? null : value);+ }+ };++ return { notFound, loadFailed, isRetrying, retry };+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 0c5f98397b..47be3c134d 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -41,6 +41,7 @@"./issues": "./issues/index.ts","./issues/use-issue-deletion": "./issues/use-issue-deletion.ts","./issues/batch": "./issues/batch.ts",+ "./issues/read-state": "./issues/read-state.ts","./issues/canonical-id": "./issues/canonical-id.ts","./issues/queries": "./issues/queries.ts","./issues/wakeups": "./issues/wakeups.ts",diff --git a/packages/views/issues/components/issue-detail-route.test.tsx b/packages/views/issues/components/issue-detail-route.test.tsxindex ef47514e07..f822cdf269 100644--- a/packages/views/issues/components/issue-detail-route.test.tsx+++ b/packages/views/issues/components/issue-detail-route.test.tsx@@ -3,6 +3,7 @@ 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 { ApiError } from "@multica/core/api/client";import type { ApiClient } from "@multica/core/api/client";import { NavigationProvider } from "../../navigation";import type { NavigationAdapter } from "../../navigation";@@ -127,7 +128,7 @@ describe("IssueDetailRoute with an identifier that names no issue", () => {expect(vi.isMockFunction(IssueDetail)).toBe(false);replace.mockClear();push.mockClear();- const getIssue = vi.fn().mockRejectedValue(new Error("issue not found"));+ const getIssue = vi.fn().mockRejectedValue(new ApiError("issue not found", 404, "Not Found"));setApiInstance({ getIssue } as unknown as ApiClient);const qc = new QueryClient({defaultOptions: { queries: { staleTime: Infinity, retry: false } },diff --git a/packages/views/issues/components/issue-detail-route.tsx b/packages/views/issues/components/issue-detail-route.tsxindex 2eac0627bf..b2787bc6e2 100644--- a/packages/views/issues/components/issue-detail-route.tsx+++ b/packages/views/issues/components/issue-detail-route.tsx@@ -5,7 +5,7 @@ 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";+import { IssueDetail, IssueDetailSkeleton, IssueNotFound, IssueLoadError } from "./issue-detail";import { IssuePeekHost } from "./issue-peek";interface IssueDetailRouteProps {@@ -70,12 +70,18 @@ function useCommentHighlightHash(): { hash: string; commentId?: string } {*/export function IssueDetailRoute({ routeId, onDelete }: IssueDetailRouteProps) {const wsId = useWorkspaceId();- const { canonicalId, issue, isResolving, notFound } = useCanonicalIssue(wsId, routeId);+ const {+ canonicalId, issue, isResolving, notFound, loadFailed, isRetrying, retry, hasLoaded,+ } = useCanonicalIssue(wsId, routeId);const highlight = useCommentHighlightHash();useCanonicalIssueUrl(routeId, issue?.identifier, highlight.hash);- if (isResolving) return <IssueDetailSkeleton />;+ if (loadFailed) {+ return <IssueLoadError showBackLink={!onDelete} onRetry={retry} isRetrying={isRetrying} />;+ }++ if (isResolving || (!issue && !notFound)) 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,@@ -90,6 +96,7 @@ export function IssueDetailRoute({ routeId, onDelete }: IssueDetailRouteProps) {<IssuePeekHost key={canonicalId}><IssueDetailissueId={canonicalId}+ skipInitialRefetch={hasLoaded}onDelete={onDelete}highlightCommentId={highlight.commentId}/>diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex 3355619689..e31cb3b8a1 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -6,6 +6,7 @@ import type { AgentTask, Attachment, Issue, IssueStatusEntry, Label, TimelineEntimport { issueKeys } from "@multica/core/issues/queries";import { issueStatusKeys } from "@multica/core/issue-statuses";import { I18nProvider } from "@multica/core/i18n/react";+import { ApiError } from "@multica/core/api/client";import { toast } from "sonner";import { useResolvedExpandStore } from "@multica/core/issues/stores/resolved-expand-store";import { useCommentCollapseStore } from "@multica/core/issues/stores";@@ -1228,7 +1229,7 @@ describe("IssueDetail (shared)", () => {});it("keeps the peek's host controls when the issue cannot be loaded", async () => {- mockApiObj.getIssue.mockRejectedValue(new Error("Not found"));+ mockApiObj.getIssue.mockRejectedValue(new ApiError("Not found", 404, "Not Found"));renderPeek("nonexistent-id");await waitFor(() => {expect(@@ -1822,8 +1823,31 @@ describe("IssueDetail (shared)", () => {).toBeTruthy();});+ it("keeps an unsaved comment mounted when the primary background refresh fails", async () => {+ const queryClient = createTestQueryClient();+ render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <QueryClientProvider client={queryClient}>+ <IssueDetail issueId="issue-1" />+ </QueryClientProvider>+ </I18nProvider>,+ );+ await screen.findByText("Implement authentication");+ fireEvent.click(screen.getByTestId("comment-composer-shell"));+ const editor = await screen.findByPlaceholderText("Leave a comment...");+ fireEvent.change(editor, { target: { value: "Unsaved synthetic comment" } });+ mockApiObj.getIssue.mockRejectedValue(new ApiError("unavailable", 503, "Unavailable"));+ await act(async () => {+ await queryClient.refetchQueries({ queryKey: issueKeys.detail("ws-1", "issue-1"), exact: true });+ });+ expect(queryClient.getQueryState(issueKeys.detail("ws-1", "issue-1"))?.status).toBe("error");+ expect(editor).toBeInTheDocument();+ expect(editor).toHaveValue("Unsaved synthetic comment");+ expect(screen.queryByText("Could not load issue.")).not.toBeInTheDocument();+ });+it("shows 'not found' message when issue does not exist", async () => {- mockApiObj.getIssue.mockRejectedValue(new Error("Not found"));+ mockApiObj.getIssue.mockRejectedValue(new ApiError("Not found", 404, "Not Found"));renderIssueDetail("nonexistent-id");@@ -1835,7 +1859,7 @@ describe("IssueDetail (shared)", () => {});it("shows 'Back' button when issue is not found and no onDelete prop", async () => {- mockApiObj.getIssue.mockRejectedValue(new Error("Not found"));+ mockApiObj.getIssue.mockRejectedValue(new ApiError("Not found", 404, "Not Found"));renderIssueDetail("nonexistent-id");diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex c5d7d32dca..9adbf6e64e 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -16,6 +16,7 @@ import { useDefaultLayout, usePanelRef } from "react-resizable-panels";import { AppLink, useBackOrReplace } from "../../navigation";import { IssueDuplicateBanner, IssueDuplicatesSection, isDuplicateIssue } from "./issue-duplicates";import {+ AlertTriangle,Archive,Calendar,CalendarClock,@@ -25,6 +26,7 @@ import {ChevronRight,CircleCheck,FileQuestion,+ Loader2,Milestone,MoreHorizontal,PanelRight,@@ -130,6 +132,7 @@ import {import { collectDeliverableFiles } from "@multica/core/attachments/deliverables";import { AttachmentVersionsProvider } from "./deliverables/attachment-versions";import { useQuery } from "@tanstack/react-query";+import { useIssueReadState } from "@multica/core/issues/read-state";import { useAuthStore } from "@multica/core/auth";import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";@@ -1195,6 +1198,8 @@ interface IssueDetailProps {* the notification it selected itself, and keeps one marked unread there.*/readsInbox?: boolean;+ /** The route already completed the authoritative detail read this mount. */+ skipInitialRefetch?: boolean;}// Not found@@ -1250,6 +1255,54 @@ export function IssueNotFound({);}+/** Safe primary-read failure; host navigation remains available during retry. */+export function IssueLoadError({+ showBackLink = true,+ leading,+ trailing,+ onRetry,+ isRetrying,+}: {+ showBackLink?: boolean;+ leading?: ReactNode;+ trailing?: ReactNode;+ onRetry: () => Promise<void>;+ isRetrying: boolean;+}) {+ const { t } = useT("issues");+ const backOrReplace = useBackOrReplace();+ const paths = useWorkspacePaths();++ return (+ <div className="flex flex-1 min-h-0 flex-col">+ {(leading || trailing) && (+ <div className={cn("flex h-12 shrink-0 items-center gap-2 border-b", PAGE_GUTTER)}>+ {leading}+ {trailing && <div className="ml-auto flex shrink-0 items-center gap-1">{trailing}</div>}+ </div>+ )}+ <CollectionPageState+ icon={AlertTriangle}+ title={t(($) => $.detail.load_failed)}+ actions={+ <>+ <Button size="sm" disabled={isRetrying} aria-busy={isRetrying} onClick={() => { void onRetry(); }}>+ {isRetrying && <Loader2 aria-hidden="true" className="animate-spin" />}+ {t(($) => $.detail.load_retry)}+ </Button>+ {showBackLink && (+ <Button variant="outline" size="sm" onClick={() => backOrReplace(paths.issues())}>+ <ChevronLeft aria-hidden="true" />+ {t(($) => $.detail.back)}+ </Button>+ )}+ </>+ }+ />+ </div>+ );+}+// Loading skeleton/**@@ -1327,7 +1380,7 @@ export function IssueDetailSkeleton({// IssueDetail-export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, highlightRequestToken, leadingAction, variant = "page", trailingActions, readsInbox = true }: IssueDetailProps) {+export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, highlightRequestToken, leadingAction, variant = "page", trailingActions, readsInbox = true, skipInitialRefetch = false }: IssueDetailProps) {const isPeek = variant === "peek";const { t } = useT("issues");const { t: tCommon } = useT("common");@@ -1554,19 +1607,21 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// Issue data from TQ — uses detail query, seeded from list cache if available.// Only seed when description is present; the list API omits it, so a partial// list row must not masquerade as a hydrated issue detail.- const { data: issue = null, isLoading: issueLoading, refetch: refetchIssue } = useQuery({+ const issueQuery = useQuery({...issueDetailOptions(wsId, id),// List rows and issue-created realtime payloads intentionally omit the// detail-only source-context snapshot. They can still seed this query via- // initialData, so always reconcile with the authoritative detail endpoint- // when the detail view mounts. Without this, the global Infinity staleTime+ // initialData, so reconcile with the authoritative detail endpoint when+ // mounting unless the route already completed that read. Without this, the global Infinity staleTime// hides source context until a full page refresh.- refetchOnMount: "always",+ refetchOnMount: skipInitialRefetch ? false : "always",initialData: () => {const cached = allIssues.find((i) => i.id === id);return cached?.description != null ? cached : undefined;},});+ const { data: issue = null, isLoading: issueLoading, refetch: refetchIssue } = issueQuery;+ const issueReadState = useIssueReadState(wsId, id, issueQuery);useMarkIssueReadWhileViewing(wsId, issue?.id ?? "");useMarkIssueInboxReadWhileViewing(wsId, issue?.id ?? "", readsInbox);const descriptionSourceId = `description:${id}`;@@ -2749,6 +2804,18 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr[resolvedIssueId, resolvedIssueIdentifier],);+ if (issueReadState.loadFailed) {+ return (+ <IssueLoadError+ showBackLink={!onDelete}+ leading={leadingAction}+ trailing={trailingActions}+ onRetry={issueReadState.retry}+ isRetrying={issueReadState.isRetrying}+ />+ );+ }+if (loading) {// The host's trailing controls hold the peek's only close button, so the// waiting and missing states carry them too.diff --git a/packages/views/issues/components/issue-load-failure.test.tsx b/packages/views/issues/components/issue-load-failure.test.tsxnew file mode 100644index 0000000000..76c13b9dd2--- /dev/null+++ b/packages/views/issues/components/issue-load-failure.test.tsx@@ -0,0 +1,243 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, cleanup, fireEvent, render, renderHook, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { createAuthStore, registerAuthStore } from "@multica/core/auth";+import { createChatStore, registerChatStore } from "@multica/core/chat";+import { WSProvider } from "@multica/core/realtime";+import { defaultStorage } from "@multica/core/platform";+import { TooltipProvider } from "@multica/ui/components/ui/tooltip";+import { ApiClient, setApiInstance } from "@multica/core/api";+import { useCanonicalIssue } from "@multica/core/issues/canonical-id";+import { issueKeys } from "@multica/core/issues/queries";+import { I18nProvider } from "@multica/core/i18n/react";+import { NavigationProvider } from "../../navigation";+import enIssues from "../../locales/en/issues.json";+import enCommon from "../../locales/en/common.json";+import { IssueDetail } from "./issue-detail";+import { IssueDetailRoute } from "./issue-detail-route";++const scope = vi.hoisted(() => ({ wsId: "ws-synthetic" }));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => scope.wsId }));+vi.mock("@multica/core/paths", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/paths")>("@multica/core/paths");+ return { ...actual, useCurrentWorkspace: () => ({ id: scope.wsId, slug: "synthetic", name: "Synthetic" }), useWorkspacePaths: () => actual.paths.workspace("synthetic") };+});++const uuid = "11111111-1111-4111-8111-111111111111";+const issue = {+ id: uuid, workspace_id: "ws-synthetic", number: 1, identifier: "SYN-1",+ title: "Synthetic issue", description: "Synthetic description", status: "todo", priority: "none",+ assignee_type: null, assignee_id: null, creator_type: "member", creator_id: "synthetic-user",+ parent_issue_id: null, project_id: null, position: 0, stage: null, start_date: null, due_date: null,+ metadata: {}, properties: {}, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z",+};+const response = (status: number, body: unknown = { error: "SYNTHETIC_PRIVATE_ERROR" }) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });+let auth: ReturnType<typeof createAuthStore>;+let qc: QueryClient;+let primary: ReturnType<typeof vi.fn<(url: string) => Promise<Response>>>;+const replace = vi.fn();+const back = vi.fn();+function surface(routeId: string, host: "route" | "inbox" | "peek" = "route") {+ return <I18nProvider resources={{ en: { issues: enIssues, common: enCommon } }} locale="en">+ <QueryClientProvider client={qc}>+ <WSProvider wsUrl="ws://synthetic.invalid" authStore={auth} storage={defaultStorage}><TooltipProvider><NavigationProvider value={{ push: vi.fn(), replace, back, pathname: `/synthetic/issues/${routeId}`, searchParams: new URLSearchParams(), hash: "#comment-synthetic", getShareableUrl: (p) => p }}>+ {host === "route" ? <IssueDetailRoute routeId={routeId} /> : <IssueDetail issueId={routeId} variant={host === "peek" ? "peek" : "page"} leadingAction={<button onClick={back}>Inbox back</button>} trailingActions={<button onClick={back}>Close peek</button>} />}+ </NavigationProvider></TooltipProvider></WSProvider>+ </QueryClientProvider>+ </I18nProvider>;+}+beforeEach(() => {+ scope.wsId = "ws-synthetic";+ qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });+ primary = vi.fn<(url: string) => Promise<Response>>().mockImplementation(() => Promise.resolve(response(503)));+ replace.mockClear(); back.mockClear();+ // Only the HTTP boundary is synthetic. Queries, schemas, resolver and detail components are real.+ vi.stubGlobal("fetch", vi.fn((url: string) => {+ const pathname = new URL(url).pathname;+ if (["SYN-1", uuid, "OTHER-2"].some((id) => pathname === `/api/issues/${id}`)) {+ return primary(url);+ }+ const body = /\/(members|agents|squads|assignee-frequency)$/.test(pathname)+ ? []+ : { issues: [], total: 0, members: [], agents: [], comments: [], tasks: [], entries: [], has_more: false };+ return Promise.resolve(response(200, body));+ }));+ const api = new ApiClient("https://synthetic.invalid");+ setApiInstance(api);+ auth = createAuthStore({ api, storage: defaultStorage });+ registerAuthStore(auth);+ registerChatStore(createChatStore({ storage: defaultStorage }));+});+afterEach(() => { cleanup(); qc.clear(); vi.unstubAllGlobals(); });++describe("primary issue read failures through the production API client", () => {+ it.each(["SYN-1", uuid])("shows a safe load failure for 503 at %s without looping", async (id) => {+ const view = render(surface(id));+ await screen.findByText("Could not load issue.");+ expect(screen.queryByText(enIssues.detail.not_found_title)).not.toBeInTheDocument();+ expect(document.body).not.toHaveTextContent("SYNTHETIC_PRIVATE_ERROR");+ view.rerender(surface(id));+ await act(async () => { await new Promise((r) => setTimeout(r, 80)); });+ expect(primary).toHaveBeenCalledTimes(1);+ expect(replace).not.toHaveBeenCalled();+ });+ it.each([+ [408, "route"], [429, "route"],+ [408, "inbox"], [429, "inbox"],+ [408, "peek"], [429, "peek"],+ ] as const)("HTTP %s in %s allows a scoped manual retry, another refusal and recovery", async (status, host) => {+ primary.mockImplementation(() => Promise.resolve(response(status)));+ const unrelatedKey = issueKeys.detail(scope.wsId, "UNRELATED-2");+ qc.setQueryData(unrelatedKey, issue);+ render(surface(host === "route" ? "SYN-1" : uuid, host));+ const retry = await screen.findByRole("button", { name: "Retry" });+ expect(screen.getByText("Could not load issue.")).toBeInTheDocument();+ expect(screen.queryByText(enIssues.detail.not_found_title)).not.toBeInTheDocument();+ expect(document.body).not.toHaveTextContent("SYNTHETIC_PRIVATE_ERROR");+ const initialReads = primary.mock.calls.length;+ // Shared UUID hosts also mount the existing independent reactions read.+ expect(initialReads).toBe(host === "route" ? 1 : 2);+ let settle!: (value: Response) => void;+ primary.mockImplementationOnce(() => new Promise<Response>((resolve) => { settle = resolve; }));+ fireEvent.click(retry);+ fireEvent.click(retry);+ expect(retry).toBeDisabled();+ expect(retry).toHaveAttribute("aria-busy", "true");+ expect(primary).toHaveBeenCalledTimes(initialReads + 1);+ await act(async () => { settle(response(status)); });+ await waitFor(() => expect(retry).toBeEnabled());+ expect(primary).toHaveBeenCalledTimes(initialReads + 1);+ expect(document.body).not.toHaveTextContent("SYNTHETIC_PRIVATE_ERROR");+ primary.mockImplementation(() => Promise.resolve(response(200, issue)));+ fireEvent.click(retry);+ await screen.findAllByText("Synthetic issue");+ expect(screen.queryByText("Could not load issue.")).not.toBeInTheDocument();+ // Route recovery mounts reactions; shared UUID hosts already read reactions at mount.+ expect(primary).toHaveBeenCalledTimes(initialReads + (host === "route" ? 3 : 2));+ expect(qc.getQueryData(unrelatedKey)).toEqual(issue);+ });+ it.each([400, 422])("does not infer nonexistence from other HTTP %s or error text", async (status) => {+ primary.mockImplementation(() => Promise.resolve(response(status, { error: "Issue not found" })));+ render(surface("SYN-1"));+ await screen.findByText("Could not load issue.");+ expect(screen.getByRole("button", { name: "Retry" })).toBeEnabled();+ expect(screen.queryByText(enIssues.detail.not_found_title)).not.toBeInTheDocument();+ expect(document.body).not.toHaveTextContent("Issue not found");+ expect(primary).toHaveBeenCalledTimes(1);+ });+ it("shows a network failure without displaying the exception", async () => {+ primary.mockRejectedValue(new TypeError("SYNTHETIC_PRIVATE_ERROR"));+ render(surface("SYN-1"));+ await screen.findByText("Could not load issue.");+ expect(document.body).not.toHaveTextContent("SYNTHETIC_PRIVATE_ERROR");+ });+ it.each([["SYN-1", 403], ["SYN-1", 404], [uuid, 403], [uuid, 404]] as const)("retains the opaque unavailable view for %s HTTP %s", async (id, status) => {+ primary.mockImplementation(() => Promise.resolve(response(status)));+ render(surface(id));+ await screen.findByText(enIssues.detail.not_found_title);+ expect(screen.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument();+ expect(document.body).not.toHaveTextContent("SYNTHETIC_PRIVATE_ERROR");+ expect(primary).toHaveBeenCalledTimes(1);+ });+ it.each(["inbox", "peek"] as const)("retains %s host controls on failed reads", async (host) => {+ render(surface(uuid, host));+ await screen.findByText("Could not load issue.");+ fireEvent.click(screen.getByRole("button", { name: host === "inbox" ? "Inbox back" : "Close peek" }));+ expect(back).toHaveBeenCalledTimes(1);+ });+ it.each(["route", "inbox", "peek"] as const)("%s retries only the current failed read, prevents reentry and settles after another failure", async (host) => {+ render(surface(host === "route" ? "SYN-1" : uuid, host));+ const retry = await screen.findByRole("button", { name: "Retry" });+ const previousReads = primary.mock.calls.length;+ let settle!: (value: Response) => void;+ primary.mockImplementation(() => new Promise<Response>((resolve) => { settle = resolve; }));+ fireEvent.click(retry);+ fireEvent.click(retry);+ expect(retry).toBeDisabled();+ expect(retry).toHaveAttribute("aria-busy", "true");+ expect(primary).toHaveBeenCalledTimes(previousReads + 1);+ await act(async () => { settle(response(503)); });+ await waitFor(() => expect(retry).not.toBeDisabled());+ expect(primary).toHaveBeenCalledTimes(previousReads + 1);+ });+ it("treats an unreadable successful response as a generic load failure", async () => {+ primary.mockImplementation(() => Promise.resolve(response(200, null)));+ render(surface("SYN-1"));+ await screen.findByText("Could not load issue.");+ expect(screen.getByRole("button", { name: "Retry" })).toBeEnabled();+ });+ it.each(["SYN-1", uuid])("opens a valid %s route without redundant primary refresh", async (id) => {+ primary.mockImplementation(() => Promise.resolve(response(200, issue)));+ render(surface(id));+ await screen.findAllByText("Synthetic issue");+ await act(async () => { await new Promise((r) => setTimeout(r, 80)); });+ // One primary read plus the existing independent reactions read.+ expect(primary).toHaveBeenCalledTimes(2);+ if (id === uuid) expect(replace).toHaveBeenCalledWith("/synthetic/issues/SYN-1#comment-synthetic");+ });+ it.each(["route", "inbox", "peek"] as const)("%s recovers the real detail after a manual retry returns 200", async (host) => {+ render(surface(host === "route" ? "SYN-1" : uuid, host));+ const retry = await screen.findByRole("button", { name: "Retry" });+ primary.mockImplementation(() => Promise.resolve(response(200, issue)));+ fireEvent.click(retry);+ await screen.findAllByText("Synthetic issue");+ expect(screen.queryByText("Could not load issue.")).not.toBeInTheDocument();+ // Recovery plus the existing independent reactions read.+ expect(primary).toHaveBeenCalledTimes(3);+ });+ it.each(["route", "inbox", "peek"] as const)("%s keeps hydrated content on a background refresh failure", async (host) => {+ qc.setQueryData(issueKeys.detail(scope.wsId, uuid), issue);+ render(surface(uuid, host));+ const title = (await screen.findAllByText("Synthetic issue"))[0];+ await waitFor(() => expect(qc.getQueryState(issueKeys.detail(scope.wsId, uuid))?.status).toBe("error"));+ expect(title).toBeInTheDocument();+ expect(screen.queryByText("Could not load issue.")).not.toBeInTheDocument();+ expect(screen.queryByText(enIssues.detail.not_found_title)).not.toBeInTheDocument();+ });+ it.each(["workspace", "route", "both"])("ignores a retry finishing after the %s changes", async (changed) => {+ const view = render(surface("SYN-1"));+ const retry = await screen.findByRole("button", { name: "Retry" });+ let settle!: (value: Response) => void;+ primary.mockImplementationOnce(() => new Promise<Response>((resolve) => { settle = resolve; }));+ fireEvent.click(retry);+ if (changed !== "route") scope.wsId = "ws-other";+ view.rerender(surface(changed === "workspace" ? "SYN-1" : "OTHER-2"));+ await screen.findByText("Could not load issue.");+ await act(async () => { settle(response(200, issue)); });+ expect(screen.queryByText("Synthetic issue")).not.toBeInTheDocument();+ expect(replace).not.toHaveBeenCalled();+ expect(screen.getByRole("button", { name: "Retry" })).toBeEnabled();+ expect(qc.getQueryData(issueKeys.detail("ws-other", uuid))).toBeUndefined();+ });+ it("allows an in-flight retry to settle after unmount", async () => {+ const view = render(surface("SYN-1"));+ const retry = await screen.findByRole("button", { name: "Retry" });+ let settle!: (value: Response) => void;+ primary.mockImplementationOnce(() => new Promise<Response>((resolve) => { settle = resolve; }));+ fireEvent.click(retry);+ view.unmount();+ await act(async () => { settle(response(503)); });+ expect(replace).not.toHaveBeenCalled();+ });++ it.each(["SYN-1", uuid])("resolves %s through the real API with one canonical lookup", async (id) => {+ primary.mockImplementation(() => Promise.resolve(response(200, issue)));+ const { result, rerender } = renderHook(() => useCanonicalIssue(scope.wsId, id), {+ wrapper: ({ children }) => <QueryClientProvider client={qc}>{children}</QueryClientProvider>,+ });+ await waitFor(() => expect(result.current.issue?.id).toBe(uuid));+ rerender();+ expect(primary).toHaveBeenCalledTimes(1);+ });++ it("preserves the API client's unauthorized callback", async () => {+ const onUnauthorized = vi.fn();+ setApiInstance(new ApiClient("https://synthetic.invalid", { onUnauthorized }));+ primary.mockImplementation(() => Promise.resolve(response(401)));+ render(surface("SYN-1"));+ await screen.findByText(enIssues.detail.not_found_title);+ expect(onUnauthorized).toHaveBeenCalledTimes(1);+ expect(screen.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument();+ });++});diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex a632303597..e9d7514157 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -465,6 +465,8 @@"metadata_description": "Key-value data recorded by agents and integrations for workflow coordination.","section_load_failed_retry": "Could not load. Retry","not_found": "This issue does not exist or has been deleted in this workspace.",+ "load_failed": "Could not load issue.",+ "load_retry": "Retry","not_found_title": "Issue not found","breadcrumb_project_unknown": "Unknown project","back": "Back",diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex f55cda3494..ff01ac77ea 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -557,6 +557,8 @@"thread_nav_show_replies_one": "Mostrar {{count}} respuesta","thread_nav_show_replies_other": "Mostrar {{count}} respuestas","thread_nav_hide_replies": "Ocultar respuestas",+ "load_failed": "No se pudo cargar la tarea.",+ "load_retry": "Reintentar","not_found_title": "Tarea no encontrada"},"timeline": {diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex fd212bf548..64a49f1147 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -465,6 +465,8 @@"metadata_description": "Données clé-valeur enregistrées par les agents et les intégrations pour poursuivre le workflow.","section_load_failed_retry": "Échec du chargement. Réessayer","not_found": "Cette tâche n'existe pas ou a été supprimée dans cet espace de travail.",+ "load_failed": "Impossible de charger la tâche.",+ "load_retry": "Réessayer","not_found_title": "Tâche introuvable","breadcrumb_project_unknown": "Projet inconnu","back": "Retour",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 4922f3600e..1262b573fa 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -459,6 +459,8 @@"metadata_description": "エージェントや連携機能がワークフローを引き継ぐために記録するキーと値のデータ。","section_load_failed_retry": "読み込めませんでした。再試行","not_found": "このタスクはこのワークスペースに存在しないか、削除されています。",+ "load_failed": "タスクを読み込めませんでした。",+ "load_retry": "再試行","not_found_title": "タスクが見つかりません","breadcrumb_project_unknown": "不明なプロジェクト","back": "戻る",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex d11133910e..1f51103411 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -459,6 +459,8 @@"metadata_description": "에이전트와 연동 기능이 작업 흐름을 이어가기 위해 기록하는 키와 값 데이터입니다.","section_load_failed_retry": "불러오지 못했습니다. 다시 시도","not_found": "이 워크스페이스에 해당 태스크가 없거나 삭제되었습니다.",+ "load_failed": "태스크를 불러올 수 없습니다.",+ "load_retry": "다시 시도","not_found_title": "태스크를 찾을 수 없습니다","breadcrumb_project_unknown": "알 수 없는 프로젝트","back": "뒤로",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex c86a4e2d9f..4a67d4e681 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -459,6 +459,8 @@"metadata_description": "智能体和集成记录的键值数据,用于衔接工作流程。","section_load_failed_retry": "加载失败,点击重试","not_found": "这个任务不存在或已在该工作区被删除。",+ "load_failed": "无法加载任务。",+ "load_retry": "重试","not_found_title": "未找到该任务","breadcrumb_project_unknown": "未知项目","back": "返回",diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex e2bfaa63df..a53f9cff69 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -459,6 +459,8 @@"metadata_description": "AI 代理和整合記錄的鍵值資料,用於銜接工作流程。","section_load_failed_retry": "載入失敗,點選重試","not_found": "這個任務不存在或已在該工作區被刪除。",+ "load_failed": "無法載入任務。",+ "load_retry": "重試","not_found_title": "未找到該任務","breadcrumb_project_unknown": "未知專案","back": "返回",