Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8745: feat(deliverables): a link that always opens the latest version (#10102)
Eric Yum8310dee5bca8
diff --git a/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx b/apps/desktop/src/renderer/src/pages/issue-detail-page.tsxindex 81e34992ca..e148bb1995 100644--- a/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx+++ b/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx@@ -5,7 +5,9 @@ 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 }>();+ // React Router hands `name` over decoded; on the plain issue route it is+ // undefined.+ const { id, name } = useParams<{ id: string; name?: string }>();const wsId = useWorkspaceId();// `id` may be an identifier (`MUL-123`); resolving here means the title// watches the same UUID-keyed entry realtime events patch. Shares its@@ -18,5 +20,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 <IssueDetailRoute routeId={id} onDelete={onDelete} />;+ return <IssueDetailRoute routeId={id} onDelete={onDelete} deliverable={name} />;}diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsxindex 8287060724..5618959866 100644--- a/apps/desktop/src/renderer/src/routes.tsx+++ b/apps/desktop/src/renderer/src/routes.tsx@@ -162,6 +162,12 @@ export const appRoutes: RouteObject[] = [element: <IssueDetailPage />,handle: { title: "Issue" },},+ {+ // The issue, opened on the newest version of one deliverable.+ path: "issues/:id/deliverables/:name",+ element: <IssueDetailPage />,+ handle: { title: "Issue" },+ },{path: "projects",element: <ProjectsPage />,diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/deliverables/[name]/page.test.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/deliverables/[name]/page.test.tsxnew file mode 100644index 0000000000..90297061a1--- /dev/null+++ b/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/deliverables/[name]/page.test.tsx@@ -0,0 +1,61 @@+import { Suspense } from "react";+import { act, render } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { getRouteRegex } from "next/dist/shared/lib/router/utils/route-regex";+import { getRouteMatcher } from "next/dist/shared/lib/router/utils/route-matcher";+import { paths } from "@multica/core/paths";++const routeProps = vi.hoisted(() => ({+ last: null as { routeId: string; deliverable?: string } | null,+}));++vi.mock("@multica/views/issues/components", () => ({+ IssueDetailRoute: (props: { routeId: string; deliverable?: string }) => {+ routeProps.last = props;+ return null;+ },+}));++import IssueDeliverablePage from "./page";++// Next's own matcher for this route, so the params below are the ones the+// page really receives.+const matchRoute = getRouteMatcher(+ getRouteRegex("/[workspaceSlug]/issues/[id]/deliverables/[name]"),+);++async function renderLink(filename: string) {+ const href = paths.workspace("acme").issueDeliverable("MUL-1", filename);+ const params = matchRoute(href);+ if (!params) throw new Error(`route did not match ${href}`);+ await act(async () => {+ render(+ <Suspense fallback={null}>+ <IssueDeliverablePage+ params={Promise.resolve(params as { id: string; name: string })}+ />+ </Suspense>,+ );+ });+ return routeProps.last;+}++beforeEach(() => {+ routeProps.last = null;+});++describe("deliverable link page", () => {+ it.each([+ "report.html",+ "调研 报告.html",+ "Q3 调研/报告 #2?.html",+ // Literal percent escapes in the file name: Next has already decoded the+ // segment once, and a second decode would name a different file.+ "report%20final.html",+ "report%25final.html",+ "100%.html",+ ])("opens the deliverable the link was built for: %s", async (filename) => {+ const props = await renderLink(filename);+ expect(props).toEqual({ routeId: "MUL-1", deliverable: filename });+ });+});diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/deliverables/[name]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/deliverables/[name]/page.tsxnew file mode 100644index 0000000000..7dff81822b--- /dev/null+++ b/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/deliverables/[name]/page.tsx@@ -0,0 +1,24 @@+"use client";++import { use } from "react";+import { IssueDetailRoute } from "@multica/views/issues/components";+import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";++// `/{ws}/issues/{id}/deliverables/{name}`: the issue page, opened on the+// newest version of the deliverable called `name`.+//+// Next hands dynamic params over already decoded, so `name` is the file name+// itself. Decoding it again would turn a literal `report%20final.html` into+// `report final.html` and look up the wrong file.+export default function IssueDeliverablePage({+ params,+}: {+ params: Promise<{ id: string; name: string }>;+}) {+ const { id, name } = use(params);+ return (+ <ErrorBoundary resetKeys={[id]}>+ <IssueDetailRoute routeId={id} deliverable={name} />+ </ErrorBoundary>+ );+}diff --git a/packages/core/attachments/deliverables.test.ts b/packages/core/attachments/deliverables.test.tsindex e09666fdca..bab7e7f7a4 100644--- a/packages/core/attachments/deliverables.test.ts+++ b/packages/core/attachments/deliverables.test.ts@@ -4,6 +4,7 @@ import type { Attachment } from "../types/attachment";import {collectDeliverableFiles,deliverableKey,+ findDeliverableByName,findDeliverableVersion,} from "./deliverables";@@ -113,3 +114,50 @@ describe("findDeliverableVersion", () => {expect(findDeliverableVersion(files, "")).toBeUndefined();});});++describe("findDeliverableByName", () => {+ it("returns the file whose latest upload is the newest version", () => {+ const v1 = attachment({ id: "a1", filename: "report.html", content_type: "text/html", created_at: "2026-09-20T10:00:00Z" });+ const v2 = attachment({ id: "a2", filename: "report.html", content_type: "text/html", created_at: "2026-09-21T10:00:00Z" });+ const other = attachment({ id: "b1", filename: "notes.md", created_at: "2026-09-22T10:00:00Z" });+ const files = collectDeliverableFiles([{ id: "c1", attachments: [v1, other, v2] }]);+ expect(findDeliverableByName(files, "report.html")?.latest.id).toBe("a2");+ });++ it("follows a new version as soon as it is in the timeline", () => {+ const v1 = attachment({ id: "a1", filename: "report.html", content_type: "text/html", created_at: "2026-09-20T10:00:00Z" });+ const v2 = attachment({ id: "a2", filename: "report.html", content_type: "text/html", created_at: "2026-09-21T10:00:00Z" });+ const before = collectDeliverableFiles([{ id: "c1", attachments: [v1] }]);+ const after = collectDeliverableFiles([+ { id: "c1", attachments: [v1] },+ { id: "c2", attachments: [v2] },+ ]);+ expect(findDeliverableByName(before, "report.html")?.latest.id).toBe("a1");+ expect(findDeliverableByName(after, "report.html")?.latest.id).toBe("a2");+ });++ it("matches names with spaces and non-ASCII characters exactly", () => {+ const spaced = attachment({ id: "s1", filename: "Q3 report final.html", content_type: "text/html" });+ const cjk = attachment({ id: "z1", filename: "调研 报告.md" });+ const files = collectDeliverableFiles([{ id: "c1", attachments: [spaced, cjk] }]);+ expect(findDeliverableByName(files, "Q3 report final.html")?.latest.id).toBe("s1");+ expect(findDeliverableByName(files, "调研 报告.md")?.latest.id).toBe("z1");+ expect(findDeliverableByName(files, " 调研 报告.md ")?.latest.id).toBe("z1");+ expect(findDeliverableByName(files, "调研报告.md")).toBeUndefined();+ });++ it("picks the most recent upload when one name has two content types", () => {+ const plain = attachment({ id: "p1", filename: "a.md", content_type: "text/plain", created_at: "2026-09-20T10:00:00Z" });+ const md = attachment({ id: "m1", filename: "a.md", content_type: "text/markdown", created_at: "2026-09-21T10:00:00Z" });+ const files = collectDeliverableFiles([{ id: "c1", attachments: [plain, md] }]);+ expect(files).toHaveLength(2);+ expect(findDeliverableByName(files, "a.md")?.latest.id).toBe("m1");+ });++ it("returns undefined for unknown or empty names", () => {+ const files = collectDeliverableFiles([{ id: "c1", attachments: [attachment({ id: "a1" })] }]);+ expect(findDeliverableByName(files, "missing.html")).toBeUndefined();+ expect(findDeliverableByName(files, "")).toBeUndefined();+ expect(findDeliverableByName(files, " ")).toBeUndefined();+ });+});diff --git a/packages/core/attachments/deliverables.ts b/packages/core/attachments/deliverables.tsindex af4a90e7c8..e18be3a109 100644--- a/packages/core/attachments/deliverables.ts+++ b/packages/core/attachments/deliverables.ts@@ -95,6 +95,21 @@ export function collectDeliverableFiles(return files.sort((a, b) => compareUploadOrder(b.latest, a.latest));}+/**+ * The deliverable a "latest version" link names: the file called `filename`,+ * compared after trimming like `deliverableKey` does. A name uploaded under+ * two content types is two deliverables; the link means whichever was+ * uploaded most recently. `files` is newest first, so that is the first match.+ */+export function findDeliverableByName(+ files: ReadonlyArray<DeliverableFile>,+ filename: string,+): DeliverableFile | undefined {+ const name = (filename ?? "").trim();+ if (!name) return undefined;+ return files.find((file) => (file.latest.filename ?? "").trim() === name);+}+/*** The deliverable an attachment belongs to and its 1-based version number, or* undefined when the attachment is not a deliverable (a description file, adiff --git a/packages/core/diagnostics/diagnostic-context.ts b/packages/core/diagnostics/diagnostic-context.tsindex 50c396f2e7..ad3cd43453 100644--- a/packages/core/diagnostics/diagnostic-context.ts+++ b/packages/core/diagnostics/diagnostic-context.ts@@ -55,6 +55,7 @@ type RoutePattern = readonly string[];const WORKSPACE_ROUTES: readonly RoutePattern[] = [["issues"],["issues", ":id"],+ ["issues", ":id", "deliverables", ":name"],["projects"],["projects", ":id"],["autopilots"],diff --git a/packages/core/paths/paths.test.ts b/packages/core/paths/paths.test.tsindex e277c304b4..a1f9e3fbb2 100644--- a/packages/core/paths/paths.test.ts+++ b/packages/core/paths/paths.test.ts@@ -41,6 +41,15 @@ describe("paths.workspace(slug)", () => {it("URL-encodes special characters in ids", () => {expect(ws.issueDetail("id with space")).toBe("/acme/issues/id%20with%20space");});++ it("builds a deliverable link with the filename as one encoded segment", () => {+ expect(ws.issueDeliverable("MUL-1", "report.html")).toBe(+ "/acme/issues/MUL-1/deliverables/report.html",+ );+ expect(ws.issueDeliverable("MUL-1", "Q3 调研/报告 #2?.html")).toBe(+ "/acme/issues/MUL-1/deliverables/Q3%20%E8%B0%83%E7%A0%94%2F%E6%8A%A5%E5%91%8A%20%232%3F.html",+ );+ });});describe("paths (global)", () => {diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.tsindex 480d4ea893..29911fd02a 100644--- a/packages/core/paths/paths.ts+++ b/packages/core/paths/paths.ts@@ -42,6 +42,11 @@ function workspaceScoped(slug: string) {usage: () => `${ws}/usage`,issues: () => `${ws}/issues`,issueDetail: (id: string) => `${ws}/issues/${encode(id)}`,+ // Opens the newest upload of the deliverable named `filename` on this+ // issue. Addresses the file by name, not by attachment id, so the link+ // keeps pointing at the latest version as new ones are uploaded.+ issueDeliverable: (id: string, filename: string) =>+ `${ws}/issues/${encode(id)}/deliverables/${encode(filename)}`,projects: () => `${ws}/projects`,projectDetail: (id: string) => `${ws}/projects/${encode(id)}`,autopilots: () => `${ws}/autopilots`,diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsxindex 8d6194de28..cc048fbec1 100644--- a/packages/views/editor/attachment-preview-modal.tsx+++ b/packages/views/editor/attachment-preview-modal.tsx@@ -41,6 +41,7 @@ import {FileVideo,ImageIcon,LayoutGrid,+ Link2,ListTree,Loader2,Maximize2,@@ -224,6 +225,15 @@ export interface PreviewLocateAction {onSelect: () => void;}+/**+ * Copy a link to the file on screen — labelled by the host, which knows what+ * the link points at (for an issue deliverable, its newest version).+ */+export interface PreviewCopyLinkAction {+ label: string;+ onSelect: () => void;+}+/** The info panel beside the stage (MUL-7649). Its open state outlives the file. */export interface PreviewInfoPanel {content: ReactNode;@@ -238,12 +248,19 @@ interface AttachmentPreviewModalProps {sequence?: PreviewSequence;/** Fired when the image kind fails to load — lets a gallery skip the frame. */onImageError?: () => void;+ /**+ * The image failed and the host is staying on it: show the failure on the+ * stage (with a download) instead of a broken frame.+ */+ imageFailed?: boolean;/** Rendered after the file name, e.g. a version switcher. */titleAccessory?: ReactNode;/** Adds the info button and `I`. */info?: PreviewInfoPanel;/** Adds "show where this was posted": the caller closes the viewer and scrolls. */locate?: PreviewLocateAction;+ /** Adds a "copy link" button for the file on screen. */+ copyLink?: PreviewCopyLinkAction;/** Adds the overview button and `G`. */onOpenOverview?: () => void;}@@ -417,9 +434,11 @@ export function AttachmentPreviewModal({onExitComplete,sequence,onImageError,+ imageFailed,titleAccessory,info,locate,+ copyLink,onOpenOverview,}: AttachmentPreviewModalProps & { onExitComplete?: () => void }) {const download = useDownloadAttachment();@@ -592,10 +611,12 @@ export function AttachmentPreviewModal({onOpenInNewTab={canOpenInNewTab ? handleOpenInNewTab : undefined}sequence={sequence}onImageError={onImageError}+ imageFailed={imageFailed}reduceMotion={shouldReduceMotion}titleAccessory={titleAccessory}info={info}locate={locate}+ copyLink={copyLink}onOpenOverview={onOpenOverview}onHtmlAddressChange={handleHtmlAddressChange}/>@@ -681,10 +702,12 @@ function PreviewPanel({onOpenInNewTab,sequence,onImageError,+ imageFailed,reduceMotion,titleAccessory,info,locate,+ copyLink,onOpenOverview,renderHtmlFrame = renderViewerHtmlFrame,initialHtmlAddress = "",@@ -699,10 +722,12 @@ function PreviewPanel({onOpenInNewTab?: () => void;sequence?: PreviewSequence;onImageError?: () => void;+ imageFailed?: boolean;reduceMotion: boolean;titleAccessory?: ReactNode;info?: PreviewInfoPanel;locate?: PreviewLocateAction;+ copyLink?: PreviewCopyLinkAction;onOpenOverview?: () => void;renderHtmlFrame?: HtmlFrameRenderer;/** Query and fragment an HTML file opens at. */@@ -975,6 +1000,11 @@ function PreviewPanel({<MessageSquareText className="size-4" /></ChromeButton>)}+ {copyLink && (+ <ChromeButton label={copyLink.label} onClick={copyLink.onSelect}>+ <Link2 className="size-4" />+ </ChromeButton>+ )}{onOpenInNewTab && (<ChromeButtonlabel={t(($) => $.attachment.open_in_new_tab)}@@ -1048,7 +1078,13 @@ function PreviewPanel({},}}>- {kind === "image" ? (+ {kind === "image" && imageFailed ? (+ <UnsupportedFallback+ message={t(($) => $.attachment.preview_failed)}+ onDownload={handleDownload}+ downloading={downloading}+ />+ ) : kind === "image" ? (<ImagePreviewstate={state}mediaUrl={mediaUrl}diff --git a/packages/views/editor/index.ts b/packages/views/editor/index.tsindex d58afb7f03..37dab00cc3 100644--- a/packages/views/editor/index.ts+++ b/packages/views/editor/index.ts@@ -30,6 +30,7 @@ export {} from "./attachment-preview-modal";export type {AttachmentPreviewHandle,+ PreviewCopyLinkAction,PreviewLocateAction,PreviewSequence,} from "./attachment-preview-modal";@@ -39,6 +40,7 @@ export {usePreviewSequence,} from "./preview-sequence-context";export type {+ OpenAtOptions,PreviewItemDetails,PreviewSequenceControls,} from "./preview-sequence-context";diff --git a/packages/views/editor/preview-sequence-context.test.tsx b/packages/views/editor/preview-sequence-context.test.tsxindex 3ea65abd4f..bff6a5840c 100644--- a/packages/views/editor/preview-sequence-context.test.tsx+++ b/packages/views/editor/preview-sequence-context.test.tsx@@ -345,6 +345,51 @@ describe("PreviewSequenceProvider", () => {expectCounter("1 / 3");});+ it("stays on a file opened by name when it fails, and says so on the stage", () => {+ function PinnedOpener() {+ const sequence = usePreviewSequence();+ return (+ <button type="button" onClick={() => sequence.openAt(THREE[1]!.id, { stayOnError: true })}>+ open+ </button>+ );+ }+ render(+ <PreviewSequenceProvider items={sequenceOf(THREE)}>+ <PinnedOpener />+ </PreviewSequenceProvider>,+ );+ act(() => {+ fireEvent.click(screen.getByText("open"));+ });+ expectCounter("2 / 3");++ act(() => {+ fireEvent.error(screen.getByRole("dialog").querySelector("img")!);+ });++ // Not swapped for a neighbour: same position, same title, no broken frame,+ // a visible failure with a way to download, and no "skipped it" toast.+ expectCounter("2 / 3");+ expect(screen.getByRole("dialog", { name: THREE[1]!.filename })).toBeInTheDocument();+ expect(screen.getByRole("dialog").querySelector("img")).toBeNull();+ // The stage shows the failure with its own download button, beside the+ // top bar's (this file renders without translations, so match structure).+ expect(screen.getAllByRole("button", { name: "Download" })).toHaveLength(2);+ expect(toastErrorMock).not.toHaveBeenCalled();++ // Moving on is still the reader's call, and a later failure skips as usual.+ act(() => {+ fireEvent.click(nextButton());+ });+ expectCounter("3 / 3");+ act(() => {+ fireEvent.error(screen.getByRole("dialog").querySelector("img")!);+ });+ expectCounter("1 / 3");+ expect(toastErrorMock).toHaveBeenCalledTimes(1);+ });+it("pages onto files that are not images", async () => {const mixed = [imageAttachment(1),@@ -575,6 +620,54 @@ describe("host details", () => {await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());});+ it("copies a link from the top bar and stays open", () => {+ const onSelect = vi.fn();+ render(+ <PreviewSequenceProvider+ items={sequenceOf(THREE)}+ describeItem={(item) =>+ item.key === THREE[0]!.id+ ? { copyLink: { label: "Copy link to latest version", onSelect } }+ : undefined+ }+ >+ <Opener openKey={THREE[0]!.id} />+ </PreviewSequenceProvider>,+ );+ openFirst();+ act(() => {+ fireEvent.click(screen.getByRole("button", { name: "Copy link to latest version" }));+ });+ expect(onSelect).toHaveBeenCalledTimes(1);+ expect(screen.getByRole("dialog")).toBeInTheDocument();++ // A file the host has no link for shows no button.+ act(() => {+ fireEvent.click(nextButton());+ });+ expect(screen.queryByRole("button", { name: "Copy link to latest version" })).toBeNull();+ });++ it("reports when the viewer has finished closing, not when it moves", async () => {+ const onClosed = vi.fn();+ render(+ <PreviewSequenceProvider items={sequenceOf(THREE)} onClosed={onClosed}>+ <Opener openKey={THREE[0]!.id} />+ </PreviewSequenceProvider>,+ );+ openFirst();+ act(() => {+ fireEvent.click(nextButton());+ });+ expect(onClosed).not.toHaveBeenCalled();++ act(() => {+ fireEvent.keyDown(document, { key: "Escape" });+ });+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ await waitFor(() => expect(onClosed).toHaveBeenCalledTimes(1));+ });+it("hands the overview the file on screen when G is pressed", async () => {const onOpenOverview = vi.fn();render(diff --git a/packages/views/editor/preview-sequence-context.tsx b/packages/views/editor/preview-sequence-context.tsxindex 402d1aaae5..41568b1412 100644--- a/packages/views/editor/preview-sequence-context.tsx+++ b/packages/views/editor/preview-sequence-context.tsx@@ -54,6 +54,7 @@ import { useT } from "../i18n";import {AttachmentPreviewModal,PreviewImagePrefetch,+ type PreviewCopyLinkAction,type PreviewLocateAction,type PreviewSource,} from "./attachment-preview-modal";@@ -82,6 +83,8 @@ export interface PreviewItemDetails {info?: ReactNode;/** Take the reader to where the file was posted. The viewer closes first. */locate?: PreviewLocateAction;+ /** Copy a link to the file. Unlike `locate`, the viewer stays open. */+ copyLink?: PreviewCopyLinkAction;}/** Handed to `describeItem` so its controls can move within the session. */@@ -105,7 +108,16 @@ interface PreviewSequenceApi {* Returns false when no provider is mounted or the key is not part of this* surface's sequence, so callers can fall back to a single-file preview.*/- openAt: (key: string) => boolean;+ openAt: (key: string, options?: OpenAtOptions) => boolean;+}++export interface OpenAtOptions {+ /**+ * The reader asked for this exact file (a link that names it), so a load+ * failure must not quietly show them a different one: stay on it and say+ * it failed, instead of skipping to the next loadable image.+ */+ stayOnError?: boolean;}const NO_SEQUENCE: PreviewSequenceApi = { openAt: () => false };@@ -144,12 +156,16 @@ interface Session {/** Snapshot taken at open time — see the freeze note in the file header. */items: ImageSequenceItem[];index: number;+ /** The file opened with `stayOnError`; a load failure keeps it on screen. */+ pinnedKey?: string;}export function PreviewSequenceProvider({items,describeItem,onOpenOverview,+ onOpened,+ onClosed,children,}: {items: ReadonlyArray<ImageSequenceItem>;@@ -162,6 +178,13 @@ export function PreviewSequenceProvider({* showing, so the overview can offer a way back to it.*/onOpenOverview?: (currentKey: string) => void;+ /**+ * `openAt` opened the viewer. Called synchronously, inside `openAt`, so a+ * host can tell a handoff into the viewer from the reader leaving.+ */+ onOpened?: () => void;+ /** The viewer finished closing, by any means. */+ onClosed?: () => void;children: ReactNode;}) {const { t } = useT("editor");@@ -169,6 +192,8 @@ export function PreviewSequenceProvider({// context value (and re-render every image) on every incoming message.const itemsRef = useRef(items);itemsRef.current = items;+ const onOpenedRef = useRef(onOpened);+ onOpenedRef.current = onOpened;const [session, setSession] = useState<Session | null>(null);const [open, setOpen] = useState(false);@@ -188,15 +213,20 @@ export function PreviewSequenceProvider({const api = useMemo<PreviewSequenceApi>(() => ({- openAt: (key: string) => {+ openAt: (key: string, options?: OpenAtOptions) => {const snapshot = [...itemsRef.current];const index = indexOfImageKey(snapshot, key);if (index < 0) return false;directionRef.current = 1;brokenRef.current = new Set();setBroken(brokenRef.current);- setSession({ items: snapshot, index });+ setSession({+ items: snapshot,+ index,+ pinnedKey: options?.stayOnError ? key : undefined,+ });setOpen(true);+ onOpenedRef.current?.();return true;},}),@@ -235,6 +265,9 @@ export function PreviewSequenceProvider({brokenRef.current = new Set(brokenRef.current).add(failed.key);setBroken(brokenRef.current);+ // The file the reader asked for by name: stay and show the failure on the+ // stage rather than swapping in a different image.+ if (failed.key === session.pinnedKey) return;toast.error(t(($) => $.image.unavailable));const forward = directionRef.current;@@ -276,8 +309,12 @@ export function PreviewSequenceProvider({source={toPreviewSource(current)}open={open}onClose={() => setOpen(false)}- onExitComplete={() => setSession(null)}+ onExitComplete={() => {+ setSession(null);+ onClosed?.();+ }}onImageError={handleImageError}+ imageFailed={current.key === session.pinnedKey && broken.has(current.key)}titleAccessory={details?.titleAccessory}info={details?.info@@ -295,6 +332,7 @@ export function PreviewSequenceProvider({}: undefined}+ copyLink={details?.copyLink}onOpenOverview={onOpenOverview? () => {diff --git a/packages/views/issues/components/deliverables/deliverable-details.tsx b/packages/views/issues/components/deliverables/deliverable-details.tsxindex e76f12d5e0..aff7dc39ba 100644--- a/packages/views/issues/components/deliverables/deliverable-details.tsx+++ b/packages/views/issues/components/deliverables/deliverable-details.tsx@@ -38,16 +38,20 @@ export type DeliverableOrigin =/*** The issue page's `describeItem` for its preview sequence: the version- * switcher next to the file name, the info panel, and "show in comments".+ * switcher next to the file name, the info panel, "show in comments", and+ * "copy link to latest version" for deliverables.*/export function useDeliverableDetails({files,commentById,onLocate,+ onCopyLink,}: {files: ReadonlyArray<DeliverableFile>;commentById: ReadonlyMap<string, TimelineEntry>;onLocate: (origin: DeliverableOrigin) => void;+ /** Copies a deliverable's latest-version link, by file name. */+ onCopyLink?: (filename: string) => void;}) {const { t } = useT("issues");return useCallback(@@ -95,9 +99,18 @@ export function useDeliverableDetails({/>),locate: locate ? { label: locateLabel, onSelect: locate } : undefined,+ // Only a deliverable has a latest version to link to; a description+ // file is an input, and the link would name no deliverable.+ copyLink:+ deliverable && onCopyLink+ ? {+ label: t(($) => $.deliverables.copy_link),+ onSelect: () => onCopyLink(deliverable.file.latest.filename),+ }+ : undefined,};},- [files, commentById, onLocate, t],+ [files, commentById, onLocate, onCopyLink, t],);}diff --git a/packages/views/issues/components/deliverables/deliverable-link.fresh.test.tsx b/packages/views/issues/components/deliverables/deliverable-link.fresh.test.tsxnew file mode 100644index 0000000000..a5a589d84a--- /dev/null+++ b/packages/views/issues/components/deliverables/deliverable-link.fresh.test.tsx@@ -0,0 +1,197 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { act } from "@testing-library/react";+import { useMemo } from "react";+import { QueryClientProvider, type QueryClient } from "@tanstack/react-query";+import { createQueryClient } from "@multica/core/query-client";+import { issueKeys } from "@multica/core/issues/queries";+import { collectDeliverableFiles } from "@multica/core/attachments/deliverables";+import type { Attachment, TimelineEntry } from "@multica/core/types";+import { renderWithI18n } from "../../../test/i18n";++// The real timeline hook and QueryClient defaults (staleTime: Infinity), with+// the API answer held back so each test decides when the server replies.+const { listTimelineMock, openAtMock, toastMock } = vi.hoisted(() => ({+ listTimelineMock: vi.fn(),+ openAtMock: vi.fn((_key: string, _options?: { stayOnError?: boolean }) => true),+ toastMock: { success: vi.fn(), error: vi.fn() },+}));++vi.mock("@multica/core/api", () => ({ api: { listTimeline: listTimelineMock } }));+vi.mock("@multica/core/realtime", () => ({ useWSEvent: () => {}, useWSReconnect: () => {} }));+// Comment mutations need a workspace and play no part in reading the timeline.+vi.mock("@multica/core/issues/mutations", () => {+ const mutation = () => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false });+ return {+ useCreateComment: mutation,+ useUpdateComment: mutation,+ useDeleteComment: mutation,+ useResolveComment: mutation,+ useToggleCommentReaction: mutation,+ };+});+vi.mock("sonner", () => ({ toast: toastMock }));+vi.mock("../../../editor", () => ({+ usePreviewSequence: () => ({ openAt: openAtMock }),+ useAttachmentPreview: () => ({ open: vi.fn(), tryOpen: () => false, modal: null }),+ useDownloadAttachment: () => vi.fn(),+}));++import { useIssueTimeline } from "../../hooks/use-issue-timeline";+import { OpenDeliverableOnLoad, useFreshTimelineRead } from "./deliverable-link";++const ISSUE = "issue-1";+const NAME = "report.html";++function attachment(id: string, commentId: string): Attachment {+ return {+ id,+ workspace_id: "ws-1",+ issue_id: ISSUE,+ comment_id: commentId,+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "agent",+ uploader_id: "lambda",+ filename: NAME,+ url: `https://cdn.example.test/${id}`,+ download_url: `https://cdn.example.test/${id}?sig=1`,+ markdown_url: `https://cdn.example.test/${id}`,+ content_type: "text/html",+ size_bytes: 1024,+ created_at: `2026-09-2${commentId.slice(-1)}T10:00:00Z`,+ };+}++function comment(id: string, files: Attachment[]): TimelineEntry {+ return {+ type: "comment",+ id,+ actor_type: "agent",+ actor_id: "lambda",+ content: "",+ created_at: files[0]!.created_at,+ updated_at: files[0]!.created_at,+ attachments: files,+ } as TimelineEntry;+}++const WITH_V1 = [comment("c-1", [attachment("v1", "c-1")])];+const WITH_V2 = [...WITH_V1, comment("c-2", [attachment("v2", "c-2")])];++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++// What IssueDetail does with a deliverable link, minus the rest of the page.+function LinkedIssue({ onDone }: { onDone: () => void }) {+ const { timeline, dataUpdatedAt } = useIssueTimeline(ISSUE);+ const files = useMemo(() => collectDeliverableFiles(timeline), [timeline]);+ const read = useFreshTimelineRead(ISSUE, NAME, dataUpdatedAt);+ return (+ <OpenDeliverableOnLoad+ name={NAME}+ files={files}+ read={read}+ onOpenedInViewer={() => {}}+ onDone={onDone}+ />+ );+}++function renderLink(qc: QueryClient) {+ const onDone = vi.fn();+ renderWithI18n(+ <QueryClientProvider client={qc}>+ <LinkedIssue onDone={onDone} />+ </QueryClientProvider>,+ );+ return { onDone };+}++let qc: QueryClient;+beforeEach(() => {+ vi.clearAllMocks();+ qc = createQueryClient();+});++describe("a deliverable link with the issue's timeline already cached", () => {+ it("opens the version the server has now, not the cached one", async () => {+ // An earlier visit cached v1; v2 was uploaded since, and the cache was+ // invalidated (or not) on the way back.+ qc.setQueryData(issueKeys.timeline(ISSUE), WITH_V1);+ await qc.invalidateQueries({ queryKey: issueKeys.timeline(ISSUE), refetchType: "none" });+ const reply = deferred<TimelineEntry[]>();+ listTimelineMock.mockReturnValueOnce(reply.promise);++ const { onDone } = renderLink(qc);+ expect(openAtMock).not.toHaveBeenCalled();++ await act(async () => reply.resolve(WITH_V2));+ expect(openAtMock).toHaveBeenCalledTimes(1);+ expect(openAtMock).toHaveBeenCalledWith("v2", { stayOnError: true });+ expect(onDone).not.toHaveBeenCalled();+ });++ it("reads the server even when the cache counts as fresh", async () => {+ // staleTime: Infinity, not invalidated: mounting alone would not refetch.+ qc.setQueryData(issueKeys.timeline(ISSUE), WITH_V1);+ const reply = deferred<TimelineEntry[]>();+ listTimelineMock.mockReturnValueOnce(reply.promise);++ renderLink(qc);+ expect(listTimelineMock).toHaveBeenCalledTimes(1);+ expect(openAtMock).not.toHaveBeenCalled();++ await act(async () => reply.resolve(WITH_V2));+ expect(openAtMock).toHaveBeenCalledWith("v2", { stayOnError: true });+ });++ it("does not call a file missing because a cached timeline is empty", async () => {+ qc.setQueryData(issueKeys.timeline(ISSUE), []);+ await qc.invalidateQueries({ queryKey: issueKeys.timeline(ISSUE), refetchType: "none" });+ const reply = deferred<TimelineEntry[]>();+ listTimelineMock.mockReturnValueOnce(reply.promise);++ const { onDone } = renderLink(qc);+ expect(toastMock.error).not.toHaveBeenCalled();+ expect(onDone).not.toHaveBeenCalled();++ await act(async () => reply.resolve(WITH_V1));+ expect(openAtMock).toHaveBeenCalledWith("v1", { stayOnError: true });+ expect(toastMock.error).not.toHaveBeenCalled();+ expect(onDone).not.toHaveBeenCalled();+ });++ it("still reports a file the current timeline really does not have", async () => {+ qc.setQueryData(issueKeys.timeline(ISSUE), WITH_V1);+ listTimelineMock.mockResolvedValueOnce([]);++ const { onDone } = renderLink(qc);+ await act(async () => {});+ expect(openAtMock).not.toHaveBeenCalled();+ expect(toastMock.error).toHaveBeenCalledWith(expect.stringContaining(NAME));+ expect(onDone).toHaveBeenCalledTimes(1);+ });+});++describe("a deliverable link whose timeline read fails", () => {+ it("says the load failed and keeps the link, instead of calling the file missing", async () => {+ qc.setQueryData(issueKeys.timeline(ISSUE), []);+ // The app retries a failed query once; both attempts fail here.+ listTimelineMock.mockRejectedValue(new Error("offline"));++ const { onDone } = renderLink(qc);+ await vi.waitFor(() => expect(toastMock.error).toHaveBeenCalledTimes(1), { timeout: 5000 });+ expect(toastMock.error).toHaveBeenCalledWith(expect.stringMatching(/load|reload/i));+ expect(toastMock.error).not.toHaveBeenCalledWith(expect.stringContaining("No deliverable"));+ expect(openAtMock).not.toHaveBeenCalled();+ // The address keeps the link, so reloading tries again.+ expect(onDone).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/issues/components/deliverables/deliverable-link.session.test.tsx b/packages/views/issues/components/deliverables/deliverable-link.session.test.tsxnew file mode 100644index 0000000000..fda6bab423--- /dev/null+++ b/packages/views/issues/components/deliverables/deliverable-link.session.test.tsx@@ -0,0 +1,208 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { act, fireEvent, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { useCallback, useState } from "react";+import { collectDeliverableFiles } from "@multica/core/attachments/deliverables";+import type { Attachment } from "@multica/core/types";+import { renderWithI18n } from "../../../test/i18n";++// The real viewer (PreviewSequenceProvider) and the real overview, wired to+// the link session the way IssueDetail wires them. `onLinkDone` stands for+// the route putting the plain issue address back.+vi.mock("@multica/core/api", () => ({+ api: { getBaseUrl: () => "", getAttachmentTextContent: vi.fn() },+ PreviewTooLargeError: class extends Error {},+ PreviewUnsupportedError: class extends Error {},+}));+vi.mock("../../../platform", () => ({ openExternal: vi.fn(), useImmersiveMode: () => {} }));+vi.mock("../../../editor/use-download-attachment", () => ({ useDownloadAttachment: () => vi.fn() }));+vi.mock("../../../editor/readonly-content", () => ({ ReadonlyContent: () => null }));+vi.mock("../../../editor/hooks/use-inline-media-url", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../../editor/hooks/use-inline-media-url")>()),+ useResignedInlineMedia: (_id: string | undefined, url: string) => ({ url, pending: false }),+}));+vi.mock("@multica/core/workspace/avatar-url", () => ({ resolvePublicFileUrl: (url: string) => url }));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: () => "Lambda" }),+}));+vi.mock("../../../common/actor-avatar", () => ({ ActorAvatar: () => null }));+vi.mock("../../../navigation", () => ({+ useNavigation: () => ({+ push: vi.fn(),+ replace: vi.fn(),+ back: vi.fn(),+ pathname: "/acme/issues/MUL-1",+ searchParams: new URLSearchParams(),+ hash: "",+ getShareableUrl: (p: string) => `https://app.example.test${p}`,+ }),+}));+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++import { PreviewSequenceProvider, collectPreviewSequence } from "../../../editor";+import { DeliverablesOverview } from "./deliverables-overview";+import { OpenDeliverableOnLoad, useDeliverableLinkSession } from "./deliverable-link";++function image(id: string, filename: string, commentId: string): Attachment {+ return {+ id,+ workspace_id: "ws-1",+ issue_id: "issue-1",+ comment_id: commentId,+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "agent",+ uploader_id: "lambda",+ filename,+ url: `https://cdn.example.test/${id}.png`,+ download_url: `https://cdn.example.test/${id}.png?sig=1`,+ markdown_url: `https://cdn.example.test/${id}.png`,+ content_type: "image/png",+ size_bytes: 10,+ created_at: "2026-09-20T10:00:00Z",+ };+}++const CHART = image("a-chart", "chart.png", "c-1");+const PHOTO = image("a-photo", "photo.png", "c-2");+const COMMENTS = [+ { id: "c-1", attachments: [CHART] },+ { id: "c-2", attachments: [PHOTO] },+];+const FILES = collectDeliverableFiles(COMMENTS);+const SEQUENCE = collectPreviewSequence(COMMENTS);++function LinkedIssue({ onLinkDone }: { onLinkDone: () => void }) {+ const link = useDeliverableLinkSession(onLinkDone);+ const [overview, setOverview] = useState<{ open: boolean; returnKey: string | null }>({+ open: false,+ returnKey: null,+ });+ const { onOverviewOpenedFromViewer, onOverviewClosed } = link;+ const openOverviewFromViewer = useCallback(+ (key: string) => {+ onOverviewOpenedFromViewer();+ setOverview({ open: true, returnKey: key });+ },+ [onOverviewOpenedFromViewer],+ );+ const closeOverview = useCallback(() => {+ setOverview((current) => ({ ...current, open: false }));+ onOverviewClosed();+ }, [onOverviewClosed]);+ return (+ <PreviewSequenceProvider+ items={SEQUENCE}+ onOpenOverview={openOverviewFromViewer}+ onOpened={link.onViewerOpened}+ onClosed={link.onViewerClosed}+ >+ <OpenDeliverableOnLoad+ name="chart.png"+ files={FILES}+ read="ready"+ onOpenedInViewer={link.onOpenedInViewer}+ onDone={onLinkDone}+ />+ <DeliverablesOverview+ open={overview.open}+ onClose={closeOverview}+ returnKey={overview.returnKey}+ identifier="MUL-1"+ files={FILES}+ commentById={new Map()}+ onLocate={() => {}}+ />+ </PreviewSequenceProvider>+ );+}++function renderLink() {+ const onLinkDone = vi.fn();+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ renderWithI18n(+ <QueryClientProvider client={qc}>+ <LinkedIssue onLinkDone={onLinkDone} />+ </QueryClientProvider>,+ );+ return { onLinkDone };+}++const overviewTitle = () => screen.queryByText("MUL-1 deliverables");+const viewerFile = (name: string) => screen.queryByRole("img", { name });++async function waitForViewerClosed() {+ await waitFor(() => expect(viewerFile("chart.png")).toBeNull());+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe("a deliverable link's session", () => {+ it("gives the address back when the reader closes the viewer", async () => {+ const { onLinkDone } = renderLink();+ expect(viewerFile("chart.png")).not.toBeNull();+ act(() => {+ fireEvent.keyDown(document, { key: "Escape" });+ });+ await waitForViewerClosed();+ await waitFor(() => expect(onLinkDone).toHaveBeenCalledTimes(1));+ });++ it("keeps the address while the viewer hands over to the overview (G)", async () => {+ const { onLinkDone } = renderLink();+ act(() => {+ fireEvent.keyDown(document, { key: "g" });+ });+ await waitForViewerClosed();+ expect(overviewTitle()).not.toBeNull();+ // Let any queued work run: the address must still be the link's.+ await act(async () => {});+ expect(onLinkDone).not.toHaveBeenCalled();+ });++ it("keeps the address on the All deliverables button too", async () => {+ const { onLinkDone } = renderLink();+ act(() => {+ fireEvent.click(screen.getByRole("button", { name: "All deliverables" }));+ });+ await waitForViewerClosed();+ expect(overviewTitle()).not.toBeNull();+ await act(async () => {});+ expect(onLinkDone).not.toHaveBeenCalled();+ });++ it("gives the address back once the overview is closed", async () => {+ const { onLinkDone } = renderLink();+ act(() => {+ fireEvent.keyDown(document, { key: "g" });+ });+ await waitForViewerClosed();+ act(() => {+ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ });+ await waitFor(() => expect(onLinkDone).toHaveBeenCalledTimes(1));+ });++ it("follows the reader back into the viewer, and ends when that closes", async () => {+ const { onLinkDone } = renderLink();+ act(() => {+ fireEvent.keyDown(document, { key: "g" });+ });+ await waitForViewerClosed();+ // G again: back to the file the viewer was showing.+ act(() => {+ fireEvent.keyDown(document, { key: "g" });+ });+ await waitFor(() => expect(viewerFile("chart.png")).not.toBeNull());+ await act(async () => {});+ expect(onLinkDone).not.toHaveBeenCalled();++ act(() => {+ fireEvent.keyDown(document, { key: "Escape" });+ });+ await waitForViewerClosed();+ await waitFor(() => expect(onLinkDone).toHaveBeenCalledTimes(1));+ });+});diff --git a/packages/views/issues/components/deliverables/deliverable-link.test.tsx b/packages/views/issues/components/deliverables/deliverable-link.test.tsxnew file mode 100644index 0000000000..816510f657--- /dev/null+++ b/packages/views/issues/components/deliverables/deliverable-link.test.tsx@@ -0,0 +1,189 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { collectDeliverableFiles } from "@multica/core/attachments/deliverables";+import type { Attachment } from "@multica/core/types";+import { NavigationProvider, type NavigationAdapter } from "../../../navigation";+import { renderWithI18n } from "../../../test/i18n";++const { openAtMock, tryOpenMock, downloadMock, copyTextMock, toastMock } = vi.hoisted(() => ({+ openAtMock: vi.fn((_key: string, _options?: { stayOnError?: boolean }) => true),+ tryOpenMock: vi.fn(() => false),+ downloadMock: vi.fn(),+ copyTextMock: vi.fn(async (_text: string) => true),+ toastMock: { success: vi.fn(), error: vi.fn() },+}));++vi.mock("../../../editor", () => ({+ usePreviewSequence: () => ({ openAt: openAtMock }),+ useAttachmentPreview: () => ({ open: vi.fn(), tryOpen: tryOpenMock, modal: null }),+ useDownloadAttachment: () => downloadMock,+}));++vi.mock("@multica/ui/lib/clipboard", () => ({ copyText: copyTextMock }));+vi.mock("sonner", () => ({ toast: toastMock }));++vi.mock("@multica/core/paths", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/paths")>(+ "@multica/core/paths",+ );+ return { ...actual, useWorkspacePaths: () => actual.paths.workspace("acme") };+});++import { OpenDeliverableOnLoad, useCopyDeliverableLink } from "./deliverable-link";++function attachment(over: Partial<Attachment> & { id: string }): Attachment {+ return {+ workspace_id: "ws-1",+ issue_id: "issue-1",+ comment_id: "c-1",+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "agent",+ uploader_id: "lambda",+ filename: "调研 报告.html",+ url: `https://cdn.example.test/${over.id}`,+ download_url: `https://cdn.example.test/${over.id}?sig=1`,+ markdown_url: `https://cdn.example.test/${over.id}`,+ content_type: "text/html",+ size_bytes: 1024,+ created_at: "2026-09-20T10:00:00Z",+ ...over,+ };+}++const V1 = attachment({ id: "v1", comment_id: "c-1", created_at: "2026-09-20T10:00:00Z" });+const V2 = attachment({ id: "v2", comment_id: "c-2", created_at: "2026-09-21T10:00:00Z" });+const ONE_VERSION = collectDeliverableFiles([{ id: "c-1", attachments: [V1] }]);+const TWO_VERSIONS = collectDeliverableFiles([+ { id: "c-1", attachments: [V1] },+ { id: "c-2", attachments: [V2] },+]);++function navigation(): NavigationAdapter {+ return {+ push: vi.fn(),+ replace: vi.fn(),+ back: vi.fn(),+ pathname: "/acme/issues/MUL-1",+ searchParams: new URLSearchParams(),+ hash: "",+ getShareableUrl: (p: string) => `https://app.example.test${p}`,+ };+}++function withNav(children: ReactNode) {+ return <NavigationProvider value={navigation()}>{children}</NavigationProvider>;+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe("OpenDeliverableOnLoad", () => {+ function renderOpener(props: Partial<Parameters<typeof OpenDeliverableOnLoad>[0]> = {}) {+ const onOpenedInViewer = vi.fn();+ const onDone = vi.fn();+ const all = {+ name: "调研 报告.html",+ files: ONE_VERSION,+ read: "ready" as const,+ onOpenedInViewer,+ onDone,+ ...props,+ };+ const view = renderWithI18n(<OpenDeliverableOnLoad {...all} />);+ return { ...view, onOpenedInViewer, onDone, props: all };+ }++ it("opens the newest version in the page's viewer", () => {+ const { onOpenedInViewer, onDone } = renderOpener({ files: TWO_VERSIONS });+ expect(openAtMock).toHaveBeenCalledTimes(1);+ // Asks the viewer to stay on the named file if it fails to load.+ expect(openAtMock).toHaveBeenCalledWith("v2", { stayOnError: true });+ expect(onOpenedInViewer).toHaveBeenCalledTimes(1);+ // The viewer is still open; the host puts the address back when it closes.+ expect(onDone).not.toHaveBeenCalled();+ });++ it("opens the new version when the same link is visited after a re-upload", () => {+ const first = renderOpener({ files: ONE_VERSION });+ expect(openAtMock).toHaveBeenLastCalledWith("v1", { stayOnError: true });+ first.unmount();++ renderOpener({ files: TWO_VERSIONS });+ expect(openAtMock).toHaveBeenLastCalledWith("v2", { stayOnError: true });+ });++ it("waits for the timeline before deciding", () => {+ const { rerender, onDone, props } = renderOpener({ files: [], read: "pending" });+ expect(openAtMock).not.toHaveBeenCalled();+ expect(onDone).not.toHaveBeenCalled();+ expect(toastMock.error).not.toHaveBeenCalled();++ rerender(<OpenDeliverableOnLoad {...props} files={ONE_VERSION} read="ready" />);+ expect(openAtMock).toHaveBeenCalledWith("v1", { stayOnError: true });+ expect(toastMock.error).not.toHaveBeenCalled();+ });++ it("does not re-open when a new version arrives while the page is open", () => {+ const { rerender, props } = renderOpener({ files: ONE_VERSION });+ rerender(<OpenDeliverableOnLoad {...props} files={TWO_VERSIONS} />);+ expect(openAtMock).toHaveBeenCalledTimes(1);+ });++ it("says so, and gives the address back, when no deliverable has the name", () => {+ const { onDone, onOpenedInViewer } = renderOpener({ name: "missing.html" });+ expect(openAtMock).not.toHaveBeenCalled();+ expect(toastMock.error).toHaveBeenCalledWith(+ expect.stringContaining("missing.html"),+ );+ expect(onDone).toHaveBeenCalledTimes(1);+ expect(onOpenedInViewer).not.toHaveBeenCalled();+ });++ it("falls back to the standalone viewer or a download outside the sequence", () => {+ // Not in the sequence: the opener's check and the fallback's both say so.+ openAtMock.mockReturnValueOnce(false).mockReturnValueOnce(false);+ const zip = collectDeliverableFiles([+ {+ id: "c-1",+ attachments: [attachment({ id: "zip", filename: "bundle.zip", content_type: "application/zip" })],+ },+ ]);+ const { onDone, onOpenedInViewer } = renderOpener({ name: "bundle.zip", files: zip });+ expect(tryOpenMock).toHaveBeenCalled();+ expect(downloadMock).toHaveBeenCalledWith("zip");+ expect(onOpenedInViewer).not.toHaveBeenCalled();+ expect(onDone).toHaveBeenCalledTimes(1);+ });+});++describe("useCopyDeliverableLink", () => {+ it("copies the latest-version link, not a link to one upload", async () => {+ const { result } = renderHook(() => useCopyDeliverableLink("MUL-1"), {+ wrapper: ({ children }) => withNav(children),+ });+ result.current?.("调研 报告.html");+ await waitFor(() => expect(toastMock.success).toHaveBeenCalled());+ expect(copyTextMock).toHaveBeenCalledWith(+ "https://app.example.test/acme/issues/MUL-1/deliverables/%E8%B0%83%E7%A0%94%20%E6%8A%A5%E5%91%8A.html",+ );+ });++ it("reports a failed copy", async () => {+ copyTextMock.mockResolvedValueOnce(false);+ const { result } = renderHook(() => useCopyDeliverableLink("MUL-1"), {+ wrapper: ({ children }) => withNav(children),+ });+ result.current?.("report.html");+ await waitFor(() => expect(toastMock.error).toHaveBeenCalled());+ });++ it("offers nothing without an issue to link into", () => {+ const { result } = renderHook(() => useCopyDeliverableLink(undefined), {+ wrapper: ({ children }) => withNav(children),+ });+ expect(result.current).toBeUndefined();+ });+});diff --git a/packages/views/issues/components/deliverables/deliverable-link.tsx b/packages/views/issues/components/deliverables/deliverable-link.tsxnew file mode 100644index 0000000000..c25a1e932e--- /dev/null+++ b/packages/views/issues/components/deliverables/deliverable-link.tsx@@ -0,0 +1,225 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import {+ findDeliverableByName,+ type DeliverableFile,+} from "@multica/core/attachments/deliverables";+import { issueTimelineOptions } from "@multica/core/issues/queries";+import { useWorkspacePaths } from "@multica/core/paths";+import { copyText } from "@multica/ui/lib/clipboard";+import { useNavigation } from "../../../navigation";+import { useT } from "../../../i18n";+import { usePreviewSequence } from "../../../editor";+import { useOpenAttachment } from "./use-open-attachment";++/**+ * Copy the "latest version" link of a deliverable: the issue's+ * `/deliverables/<name>` route, which always opens the newest upload of the+ * file. Never a link to one upload, so a link shared once keeps showing the+ * file as it is revised.+ *+ * `issueRef` is the issue identifier (`MUL-123`) or, before it is known, the+ * UUID. Returns undefined without one, so callers render no button.+ */+export function useCopyDeliverableLink(+ issueRef: string | undefined,+): ((filename: string) => void) | undefined {+ const { t } = useT("issues");+ const paths = useWorkspacePaths();+ const navigation = useNavigation();+ // `paths` and the navigation adapter are rebuilt every render; read them at+ // click time so the callback stays stable for memoized rows.+ const latest = useRef({ paths, navigation });+ latest.current = { paths, navigation };+ const copy = useCallback(+ (filename: string) => {+ if (!issueRef) return;+ const { paths, navigation } = latest.current;+ const url = navigation.getShareableUrl(paths.issueDeliverable(issueRef, filename));+ void copyText(url).then((ok) => {+ if (ok) toast.success(t(($) => $.detail.link_copied));+ else toast.error(t(($) => $.detail.link_copy_failed));+ });+ },+ [issueRef, t],+ );+ return issueRef ? copy : undefined;+}++/** Where a deliverable link's read of the issue timeline stands. */+export type TimelineReadStatus = "pending" | "ready" | "failed";++/**+ * One current read of the issue's timeline for a `/deliverables/<name>` link.+ *+ * The link must name the file as it is now, not as a cached timeline from an+ * earlier visit remembers it: that cache may predate the upload the link was+ * shared for (open v1, upload v2 elsewhere, follow the link), or be empty. The+ * query's loading flag cannot tell, because it is false whenever cached data+ * exists, and with the app's `staleTime: Infinity` mounting does not refetch.+ * So this asks the server once per link, and reports `ready` only when the+ * cache the page renders from (`dataUpdatedAt`, from `useIssueTimeline`) has+ * taken that answer, so `files` built from it already include any new upload.+ *+ * `failed` means the read itself failed: the caller must not conclude that+ * the file is missing.+ */+export function useFreshTimelineRead(+ issueId: string,+ name: string | undefined,+ dataUpdatedAt: number,+): TimelineReadStatus {+ const qc = useQueryClient();+ const [read, setRead] = useState<{+ key: string;+ status: "pending" | "done" | "failed";+ at: number;+ } | null>(null);+ const key = name === undefined ? null : `${issueId}\u0000${name}`;++ useEffect(() => {+ if (key === null) return;+ let cancelled = false;+ setRead({ key, status: "pending", at: 0 });+ // staleTime 0: fetch even when the cache counts as fresh. `retry: 1`+ // matches the app's default for queries; fetchQuery's own default is none.+ qc.fetchQuery({ ...issueTimelineOptions(issueId), staleTime: 0, retry: 1 }).then(+ () => {+ if (cancelled) return;+ const at = qc.getQueryState(issueTimelineOptions(issueId).queryKey)?.dataUpdatedAt ?? 0;+ setRead({ key, status: "done", at });+ },+ () => {+ if (!cancelled) setRead({ key, status: "failed", at: 0 });+ },+ );+ return () => {+ cancelled = true;+ };+ }, [qc, issueId, key]);++ if (!read || read.key !== key || read.status === "pending") return "pending";+ if (read.status === "failed") return "failed";+ return dataUpdatedAt >= read.at ? "ready" : "pending";+}++/**+ * Tracks the reader through the file a `/deliverables/<name>` link opened, and+ * calls `onDone` (which gives the address back) once they are done with it.+ *+ * Done is not the viewer closing, nor the overview closing: the reader can go+ * from the viewer to the overview (All deliverables, `G`) and from there back+ * into the viewer. Giving the address back during such a handoff would, on+ * web, swap the deliverable route's page for the issue route's and unmount+ * the surface just opened. So the session follows the reader across both and+ * ends only when neither is left open.+ *+ * Wire `onViewerOpened` / `onViewerClosed` to the `PreviewSequenceProvider`,+ * and the overview callbacks to the host's overview state.+ */+export function useDeliverableLinkSession(onDone: (() => void) | undefined) {+ const sessionRef = useRef<"off" | "viewer" | "overview">("off");+ const onDoneRef = useRef(onDone);+ onDoneRef.current = onDone;++ const finish = useCallback(() => {+ if (sessionRef.current === "off") return;+ sessionRef.current = "off";+ onDoneRef.current?.();+ }, []);++ return {+ /** The link opened its file in the viewer. */+ onOpenedInViewer: useCallback(() => {+ sessionRef.current = "viewer";+ }, []),+ /** The viewer opened; from the overview, the session moves back into it. */+ onViewerOpened: useCallback(() => {+ if (sessionRef.current === "overview") sessionRef.current = "viewer";+ }, []),+ /** The viewer finished closing; handed to the overview, it goes on there. */+ onViewerClosed: useCallback(() => {+ if (sessionRef.current === "viewer") finish();+ }, [finish]),+ /** The viewer handed over to the overview. Runs before the viewer closes. */+ onOverviewOpenedFromViewer: useCallback(() => {+ if (sessionRef.current === "viewer") sessionRef.current = "overview";+ }, []),+ /**+ * The overview closed. It closes first and then, in the same handler, may+ * open a file in the viewer (`G`, a card), so decide once that handler+ * has run: if the viewer took over, the session goes on there.+ */+ onOverviewClosed: useCallback(() => {+ if (sessionRef.current !== "overview") return;+ queueMicrotask(() => {+ if (sessionRef.current === "overview") finish();+ });+ }, [finish]),+ };+}++/**+ * Opens the deliverable a `/deliverables/<name>` link names, once+ * `useFreshTimelineRead` reports a current timeline. Mount inside the issue's+ * `PreviewSequenceProvider`, so the file opens in the page's viewer with its+ * versions and info panel.+ *+ * `onDone` fires when the link has been dealt with and the address should go+ * back to the plain issue page: at once when the file is missing or opened+ * outside the page's viewer (downloaded, or the standalone preview), and left+ * to the host when it opened in the viewer, which knows when that closes.+ *+ * Runs once per name: the reader closing the viewer, or a new version+ * arriving, must not re-open it.+ */+export function OpenDeliverableOnLoad({+ name,+ files,+ read,+ onOpenedInViewer,+ onDone,+}: {+ name: string;+ files: ReadonlyArray<DeliverableFile>;+ /**+ * From `useFreshTimelineRead`. Only `ready` lets a missing file count as+ * missing; on `failed` the link stays in the address, so reloading retries.+ */+ read: TimelineReadStatus;+ onOpenedInViewer: () => void;+ onDone: () => void;+}) {+ const { t } = useT("issues");+ const { openAt } = usePreviewSequence();+ const { open, modal } = useOpenAttachment();+ const handledRef = useRef<string | null>(null);++ useEffect(() => {+ if (read === "pending" || handledRef.current === name) return;+ handledRef.current = name;+ if (read === "failed") {+ toast.error(t(($) => $.deliverables.link_load_failed, { name }));+ return;+ }+ const file = findDeliverableByName(files, name);+ if (!file) {+ toast.error(t(($) => $.deliverables.not_found, { name }));+ onDone();+ return;+ }+ // The link names this file: if it fails to load, stay on it and say so+ // rather than showing the reader a different one.+ if (openAt(file.latest.id, { stayOnError: true })) {+ onOpenedInViewer();+ return;+ }+ open(file.latest);+ onDone();+ }, [read, name, files, openAt, open, onOpenedInViewer, onDone, t]);++ return modal;+}diff --git a/packages/views/issues/components/deliverables/deliverables-overview.tsx b/packages/views/issues/components/deliverables/deliverables-overview.tsxindex 3445d044fc..57644f2bce 100644--- a/packages/views/issues/components/deliverables/deliverables-overview.tsx+++ b/packages/views/issues/components/deliverables/deliverables-overview.tsx@@ -1,11 +1,12 @@"use client";import { useEffect, useMemo, useState, type CSSProperties, type ReactNode } from "react";-import { LayoutGrid, MessageSquareText, X } from "@multica/ui/icons";+import { LayoutGrid, Link2, MessageSquareText, X } from "@multica/ui/icons";import type { DeliverableFile } from "@multica/core/attachments/deliverables";import type { TimelineEntry } from "@multica/core/types";import { useActorName } from "@multica/core/workspace/hooks";import { Dialog, DialogContent, DialogTitle } from "@multica/ui/components/ui/dialog";+import { IconButton } from "@multica/ui/components/common/icon-button";import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";import { useLocale, useT, useTimeAgo } from "../../../i18n";import { ActorAvatar } from "../../../common/actor-avatar";@@ -57,6 +58,7 @@ export function DeliverablesOverview({files,commentById,onLocate,+ onCopyLink,returnKey,}: {open: boolean;@@ -65,6 +67,8 @@ export function DeliverablesOverview({files: ReadonlyArray<DeliverableFile>;commentById: ReadonlyMap<string, TimelineEntry>;onLocate: (origin: DeliverableOrigin) => void;+ /** Copies a deliverable's latest-version link, by file name. */+ onCopyLink?: (filename: string) => void;/** The file the viewer was showing when it opened this; `G` goes back to it. */returnKey: string | null;}) {@@ -121,6 +125,7 @@ export function DeliverablesOverview({onClose();onLocate(origin);}}+ onCopyLink={onCopyLink}/></DialogContent></Dialog>@@ -136,6 +141,7 @@ function OverviewBody({onClose,onOpenFile,onLocate,+ onCopyLink,}: {identifier: string;files: ReadonlyArray<DeliverableFile>;@@ -143,6 +149,7 @@ function OverviewBody({onClose: () => void;onOpenFile: (file: DeliverableFile) => void;onLocate: (origin: DeliverableOrigin) => void;+ onCopyLink?: (filename: string) => void;}) {const { t } = useT("issues");const [filter, setFilter] = useState<Filter>("all");@@ -259,6 +266,7 @@ function OverviewBody({key={group.commentId}group={group}onOpenFile={onOpenFile}+ onCopyLink={onCopyLink}onLocate={group.comment? () => onLocate({ kind: "comment", commentId: group.commentId })@@ -286,10 +294,12 @@ function CommentGroup({group,onOpenFile,onLocate,+ onCopyLink,}: {group: FileGroup;onOpenFile: (file: DeliverableFile) => void;onLocate?: () => void;+ onCopyLink?: (filename: string) => void;}) {const { t } = useT("issues");const locale = useLocale();@@ -335,21 +345,65 @@ function CommentGroup({</div><div className="grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-x-4 gap-y-5">{group.files.map((file) => (- <FileTile key={file.key} file={file} onOpen={() => onOpenFile(file)} />+ <FileTile+ key={file.key}+ file={file}+ onOpen={() => onOpenFile(file)}+ onCopyLink={onCopyLink ? () => onCopyLink(file.latest.filename) : undefined}+ />))}</div></section>);}-function FileTile({ file, onOpen }: { file: DeliverableFile; onOpen: () => void }) {+function FileTile({+ file,+ onOpen,+ onCopyLink,+}: {+ file: DeliverableFile;+ onOpen: () => void;+ onCopyLink?: () => void;+}) {+ const { t } = useT("issues");const { latest } = file;const meta = [fileTypeLabel(latest.filename),latest.size_bytes > 0 ? formatBytes(latest.size_bytes) : "",].filter(Boolean);+ // The copy button sits over the thumbnail's corner as a sibling of the+ // tile's button, since a button can't contain another.+ return (+ <div className="group/tile relative min-w-0">+ <FileTileButton file={file} meta={meta} onOpen={onOpen} />+ {onCopyLink && (+ <IconButton+ size="icon-xs"+ variant="secondary"+ label={t(($) => $.deliverables.copy_link)}+ className="absolute right-1.5 top-1.5 opacity-0 focus-visible:opacity-100 group-hover/tile:opacity-100"+ onClick={onCopyLink}+ >+ <Link2 />+ </IconButton>+ )}+ </div>+ );+}++function FileTileButton({+ file,+ meta,+ onOpen,+}: {+ file: DeliverableFile;+ meta: string[];+ onOpen: () => void;+}) {+ const { latest } = file;return (- <button type="button" className="group min-w-0 text-left" onClick={onOpen} title={latest.filename}>+ <button type="button" className="group w-full min-w-0 text-left" onClick={onOpen} title={latest.filename}><span className="block aspect-[16/10] overflow-hidden rounded-lg ring-1 ring-border transition-shadow group-hover:ring-foreground/40 group-focus-visible:ring-2 group-focus-visible:ring-ring"><DeliverableThumbnail attachment={latest} className="size-full" /></span>diff --git a/packages/views/issues/components/deliverables/deliverables-section.tsx b/packages/views/issues/components/deliverables/deliverables-section.tsxindex 137bd2779c..4bd2c40050 100644--- a/packages/views/issues/components/deliverables/deliverables-section.tsx+++ b/packages/views/issues/components/deliverables/deliverables-section.tsx@@ -3,7 +3,7 @@import { IssueSidebarSectionHeader } from "../issue-sidebar-section";import { useState } from "react";-import { LayoutGrid } from "@multica/ui/icons";+import { LayoutGrid, Link2 } from "@multica/ui/icons";import type { DeliverableFile } from "@multica/core/attachments/deliverables";import { IconButton } from "@multica/ui/components/common/icon-button";import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";@@ -30,9 +30,12 @@ const RECENT_FILES = 4;export function DeliverablesSection({files,onOpenOverview,+ onCopyLink,}: {files: ReadonlyArray<DeliverableFile>;onOpenOverview: () => void;+ /** Copies a deliverable's latest-version link, by file name. */+ onCopyLink?: (filename: string) => void;}) {const { t } = useT("issues");const [open, setOpen] = useState(true);@@ -81,6 +84,7 @@ export function DeliverablesSection({key={file.key}file={file}onOpen={() => openAttachment(file.latest)}+ onCopyLink={onCopyLink ? () => onCopyLink(file.latest.filename) : undefined}/>))}@@ -102,24 +106,52 @@ function versionedName(file: DeliverableFile, t: IssuesT): string {: file.latest.filename;}-function FileRow({ file, onOpen }: { file: DeliverableFile; onOpen: () => void }) {+function FileRow({+ file,+ onOpen,+ onCopyLink,+}: {+ file: DeliverableFile;+ onOpen: () => void;+ onCopyLink?: () => void;+}) {const { t } = useT("issues");const { latest } = file;const Icon = fileIcon(latest.content_type, latest.filename);+ // The copy button is a sibling of the row button, not inside it: a button+ // can't contain another. It shows on hover and on keyboard focus.return (- <button- type="button"- className="group flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-caption transition-colors hover:bg-accent/50"- title={latest.filename}- aria-label={versionedName(file, t)}- onClick={onOpen}- >- <Icon className="size-3.5 shrink-0 text-muted-foreground" />- <span className="min-w-0 truncate">{latest.filename}</span>- {file.versions.length > 1 && <VersionBadge version={file.versions.length} />}- <span className="ml-auto shrink-0 pl-2 text-micro tabular-nums text-muted-foreground">- {latest.size_bytes > 0 ? formatBytes(latest.size_bytes) : null}- </span>- </button>+ <div className="group relative flex items-center rounded-md transition-colors hover:bg-accent/50">+ <button+ type="button"+ className="flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-2 text-left text-caption"+ title={latest.filename}+ aria-label={versionedName(file, t)}+ onClick={onOpen}+ >+ <Icon className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="min-w-0 truncate">{latest.filename}</span>+ {file.versions.length > 1 && <VersionBadge version={file.versions.length} />}+ <span+ className={+ onCopyLink+ ? "ml-auto shrink-0 pl-2 text-micro tabular-nums text-muted-foreground group-hover:invisible group-focus-within:invisible"+ : "ml-auto shrink-0 pl-2 text-micro tabular-nums text-muted-foreground"+ }+ >+ {latest.size_bytes > 0 ? formatBytes(latest.size_bytes) : null}+ </span>+ </button>+ {onCopyLink && (+ <IconButton+ size="icon-xs"+ label={t(($) => $.deliverables.copy_link)}+ className="absolute right-1 opacity-0 focus-visible:opacity-100 group-hover:opacity-100"+ onClick={onCopyLink}+ >+ <Link2 />+ </IconButton>+ )}+ </div>);}diff --git a/packages/views/issues/components/deliverables/deliverables.test.tsx b/packages/views/issues/components/deliverables/deliverables.test.tsxindex 59b57daa7d..abedd61796 100644--- a/packages/views/issues/components/deliverables/deliverables.test.tsx+++ b/packages/views/issues/components/deliverables/deliverables.test.tsx@@ -158,6 +158,29 @@ describe("DeliverablesSection", () => {expect(downloadMock).toHaveBeenCalledWith("zip");});+ it("copies a file's latest-version link from its row, without opening it", () => {+ const onCopyLink = vi.fn();+ renderWithI18n(+ withQuery(+ <DeliverablesSection files={FILES} onOpenOverview={vi.fn()} onCopyLink={onCopyLink} />,+ ),+ );+ const buttons = screen.getAllByRole("button", { name: "Copy link to latest version" });+ // One per file row; the image thumbnails above have none.+ expect(buttons).toHaveLength(2);+ fireEvent.click(buttons[0]!);+ expect(onCopyLink).toHaveBeenCalledWith("latency.csv");+ expect(openAtMock).not.toHaveBeenCalled();+ // The row itself still opens the file.+ fireEvent.click(screen.getByRole("button", { name: "report.md, version 2" }));+ expect(openAtMock).toHaveBeenCalledWith("report-2");+ });++ it("shows no copy button without a link to copy", () => {+ renderSection(FILES);+ expect(screen.queryByRole("button", { name: "Copy link to latest version" })).toBeNull();+ });+it("opens the overview from view all", () => {const onOpenOverview = vi.fn();renderSection(FILES, onOpenOverview);@@ -223,6 +246,19 @@ describe("DeliverablesOverview", () => {expect(onLocate).toHaveBeenCalledWith({ kind: "comment", commentId: "c-2" });});+ it("copies a tile's latest-version link without opening it", () => {+ const onCopyLink = vi.fn();+ const { onClose } = renderOverview({ onCopyLink });+ const dialog = screen.getByRole("dialog", { name: "MUL-7588 deliverables" });+ const buttons = within(dialog).getAllByRole("button", { name: "Copy link to latest version" });+ expect(buttons).toHaveLength(3);+ // Groups are in page order: the screenshot comes first.+ fireEvent.click(buttons[0]!);+ expect(onCopyLink).toHaveBeenCalledWith("settings.png");+ expect(onClose).not.toHaveBeenCalled();+ expect(openAtMock).not.toHaveBeenCalled();+ });+it("goes back to the viewer's file with G, and closes with Escape", () => {const { onClose } = renderOverview({ returnKey: "shot" });act(() => {@@ -302,4 +338,42 @@ describe("useDeliverableDetails", () => {const located = `locate:${JSON.stringify({ kind: "comment", commentId: "c-2" })}`;expect(calls).toEqual(["close", located, "close", located]);});+ it("offers the latest-version link for a deliverable, by file name", () => {+ const onCopyLink = vi.fn();+ let copyLink: { label: string; onSelect: () => void } | undefined;+ function Harness() {+ const describe = useDeliverableDetails({+ files: FILES,+ commentById: new Map(TIMELINE.map((entry) => [entry.id, entry])),+ onLocate: vi.fn(),+ onCopyLink,+ });+ // An older version: the link still names the file, so it opens the newest.+ const item = { key: "report-1", url: REPORT_V1.url, filename: REPORT_V1.filename, attachment: REPORT_V1, imageByConstruction: false, blockId: "c-1" };+ copyLink = describe(item, { items: [item], goTo: () => true, close: vi.fn() }).copyLink;+ return null;+ }+ renderWithI18n(withQuery(<Harness />));+ expect(copyLink?.label).toBe("Copy link to latest version");+ copyLink?.onSelect();+ expect(onCopyLink).toHaveBeenCalledWith("report.md");+ });++ it("offers no link for a file that is not a deliverable", () => {+ let copyLink: unknown = "unset";+ function Harness() {+ const describe = useDeliverableDetails({+ files: FILES,+ commentById: new Map(),+ onLocate: vi.fn(),+ onCopyLink: vi.fn(),+ });+ const brief = attachment({ id: "brief", filename: "brief.pdf", comment_id: null });+ const item = { key: "brief", url: brief.url, filename: brief.filename, attachment: brief, imageByConstruction: false, blockId: "description" };+ copyLink = describe(item, { items: [item], goTo: () => true, close: vi.fn() }).copyLink;+ return null;+ }+ renderWithI18n(withQuery(<Harness />));+ expect(copyLink).toBeUndefined();+ });});diff --git a/packages/views/issues/components/issue-detail-route.test.tsx b/packages/views/issues/components/issue-detail-route.test.tsxindex f822cdf269..48b90ec448 100644--- a/packages/views/issues/components/issue-detail-route.test.tsx+++ b/packages/views/issues/components/issue-detail-route.test.tsx@@ -103,6 +103,36 @@ describe("useCanonicalIssueUrl", () => {);expect(replace).toHaveBeenCalledWith("/acme/issues/TRS-134#comment-comment-7");});++ it("keeps a deliverable link's tail while canonicalizing a UUID", () => {+ renderHook(+ () => useCanonicalIssueUrl(+ "cb240efb-154c-42a8-ae92-42b02676feca",+ "TRS-134",+ "",+ "调研 报告.html",+ ),+ { wrapper },+ );+ expect(replace).toHaveBeenCalledWith(+ "/acme/issues/TRS-134/deliverables/%E8%B0%83%E7%A0%94%20%E6%8A%A5%E5%91%8A.html",+ );+ });++ it("leaves a canonical deliverable link alone", () => {+ renderHook(() => useCanonicalIssueUrl("TRS-134", "TRS-134", "", "report.html"), { wrapper });+ expect(replace).not.toHaveBeenCalled();+ });++ // The deliverable argument is optional: every existing caller passes the+ // hash alone, and its comment deep link must come out exactly as before.+ it("still keeps only the comment hash when no deliverable is named", () => {+ renderHook(+ () => useCanonicalIssueUrl("trs-134", "TRS-134", "#comment-c1", undefined),+ { wrapper },+ );+ expect(replace).toHaveBeenCalledWith("/acme/issues/TRS-134#comment-c1");+ });});describe("parseCommentHighlightHash", () => {diff --git a/packages/views/issues/components/issue-detail-route.tsx b/packages/views/issues/components/issue-detail-route.tsxindex b2787bc6e2..91572e4839 100644--- a/packages/views/issues/components/issue-detail-route.tsx+++ b/packages/views/issues/components/issue-detail-route.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useRef } from "react";+import { useCallback, useEffect, useRef } from "react";import { useCanonicalIssue } from "@multica/core/issues/canonical-id";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";@@ -16,6 +16,11 @@ interface IssueDetailRouteProps {*/routeId: string;onDelete?: () => void;+ /**+ * The decoded file name of a `/{ws}/issues/{segment}/deliverables/{name}`+ * link: open the newest version of that deliverable.+ */+ deliverable?: string;}/**@@ -29,10 +34,15 @@ export function useCanonicalIssueUrl(routeId: string,identifier: string | undefined,hash = "",+ deliverable?: string,) {const paths = useWorkspacePaths();const navigation = useNavigation();- const canonicalHref = identifier ? `${paths.issueDetail(identifier)}${hash}` : null;+ // A deliverable link keeps its `/deliverables/{name}` tail: dropping it+ // would turn the address into a plain issue link while the file is open.+ const canonicalHref = identifier+ ? `${deliverable ? paths.issueDeliverable(identifier, deliverable) : paths.issueDetail(identifier)}${hash}`+ : 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.@@ -68,14 +78,27 @@ function useCommentHighlightHash(): { hash: string; commentId?: string } {* 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) {+export function IssueDetailRoute({ routeId, onDelete, deliverable }: IssueDetailRouteProps) {const wsId = useWorkspaceId();const {canonicalId, issue, isResolving, notFound, loadFailed, isRetrying, retry, hasLoaded,} = useCanonicalIssue(wsId, routeId);const highlight = useCommentHighlightHash();+ const paths = useWorkspacePaths();+ const navigation = useNavigation();++ useCanonicalIssueUrl(routeId, issue?.identifier, highlight.hash, deliverable);- useCanonicalIssueUrl(routeId, issue?.identifier, highlight.hash);+ // Once the link has opened its file and the viewer has closed (or the file+ // is missing), the address becomes the plain issue page. A replace: Back+ // should leave the issue, not re-open the file.+ const issueRef = issue?.identifier ?? routeId;+ const latestNav = useRef({ paths, navigation });+ latestNav.current = { paths, navigation };+ const onDeliverableLinkDone = useCallback(() => {+ const { paths, navigation } = latestNav.current;+ navigation.replace(paths.issueDetail(issueRef));+ }, [issueRef]);if (loadFailed) {return <IssueLoadError showBackLink={!onDelete} onRetry={retry} isRetrying={isRetrying} />;@@ -99,6 +122,8 @@ export function IssueDetailRoute({ routeId, onDelete }: IssueDetailRouteProps) {skipInitialRefetch={hasLoaded}onDelete={onDelete}highlightCommentId={highlight.commentId}+ openDeliverable={deliverable}+ onDeliverableLinkDone={deliverable ? onDeliverableLinkDone : undefined}/></IssuePeekHost>);diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 86fe53cc60..012f4572d4 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -133,6 +133,12 @@ import {} from "./deliverables/deliverable-details";import { collectDeliverableFiles } from "@multica/core/attachments/deliverables";import { AttachmentVersionsProvider } from "./deliverables/attachment-versions";+import {+ OpenDeliverableOnLoad,+ useCopyDeliverableLink,+ useDeliverableLinkSession,+ useFreshTimelineRead,+} from "./deliverables/deliverable-link";import { useQuery } from "@tanstack/react-query";import { useIssueReadState } from "@multica/core/issues/read-state";import { useAuthStore } from "@multica/core/auth";@@ -1207,6 +1213,17 @@ interface IssueDetailProps {readsInbox?: boolean;/** The route already completed the authoritative detail read this mount. */skipInitialRefetch?: boolean;+ /**+ * Route only: the file name of a `/deliverables/<name>` link. Opens the+ * newest upload of that deliverable once the timeline has loaded.+ */+ openDeliverable?: string;+ /**+ * Route only: the deliverable link has been dealt with (the viewer it+ * opened closed, or the file is missing); the route puts the plain issue+ * address back.+ */+ onDeliverableLinkDone?: () => void;}/**@@ -1400,7 +1417,7 @@ export function IssueDetailSkeleton({// IssueDetail-export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, highlightRequestToken, highlightAppRequestId, leadingAction, variant = "page", trailingActions, readsInbox = true, skipInitialRefetch = false }: IssueDetailProps) {+export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, highlightRequestToken, highlightAppRequestId, leadingAction, variant = "page", trailingActions, readsInbox = true, skipInitialRefetch = false, openDeliverable, onDeliverableLinkDone }: IssueDetailProps) {const isPeek = variant === "peek";const { t } = useT("issues");const { t: tCommon } = useT("common");@@ -1716,7 +1733,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// Custom hooks — encapsulate timeline, reactions, subscribersconst {- timeline, loading: timelineLoading,+ timeline, loading: timelineLoading, dataUpdatedAt: timelineUpdatedAt,submitComment, submitReply,editComment, deleteComment, toggleResolveComment, toggleReaction: handleToggleReaction,} = useIssueTimeline(id, user?.id);@@ -2610,11 +2627,24 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trjumpToThread(locateRootRequest);}, [locateRootRequest, jumpToThread]);+ // Identifier form, like the issue's own copy link: a pasted link should say+ // which issue it points at.+ const copyDeliverableLink = useCopyDeliverableLink(issue?.identifier ?? id);const describeDeliverable = useDeliverableDetails({files: deliverableFiles,commentById,onLocate: locateOrigin,+ onCopyLink: copyDeliverableLink,});+ const deliverableLinkRead = useFreshTimelineRead(id, openDeliverable, timelineUpdatedAt);+ // A `/deliverables/<name>` link that opened the viewer gives the address+ // back once the reader is done with the file, through the viewer and the+ // overview alike. Viewer sessions the reader opens themselves leave the+ // address alone.+ const deliverableLink = useDeliverableLinkSession(onDeliverableLinkDone);+ const onDeliverableLinkDoneStable = useCallback(() => {+ onDeliverableLinkDone?.();+ }, [onDeliverableLinkDone]);// The overview remembers the file the viewer was showing, so `G` can go// back to it.const [overview, setOverview] = useState<{ open: boolean; returnKey: string | null }>({@@ -2625,14 +2655,18 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trsetOverview({ open: false, returnKey: null });}, [id]);const openOverview = useCallback(() => setOverview({ open: true, returnKey: null }), []);+ const { onOverviewOpenedFromViewer, onOverviewClosed } = deliverableLink;const openOverviewFromViewer = useCallback(- (key: string) => setOverview({ open: true, returnKey: key }),- [],- );- const closeOverview = useCallback(- () => setOverview((current) => ({ ...current, open: false })),- [],+ (key: string) => {+ onOverviewOpenedFromViewer();+ setOverview({ open: true, returnKey: key });+ },+ [onOverviewOpenedFromViewer],);+ const closeOverview = useCallback(() => {+ setOverview((current) => ({ ...current, open: false }));+ onOverviewClosed();+ }, [onOverviewClosed]);const handleDescriptionUpload = useCallback(async (file: File) => {@@ -3161,7 +3195,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr{/* Deliverables — the files this issue's comments delivered. Hiddenwhile there are none. */}- <DeliverablesSection files={deliverableFiles} onOpenOverview={openOverview} />+ <DeliverablesSection+ files={deliverableFiles}+ onOpenOverview={openOverview}+ onCopyLink={copyDeliverableLink}+ />{/* Apps the issue's runs used. Hidden until one makes a call. */}<IssueAppsSection issueId={id} />@@ -4119,8 +4157,19 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tritems={previewSequence}describeItem={describeDeliverable}onOpenOverview={openOverviewFromViewer}+ onOpened={deliverableLink.onViewerOpened}+ onClosed={deliverableLink.onViewerClosed}><AttachmentVersionsProvider files={deliverableFiles}>{layout}</AttachmentVersionsProvider>+ {openDeliverable && (+ <OpenDeliverableOnLoad+ name={openDeliverable}+ files={deliverableFiles}+ read={deliverableLinkRead}+ onOpenedInViewer={deliverableLink.onOpenedInViewer}+ onDone={onDeliverableLinkDoneStable}+ />+ )}<DeliverablesOverviewopen={overview.open}onClose={closeOverview}@@ -4129,6 +4178,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trfiles={deliverableFiles}commentById={commentById}onLocate={locateOrigin}+ onCopyLink={copyDeliverableLink}/></PreviewSequenceProvider>);diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.tsindex edfa7cd8ef..d2ced295b2 100644--- a/packages/views/issues/hooks/use-issue-timeline.ts+++ b/packages/views/issues/hooks/use-issue-timeline.ts@@ -119,7 +119,7 @@ export function useIssueTimeline(issueId: string, userId?: string) {const qc = useQueryClient();const query = useQuery(issueTimelineOptions(issueId));- const { data, isLoading: loading } = query;+ const { data, isLoading: loading, dataUpdatedAt } = query;const timeline = useMemo<TimelineEntry[]>(() => data ?? [], [data]);@@ -525,6 +525,12 @@ export function useIssueTimeline(issueId: string, userId?: string) {return {timeline: optimisticTimeline,loading,+ /**+ * When the cached timeline was last written (Query's `dataUpdatedAt`).+ * Lets a caller tell whether `timeline` already reflects a read it+ * started; `loading` cannot, as it is false while cached data refreshes.+ */+ dataUpdatedAt,submitComment,submitReply,editComment,diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 8b659d6ab6..20f70cd599 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -1520,6 +1520,9 @@"version_short": "v{{version}}","locate_comment": "Show in comments","locate_description": "Show in description",+ "copy_link": "Copy link to latest version",+ "not_found": "No deliverable named “{{name}}” on this issue",+ "link_load_failed": "Couldn’t load this issue’s deliverables to open “{{name}}”. Reload to try again.","version_label": "Version {{version}} of {{total}}","version_of": "v{{version}} of {{total}}","info_source": "Source",diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex 5d67791e65..c1988d534c 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -1513,6 +1513,9 @@"version_short": "v{{version}}","locate_comment": "Mostrar en comentarios","locate_description": "Mostrar en la descripción",+ "copy_link": "Copiar enlace a la última versión",+ "not_found": "Esta incidencia no tiene ningún entregable llamado «{{name}}»",+ "link_load_failed": "No se pudieron cargar los entregables de esta incidencia para abrir «{{name}}». Recarga para intentarlo de nuevo.","version_label": "Versión {{version}} de {{total}}","version_of": "v{{version}} de {{total}}","info_source": "Origen",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex a68fb6ec0a..ac4a66cdc1 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -1520,6 +1520,9 @@"version_short": "v{{version}}","locate_comment": "Afficher dans les commentaires","locate_description": "Afficher dans la description",+ "copy_link": "Copier le lien vers la dernière version",+ "not_found": "Aucun livrable nommé « {{name}} » sur ce ticket",+ "link_load_failed": "Impossible de charger les livrables de ce ticket pour ouvrir « {{name}} ». Rechargez pour réessayer.","version_label": "Version {{version}} sur {{total}}","version_of": "v{{version}} sur {{total}}","info_source": "Source",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 0d41e8e726..e7a8329259 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -1469,6 +1469,9 @@"version_short": "v{{version}}","locate_comment": "コメントで表示","locate_description": "説明で表示",+ "copy_link": "最新版へのリンクをコピー",+ "not_found": "この課題に「{{name}}」という成果物はありません",+ "link_load_failed": "「{{name}}」を開くための成果物を読み込めませんでした。再読み込みしてもう一度お試しください。","version_label": "バージョン {{version}}(全 {{total}} 版)","version_of": "v{{version}}(全 {{total}} 版)","info_source": "投稿元",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex fc46e47622..4b1db53809 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -1469,6 +1469,9 @@"version_short": "v{{version}}","locate_comment": "댓글에서 보기","locate_description": "설명에서 보기",+ "copy_link": "최신 버전 링크 복사",+ "not_found": "이 이슈에 “{{name}}” 산출물이 없습니다",+ "link_load_failed": "“{{name}}”을(를) 열기 위한 산출물을 불러오지 못했습니다. 새로고침해서 다시 시도하세요.","version_label": "버전 {{version}} / 전체 {{total}}개","version_of": "v{{version}} / 전체 {{total}}개","info_source": "출처",diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.jsonindex 156560f72a..b6d2bc2678 100644--- a/packages/views/locales/ru/issues.json+++ b/packages/views/locales/ru/issues.json@@ -1619,6 +1619,9 @@"version_short": "v{{version}}","locate_comment": "Показать в комментариях","locate_description": "Показать в описании",+ "copy_link": "Скопировать ссылку на последнюю версию",+ "not_found": "В этой задаче нет результата с именем «{{name}}»",+ "link_load_failed": "Не удалось загрузить результаты задачи, чтобы открыть «{{name}}». Обновите страницу, чтобы попробовать снова.","version_label": "Версия {{version}} из {{total}}","version_of": "v{{version}} из {{total}}","info_source": "Источник",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex b87358c44e..07f8f42d73 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -1469,6 +1469,9 @@"version_short": "v{{version}}","locate_comment": "定位到评论","locate_description": "定位到描述",+ "copy_link": "复制最新版链接",+ "not_found": "这个任务里没有名为“{{name}}”的产物",+ "link_load_failed": "没能加载这个任务的产物,打不开“{{name}}”。刷新页面重试。","version_label": "第 {{version}} 版,共 {{total}} 版","version_of": "v{{version}}(共 {{total}} 版)","info_source": "来源",diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex 18656ef3bb..ebdae8034c 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -1469,6 +1469,9 @@"version_short": "v{{version}}","locate_comment": "定位到評論","locate_description": "定位到描述",+ "copy_link": "複製最新版連結",+ "not_found": "這個任務裡沒有名為「{{name}}」的產物",+ "link_load_failed": "沒能載入這個任務的產物,打不開「{{name}}」。重新整理頁面再試一次。","version_label": "第 {{version}} 版,共 {{total}} 版","version_of": "v{{version}}(共 {{total}} 版)","info_source": "來源",