Skip to content

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

Go
22.3 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useState, type ReactNode } from "react";
import {
  collectDeliverableFiles,
  type DeliverableFile,
} from "@multica/core/attachments/deliverables";
import type { Attachment, TimelineEntry } from "@multica/core/types";
import { renderWithI18n } from "../../../test/i18n";

const {
  openAtMock,
  tryOpenMock,
  downloadMock,
  resignedMediaMock,
  copyImageMock,
  copyTextMock,
  originalBlobMock,
} = vi.hoisted(() => ({
  openAtMock: vi.fn((_key: string) => true),
  tryOpenMock: vi.fn(() => false),
  downloadMock: vi.fn(),
  resignedMediaMock: vi.fn((_id: string | undefined, url: string) => ({ url, pending: false })),
  copyImageMock: vi.fn(async (_source: string | (() => Promise<Blob>)) => true),
  copyTextMock: vi.fn(async (_text: string) => true),
  originalBlobMock: vi.fn(async (_id: string) => new Blob(["original"], { type: "image/jpeg" })),
}));

vi.mock("@multica/core/api", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@multica/core/api")>()),
  api: { getBaseUrl: () => "", getAttachmentOriginalBlob: originalBlobMock },
}));

vi.mock("@multica/ui/lib/clipboard", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@multica/ui/lib/clipboard")>()),
  copyImage: copyImageMock,
  copyText: copyTextMock,
}));

vi.mock("@multica/core/workspace/hooks", () => ({
  useActorName: () => ({
    getActorName: (type: string, id: string) => (type === "agent" ? `Agent ${id}` : `Member ${id}`),
  }),
}));

vi.mock("../../../common/actor-avatar", () => ({ ActorAvatar: () => null }));

vi.mock("../../../editor", () => ({
  usePreviewSequence: () => ({ openAt: openAtMock }),
  useAttachmentPreview: () => ({ open: vi.fn(), tryOpen: tryOpenMock, modal: null }),
  useDownloadAttachment: () => downloadMock,
}));

vi.mock("../../../editor/hooks/use-inline-media-url", () => ({
  useResignedInlineMedia: resignedMediaMock,
  useAttachmentThumbnailURL: (_id: string, path: string) => ({ url: path, pending: false, failed: false }),
}));

vi.mock("@multica/core/workspace/avatar-url", () => ({
  resolvePublicFileUrl: (url: string) => url,
}));

vi.mock("../../../platform", () => ({ useImmersiveMode: () => {} }));

import { DeliverablesSection } from "./deliverables-section";
import { DeliverablesOverview } from "./deliverables-overview";
import { useDeliverableDetails, type DeliverableOrigin } from "./deliverable-details";

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: "report.md",
    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/markdown",
    size_bytes: 6 * 1024,
    created_at: "2026-09-20T10:00:00Z",
    ...over,
  };
}

function comment(
  id: string,
  attachments: Attachment[],
  over: Partial<TimelineEntry> = {},
): TimelineEntry {
  return {
    type: "comment",
    id,
    actor_type: "agent",
    actor_id: "lambda",
    actor_name: "Lambda",
    created_at: attachments[0]?.created_at ?? "2026-09-20T10:00:00Z",
    content: "Done — see the files.",
    attachments: attachments.map((a) => ({ ...a, comment_id: id })),
    ...over,
  };
}

// A run posted a screenshot and a report, a later run re-uploaded the
// report next to a CSV: four uploads, three deliverables.
const SHOT = attachment({
  id: "shot",
  filename: "settings.png",
  content_type: "image/png",
  size_bytes: 412 * 1024,
  created_at: "2026-09-20T10:00:00Z",
});
const REPORT_V1 = attachment({ id: "report-1", created_at: "2026-09-20T10:00:01Z" });
const REPORT_V2 = attachment({ id: "report-2", created_at: "2026-09-21T09:00:00Z" });
const CSV = attachment({
  id: "csv",
  filename: "latency.csv",
  content_type: "text/csv",
  size_bytes: 18 * 1024,
  created_at: "2026-09-21T09:00:01Z",
});
const TIMELINE: TimelineEntry[] = [
  comment("c-1", [SHOT, REPORT_V1]),
  comment("c-2", [REPORT_V2, CSV], { created_at: "2026-09-21T09:00:00Z" }),
];
const FILES = collectDeliverableFiles(TIMELINE);

function withQuery(children: ReactNode) {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
}

function renderSection(files: ReadonlyArray<DeliverableFile>, onOpenOverview = vi.fn()) {
  return renderWithI18n(
    withQuery(<DeliverablesSection files={files} onOpenOverview={onOpenOverview} />),
  );
}

beforeEach(() => {
  vi.clearAllMocks();
});

describe("DeliverablesSection", () => {
  it("renders nothing while nothing has been delivered", () => {
    const { container } = renderSection([]);
    expect(container).toBeEmptyDOMElement();
  });

  it("shows the latest version of each file and the total", () => {
    renderSection(FILES);

    expect(screen.getByRole("button", { name: /Deliverables/ })).not.toHaveTextContent("3");
    // One row for the report, marked as its second version.
    const report = screen.getByRole("button", { name: "report.md, version 2" });
    expect(report).toHaveTextContent("v2");
    expect(screen.getAllByTitle("report.md")).toHaveLength(1);
    expect(screen.getByRole("button", { name: "settings.png" })).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "View all 3 deliverables" })).toBeInTheDocument();
  });

  it("keeps the total in the open header once the section lists only the latest", () => {
    const files = Array.from({ length: 5 }, (_, i) =>
      attachment({ id: `doc-${i}`, filename: `notes-${i}.md`, created_at: `2026-09-2${i}T10:00:00Z` }),
    );
    renderSection(collectDeliverableFiles([comment("c-5", files)]));
    expect(screen.getByRole("button", { name: "Deliverables 5" })).toHaveAttribute("aria-expanded", "true");
  });

  it("opens the latest version in the page's viewer", () => {
    renderSection(FILES);
    fireEvent.click(screen.getByRole("button", { name: "report.md, version 2" }));
    expect(openAtMock).toHaveBeenCalledWith("report-2");
  });

  it("downloads a file neither the sequence nor the viewer can open", () => {
    openAtMock.mockReturnValueOnce(false);
    renderSection(
      collectDeliverableFiles([
        comment("c-9", [
          attachment({ id: "zip", filename: "bundle.zip", content_type: "application/zip" }),
        ]),
      ]),
    );
    fireEvent.click(screen.getByRole("button", { name: "bundle.zip" }));
    expect(tryOpenMock).toHaveBeenCalled();
    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("tiles a large image with its thumbnail and falls back to the original if it fails", () => {
    const render = attachment({
      id: "render",
      filename: "render.jpg",
      content_type: "image/jpeg",
      size_bytes: 6 * 1024 * 1024,
      thumbnail_url: "/api/attachments/render/thumbnail",
    });
    const { container } = renderSection(collectDeliverableFiles([comment("c-9", [render, SHOT])]));
    const sources = () =>
      Array.from(container.querySelectorAll("img"), (img) => img.getAttribute("src")).sort();
    // A small image without a thumbnail keeps loading its original.
    expect(sources()).toEqual(["/api/attachments/render/thumbnail", SHOT.download_url].sort());

    fireEvent.error(container.querySelector('img[src="/api/attachments/render/thumbnail"]')!);
    expect(sources()).toEqual([render.download_url, SHOT.download_url].sort());
  });

  it("opens the overview from view all", () => {
    const onOpenOverview = vi.fn();
    renderSection(FILES, onOpenOverview);
    fireEvent.click(screen.getByRole("button", { name: "View all 3 deliverables" }));
    expect(onOpenOverview).toHaveBeenCalledTimes(1);
  });
});

describe("DeliverablesOverview", () => {
  const commentById = new Map(TIMELINE.map((entry) => [entry.id, entry]));

  function renderOverview(props: Partial<Parameters<typeof DeliverablesOverview>[0]> = {}) {
    const onClose = vi.fn();
    const onLocate = vi.fn();
    renderWithI18n(
      withQuery(
        <DeliverablesOverview
          open
          onClose={onClose}
          identifier="MUL-7588"
          files={FILES}
          commentById={commentById}
          onLocate={onLocate}
          returnKey={null}
          {...props}
        />,
      ),
    );
    return { onClose, onLocate };
  }

  it("shows every uploaded image version as a separate selectable thumbnail", () => {
    const older = { ...SHOT, id: "shot-old", created_at: "2026-09-19T10:00:00Z" };
    const files = collectDeliverableFiles([comment("older-comment", [older]), ...TIMELINE]);
    renderOverview({ files });
    expect(screen.getAllByTitle("settings.png")).toHaveLength(2);
    fireEvent.click(screen.getByRole("button", { name: /^Images\s*2$/ }));
    expect(screen.getAllByTitle("settings.png")).toHaveLength(2);
    fireEvent.click(screen.getAllByTitle("settings.png")[0]!);
    expect(openAtMock).toHaveBeenCalledWith("shot-old");
  });

  it("offers a jump for every known posting comment", () => {
    const { onLocate } = renderOverview();
    const buttons = screen.getAllByRole("button", { name: "Show in comments" });
    expect(buttons).toHaveLength(2);
    fireEvent.click(buttons[0]!);
    expect(onLocate).toHaveBeenCalledWith({ kind: "comment", commentId: "c-1" });
  });

  it("counts exactly what the sidebar counts", () => {
    renderOverview();
    const dialog = screen.getByRole("dialog", { name: "MUL-7588 deliverables" });
    expect(within(dialog).getByText(/^3 deliverables/)).toBeInTheDocument();
    expect(within(dialog).getByRole("button", { name: /^All\s*3$/ })).toBeInTheDocument();
    // One group per posting comment; the report sits with its v2.
    const groups = within(dialog).getAllByRole("region", { name: "Comment by Lambda" });
    expect(groups).toHaveLength(2);
    expect(within(groups[0]!).getByTitle("settings.png")).toBeInTheDocument();
    expect(within(groups[1]!).getByTitle("report.md")).toHaveTextContent("v2");
  });

  it("filters by kind", () => {
    renderOverview();
    fireEvent.click(screen.getByRole("button", { name: /^Images\s*1$/ }));
    expect(screen.getByTitle("settings.png")).toBeInTheDocument();
    expect(screen.queryByTitle("report.md")).toBeNull();

    fireEvent.click(screen.getByRole("button", { name: /^Videos\s*0$/ }));
    expect(screen.getByText("No deliverables of this type.")).toBeInTheDocument();
  });

  it("opens a file and locates a comment, closing itself first", () => {
    const { onClose, onLocate } = renderOverview();
    fireEvent.click(screen.getByTitle("latency.csv"));
    expect(onClose).toHaveBeenCalledTimes(1);
    expect(openAtMock).toHaveBeenCalledWith("csv");

    const [, secondGroup] = screen.getAllByRole("region", { name: "Comment by Lambda" });
    fireEvent.click(within(secondGroup!).getByRole("button", { name: "Show in comments" }));
    expect(onClose).toHaveBeenCalledTimes(2);
    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(() => {
      fireEvent.keyDown(document, { key: "g" });
    });
    expect(onClose).toHaveBeenCalledTimes(1);
    expect(openAtMock).toHaveBeenCalledWith("shot");

    act(() => {
      fireEvent.keyDown(document, { key: "Escape" });
    });
    expect(onClose).toHaveBeenCalledTimes(2);
  });
});

describe("DeliverablesOverview focus", () => {
  // A full-window overlay the keyboard can't reach is not a dialog: focus
  // must move in when it opens and go back to the opener when it closes.
  it("takes focus when it opens and returns it to the opener on close", async () => {
    function Harness() {
      const [open, setOpen] = useState(false);
      return (
        <>
          <button type="button" onClick={() => setOpen(true)}>
            View all
          </button>
          <DeliverablesOverview
            open={open}
            onClose={() => setOpen(false)}
            identifier="MUL-7588"
            files={FILES}
            commentById={new Map(TIMELINE.map((entry) => [entry.id, entry]))}
            onLocate={vi.fn()}
            returnKey={null}
          />
        </>
      );
    }
    renderWithI18n(withQuery(<Harness />));
    const opener = screen.getByRole("button", { name: "View all" });
    opener.focus();
    fireEvent.click(opener);

    const dialog = await screen.findByRole("dialog", { name: "MUL-7588 deliverables" });
    await waitFor(() => expect(dialog.contains(document.activeElement)).toBe(true));

    fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
    await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
    await waitFor(() => expect(document.activeElement).toBe(opener));
  });
});

describe("useDeliverableDetails", () => {
  // The viewer covers the page, so "Show in comments" in the info panel has
  // to close it first, exactly like the same action in the top bar.
  it("closes the viewer before locating, from the info panel and the top bar", () => {
    const calls: string[] = [];
    const close = vi.fn(() => calls.push("close"));
    const onLocate = vi.fn((origin: DeliverableOrigin) => calls.push(`locate:${JSON.stringify(origin)}`));
    let locateFromTopBar: (() => void) | undefined;

    function Harness() {
      const describe = useDeliverableDetails({
        files: FILES,
        commentById: new Map(TIMELINE.map((entry) => [entry.id, entry])),
        onLocate,
      });
      const item = { key: "csv", url: CSV.url, filename: CSV.filename, attachment: CSV, imageByConstruction: false, blockId: "c-2" };
      const details = describe(item, { items: [item], goTo: () => true, close });
      locateFromTopBar = details.locate?.onSelect;
      return <>{details.info}</>;
    }
    renderWithI18n(withQuery(<Harness />));

    fireEvent.click(screen.getByRole("button", { name: "Show in comments" }));
    locateFromTopBar?.();
    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();
  });
});

describe("a thumbnail tile's right-click menu", () => {
  const RENDER = attachment({
    id: "render",
    filename: "render.jpg",
    content_type: "image/jpeg",
    size_bytes: 6 * 1024 * 1024,
    thumbnail_url: "/api/attachments/render/thumbnail",
  });
  const SKETCH = attachment({
    id: "sketch",
    filename: "sketch.jpg",
    content_type: "image/jpeg",
    size_bytes: 5 * 1024 * 1024,
    thumbnail_url: "/api/attachments/sketch/thumbnail",
    created_at: "2026-09-20T10:00:02Z",
  });
  const IMAGES = [RENDER, SKETCH];
  const IMAGE_TIMELINE = [comment("c-9", IMAGES)];
  const IMAGE_FILES = collectDeliverableFiles(IMAGE_TIMELINE);

  function DetailsSiblings() {
    const describe = useDeliverableDetails({
      files: IMAGE_FILES,
      commentById: new Map(IMAGE_TIMELINE.map((entry) => [entry.id, entry])),
      onLocate: vi.fn(),
    });
    const items = IMAGES.map((a) => ({
      key: a.id,
      url: a.url,
      filename: a.filename,
      attachment: a,
      imageByConstruction: false,
      blockId: "c-9",
    }));
    return <>{describe(items[1]!, { items, goTo: () => true, close: vi.fn() }).info}</>;
  }

  const surfaces: [string, () => ReactNode][] = [
    ["sidebar", () => <DeliverablesSection files={IMAGE_FILES} onOpenOverview={vi.fn()} />],
    [
      "overview",
      () => (
        <DeliverablesOverview
          open
          onClose={vi.fn()}
          identifier="MUL-9563"
          files={IMAGE_FILES}
          commentById={new Map()}
          onLocate={vi.fn()}
          returnKey={null}
        />
      ),
    ],
    ["viewer details", () => <DetailsSiblings />],
  ];

  function tileOf() {
    return document.querySelector<HTMLImageElement>('img[src="/api/attachments/render/thumbnail"]')!;
  }

  async function pick(name: string) {
    fireEvent.contextMenu(tileOf());
    fireEvent.click(await screen.findByRole("menuitem", { name }));
  }

  async function menuItems() {
    fireEvent.contextMenu(tileOf());
    const items = (await screen.findAllByRole("menuitem")).map((item) => item.textContent);
    fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
    return items;
  }

  describe("with the async Clipboard API", () => {
    beforeEach(() => {
      Object.defineProperty(navigator, "clipboard", {
        configurable: true,
        value: { write: vi.fn() },
      });
      vi.stubGlobal("ClipboardItem", class {});
    });

    afterEach(() => {
      Reflect.deleteProperty(navigator, "clipboard");
      vi.unstubAllGlobals();
    });

    it.each(surfaces)(
      "%s: browsing loads only thumbnails, the menu acts on the original",
      async (_surface, renderSurface) => {
        renderWithI18n(withQuery(renderSurface()));

        // Every tile shows its thumbnail; no original is requested.
        expect(tileOf()).toBeInTheDocument();
        const sources = Array.from(document.querySelectorAll("img"), (img) => img.getAttribute("src"));
        expect(sources.every((src) => src?.endsWith("/thumbnail"))).toBe(true);
        expect(resignedMediaMock).not.toHaveBeenCalled();
        expect(await menuItems()).toEqual(["View image", "Copy image", "Download", "Copy link"]);

        await pick("Copy image");
        expect(copyImageMock).toHaveBeenCalledTimes(1);
        expect(originalBlobMock).not.toHaveBeenCalled();
        const load = copyImageMock.mock.calls[0]![0] as () => Promise<Blob>;
        expect(await (await load()).text()).toBe("original");
        expect(originalBlobMock).toHaveBeenCalledWith("render");

        await pick("Download");
        expect(downloadMock).toHaveBeenCalledWith("render");

        await pick("Copy link");
        expect(copyTextMock).toHaveBeenCalledWith(RENDER.markdown_url);

        // Picking an item does not also open the file under it.
        expect(openAtMock).not.toHaveBeenCalled();
        expect(tryOpenMock).not.toHaveBeenCalled();
      },
    );
  });

  // Plain http:// self-hosting (not localhost) has no async Clipboard API, and
  // nothing can copy an image there but the browser's own menu.
  it.each(surfaces)(
    "%s: without the async Clipboard API, offers the original in the viewer instead of a copy that fails",
    async (_surface, renderSurface) => {
      const actual = await vi.importActual<typeof import("@multica/ui/lib/clipboard")>(
        "@multica/ui/lib/clipboard",
      );
      copyImageMock.mockImplementation(actual.copyImage);
      onTestFinished(() => {
        copyImageMock.mockReset();
      });
      expect(navigator.clipboard?.write).toBeUndefined();
      renderWithI18n(withQuery(renderSurface()));

      expect(await menuItems()).toEqual(["View image", "Download", "Copy link"]);
      await pick("View image");
      expect(openAtMock).toHaveBeenCalledWith("render");
      expect(copyImageMock).not.toHaveBeenCalled();
      expect(originalBlobMock).not.toHaveBeenCalled();
      expect(resignedMediaMock).not.toHaveBeenCalled();
    },
  );
});