Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(issues): consolidate thread navigation in the sidebar outline (#8120)
Jiayuan Zhangbd6fb861739e
diff --git a/packages/core/shortcuts/definitions.ts b/packages/core/shortcuts/definitions.tsindex b6052fcdbf..b599719c06 100644--- a/packages/core/shortcuts/definitions.ts+++ b/packages/core/shortcuts/definitions.ts@@ -12,7 +12,6 @@ export type ShortcutActionId =| "toggleRightSidebar"| "toggleChat"| "findInIssue"- | "openThreadNav"| "archiveInboxItem"| "send"| "goBack"@@ -95,21 +94,6 @@ export const SHORTCUT_ACTIONS: readonly ShortcutActionDefinition[] = [// to keep working while the caret sits in the chat composer itself.{ id: "toggleChat", category: "general", defaultShortcut: primary("J"), allowInEditable: true },{ id: "findInIssue", category: "general", defaultShortcut: primary("F"), allowInEditable: true },- // Mod+Shift+O mirrors "go to symbol in file" in code editors: jump to a- // section of the document you already have open, as opposed to Mod+F, which- // searches its text. `allowInEditable` because reaching another thread while- // drafting a comment is the common case, not the exception.- //- // Known gap: Chrome on Windows/Linux binds Ctrl+Shift+O to its bookmark- // manager, so on those web builds the default never reaches the page. It is- // recordable rather than reserved because the desktop app does receive it,- // and Settings → Keyboard shortcuts lets affected users rebind.- {- id: "openThreadNav",- category: "general",- defaultShortcut: createShortcutChord("O", { primary: true, shift: true }),- allowInEditable: true,- },{id: "archiveInboxItem",category: "general",diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 5aabdd6351..6d96ebe2f2 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -84,11 +84,8 @@ import { RevisionConflictCompare } from "./revision-conflict-compare";import { CommentInput } from "./comment-input";import { CurrentIssueRenderContextProvider } from "../current-issue-render-context";import { ResolvedThreadBar } from "./resolved-thread-bar";-import { getShortcut, shortcutMatchesEvent } from "@multica/core/shortcuts";-import { isImeComposing } from "@multica/core/utils";-import { ThreadMinimap } from "./thread-minimap";-import { ThreadNavPanel, mentionsUser, type ThreadNavThread } from "./thread-nav-panel";-import { collectThreadReplies, deriveThreadResolution } from "./thread-utils";+import { ThreadMinimap, type ThreadMinimapThread } from "./thread-minimap";+import { collectThreadParticipants, collectThreadReplies, deriveThreadResolution } from "./thread-utils";import { IssueAgentHeaderChip } from "./issue-agent-header-chip";import { ExecutionLogSection } from "./execution-log-section";import { QuickActionsSection } from "./quick-actions-section";@@ -1595,42 +1592,27 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// One entry per comment thread (folded resolved bars included), activity// groups skipped. Derived from the same flat `items` array Virtuoso renders- // so the order always matches the page. Feeds both thread navigators — the- // right-edge rail and the header panel — from one derivation, so they can- // never disagree about what the threads are or what order they are in.+ // so the right-edge outline always matches the page order.//// The resolved flag comes from `deriveThreadResolution`, not from the// `resolved-bar` kind: that kind only covers root resolutions that are// currently folded, so it would miss reply resolutions and would flip off// as soon as the user expanded a resolved thread.- const minimapThreads = useMemo<ThreadNavThread[]>(+ const minimapThreads = useMemo<ThreadMinimapThread[]>(() =>items.flatMap((it) => {if (it.kind !== "comment" && it.kind !== "resolved-bar") return [];const replies = timelineView.threadReplies.get(it.id) ?? EMPTY_REPLIES;- const currentUserId = user?.id ?? "";- // "@me" means the thread concerns this reader: they started it,- // answered in it, or were @mentioned anywhere in it. Authorship counts- // because a thread you spoke in is one you are expected to follow —- // narrowing to literal mentions would drop most of them.- const involvesMe =- currentUserId !== "" &&- ([it.entry, ...replies].some(- (entry) =>- (entry.actor_type === "member" && entry.actor_id === currentUserId) ||- mentionsUser(entry.content, currentUserId),- ));return [{id: it.id,entry: it.entry,resolved: deriveThreadResolution(it.entry, replies).kind !== "none",- replyCount: replies.length,- involvesMe,+ participants: collectThreadParticipants(it.entry, replies),},];}),- [items, timelineView.threadReplies, user?.id],+ [items, timelineView.threadReplies],);// When the timeline renders flat (deep-link or in-page find), there is no@@ -1740,49 +1722,6 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr[isFlatTimeline, items, scrollContainerEl],);- // Header thread navigator. `open` and `pinned` live here rather than inside- // the panel because the global shortcut has to be able to open it already- // pinned, and because the rail needs `threadNavHoverId` to light the tick- // the panel's pointer is resting on — the two navigators share one- // coordinate system (MUL-5755).- const [threadNavOpen, setThreadNavOpen] = useState(false);- const [threadNavPinned, setThreadNavPinned] = useState(false);- const [threadNavHoverId, setThreadNavHoverId] = useState<string | null>(null);- const handleThreadNavOpenChange = useCallback((open: boolean, pinned: boolean) => {- setThreadNavOpen(open);- setThreadNavPinned(pinned);- if (!open) setThreadNavHoverId(null);- }, []);-- // Global Mod+Shift+O. Scoped to the mounted issue detail and gated on- // visibility the same way Cmd+F is, so on desktop only the visible tab- // intercepts the key.- useEffect(() => {- if (minimapThreads.length === 0) return;- const onKeyDown = (e: KeyboardEvent) => {- if (e.defaultPrevented || e.repeat || isImeComposing(e)) return;- if (!shortcutMatchesEvent(getShortcut("openThreadNav"), e)) return;- if (!scrollContainerEl || scrollContainerEl.getClientRects().length === 0) return;- e.preventDefault();- // The shortcut is a deliberate act, so it opens the pinned state- // directly. Pressing it again over a hover preview pins that preview- // rather than closing it, matching what pressing the button does.- if (threadNavOpen && threadNavPinned) {- handleThreadNavOpenChange(false, false);- } else {- handleThreadNavOpenChange(true, true);- }- };- document.addEventListener("keydown", onKeyDown);- return () => document.removeEventListener("keydown", onKeyDown);- }, [- handleThreadNavOpenChange,- minimapThreads.length,- scrollContainerEl,- threadNavOpen,- threadNavPinned,- ]);-const {reactions: issueReactions,toggleReaction: handleToggleIssueReaction,@@ -2775,21 +2714,6 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trit never overlaps the title (which truncates to make room).It self-hides when no agent is active. */}<IssueAgentHeaderChip issueId={id} />- {/* Thread navigator. Leftmost of the action buttons because it- navigates the document, while everything to its right acts on- the issue. Hidden on mobile with the rail: the panel would work- there, but it needs a sheet rather than a popover to be usable- one-handed, which is its own change. */}- {!isMobile && (- <ThreadNavPanel- threads={minimapThreads}- onJump={jumpToThread}- onHoverThread={setThreadNavHoverId}- open={threadNavOpen}- pinned={threadNavPinned}- onOpenChange={handleThreadNavOpenChange}- />- )}{onDone && !issueBehavesAsAny(issue, ["done", "cancelled"]) && (<Tooltip><TooltipTrigger@@ -3481,7 +3405,6 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trthreads={minimapThreads}scrollContainerEl={scrollContainerEl}onJump={jumpToThread}- highlightedThreadId={threadNavHoverId}className="absolute bottom-0 right-3 top-12"/>)}diff --git a/packages/views/issues/components/thread-minimap.test.tsx b/packages/views/issues/components/thread-minimap.test.tsxindex 1c38d8e2ce..5b6399f777 100644--- a/packages/views/issues/components/thread-minimap.test.tsx+++ b/packages/views/issues/components/thread-minimap.test.tsx@@ -1,5 +1,5 @@import { describe, expect, it, vi } from "vitest";-import { act, fireEvent, screen } from "@testing-library/react";+import { act, fireEvent, screen, within } from "@testing-library/react";import type { TimelineEntry } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";import { ThreadMinimap, commentPreview, waveScale } from "./thread-minimap";@@ -7,6 +7,8 @@ import { ThreadMinimap, commentPreview, waveScale } from "./thread-minimap";vi.mock("@multica/core/workspace/hooks", () => ({useActorName: () => ({getActorName: (type: string, id: string) => `${type}:${id}`,+ getActorInitials: (_type: string, _id: string, name: string) => name.slice(0, 1),+ getActorAvatarUrl: () => null,}),}));@@ -74,9 +76,9 @@ describe("waveScale", () => {describe("ThreadMinimap", () => {const threads = [- { id: "c1", entry: comment("c1", "First thread opener\nwith details"), resolved: false },- { id: "c2", entry: comment("c2", "Second thread opener"), resolved: false },- { id: "c3", entry: comment("c3", ""), resolved: false },+ { id: "c1", entry: comment("c1", "First thread opener\nwith details"), resolved: false, participants: [] },+ { id: "c2", entry: comment("c2", "Second thread opener"), resolved: false, participants: [] },+ { id: "c3", entry: comment("c3", ""), resolved: false, participants: [] },];it("renders nothing below the thread threshold", () => {@@ -100,7 +102,7 @@ describe("ThreadMinimap", () => {expect(screen.getByRole("button", { name: "member:author-c3" })).toBeInTheDocument();});- it("opens the shared preview card after the intent delay and closes after the leave grace", () => {+ it("opens all thread titles after the intent delay and closes after the leave grace", () => {vi.useFakeTimers({toFake: ["setTimeout", "clearTimeout", "requestAnimationFrame", "cancelAnimationFrame"],});@@ -113,16 +115,21 @@ describe("ThreadMinimap", () => {// jsdom rects are all zero → the nearest tick resolves to index 0.fireEvent.pointerMove(nav, { clientY: 0 });act(() => vi.advanceTimersByTime(30)); // rAF flush — arms the intent timer- expect(screen.queryByText("with details")).not.toBeInTheDocument();+ expect(screen.queryByRole("list")).not.toBeInTheDocument();act(() => vi.advanceTimersByTime(150)); // intent delay elapses → card opens- expect(screen.getByText("with details")).toBeInTheDocument();+ const list = screen.getByRole("list");+ expect(within(list).getAllByRole("button")).toHaveLength(3);+ expect(within(list).getByText("First thread opener")).toBeInTheDocument();+ expect(within(list).getByText("Second thread opener")).toBeInTheDocument();+ expect(within(list).getByText("member:author-c3")).toBeInTheDocument();+ expect(screen.queryByText("with details")).not.toBeInTheDocument();fireEvent.pointerLeave(nav);act(() => vi.advanceTimersByTime(30)); // wave-clear frame- expect(screen.getByText("with details")).toBeInTheDocument(); // grace keeps it up+ expect(screen.getByRole("list")).toBeInTheDocument(); // grace keeps it upact(() => vi.advanceTimersByTime(150)); // grace elapses → card closes- expect(screen.queryByText("with details")).not.toBeInTheDocument();+ expect(screen.queryByRole("list")).not.toBeInTheDocument();} finally {vi.useRealTimers();}@@ -147,7 +154,7 @@ describe("ThreadMinimap", () => {fireEvent.pointerMove(nav, { clientY: 0 });act(() => vi.advanceTimersByTime(30 + 150)); // rAF flush + intent delay- const card = screen.getByText("with details").closest("div");+ const card = screen.getByRole("list").closest("div");expect(card).toHaveClass("right-8");expect(card?.className).not.toMatch(/(?:^|\s)left-/);} finally {@@ -155,7 +162,7 @@ describe("ThreadMinimap", () => {}});- it("badges the preview card of a resolved thread, and only that one", () => {+ it("marks resolved threads in the complete outline", () => {vi.useFakeTimers({toFake: ["setTimeout", "clearTimeout", "requestAnimationFrame", "cancelAnimationFrame"],});@@ -173,18 +180,139 @@ describe("ThreadMinimap", () => {// resolved thread.fireEvent.pointerMove(nav, { clientY: 0 });act(() => vi.advanceTimersByTime(30 + 150)); // rAF flush + intent delay- expect(screen.getByText("Resolved")).toBeInTheDocument();+ expect(screen.getByLabelText("Resolved")).toBeInTheDocument();- // The badge belongs to the hovered thread, not to the card: closing it- // must take the badge with it.+ // Closing the outline removes its resolution indicator too.fireEvent.pointerLeave(nav);act(() => vi.advanceTimersByTime(30 + 150));- expect(screen.queryByText("Resolved")).not.toBeInTheDocument();+ expect(screen.queryByLabelText("Resolved")).not.toBeInTheDocument();} finally {vi.useRealTimers();}});+ it("keeps the outline open while moving onto it and jumps from any title", () => {+ vi.useFakeTimers({+ toFake: ["setTimeout", "clearTimeout", "requestAnimationFrame", "cancelAnimationFrame"],+ });+ try {+ const onJump = vi.fn();+ renderWithI18n(+ <ThreadMinimap threads={threads} scrollContainerEl={null} onJump={onJump} />,+ );+ const nav = screen.getByRole("navigation");+ fireEvent.pointerMove(nav, { clientY: 0 });+ act(() => vi.advanceTimersByTime(180));+ const list = screen.getByRole("list");+ fireEvent.pointerLeave(nav);+ fireEvent.pointerEnter(list.parentElement!);+ act(() => vi.advanceTimersByTime(180));+ expect(list).toBeInTheDocument();+ const second = within(list).getByRole("button", { name: "Second thread opener" });+ fireEvent.pointerEnter(second);+ expect(second).toHaveAttribute("data-active");+ fireEvent.click(second);+ expect(onJump).toHaveBeenCalledWith("c2");+ } finally {+ vi.useRealTimers();+ }+ });++ it.each(["rail", "outline"])("closes after clicking the %s and moving away", (target) => {+ vi.useFakeTimers({+ toFake: ["setTimeout", "clearTimeout", "requestAnimationFrame", "cancelAnimationFrame"],+ });+ try {+ const onJump = vi.fn();+ renderWithI18n(+ <ThreadMinimap threads={threads} scrollContainerEl={null} onJump={onJump} />,+ );+ const nav = screen.getByRole("navigation");+ fireEvent.pointerMove(nav, { clientY: 0 });+ act(() => vi.advanceTimersByTime(180));+ const card = screen.getByRole("list").parentElement!;+ const button = within(target === "rail" ? nav : card)+ .getByRole("button", { name: "Second thread opener" });+ if (target === "outline") {+ fireEvent.pointerLeave(nav);+ fireEvent.pointerEnter(card);+ }+ // Native mouse clicks focus buttons before dispatching click.+ act(() => button.focus());+ fireEvent.click(button, { detail: 1 });+ expect(onJump).toHaveBeenCalledWith("c2");+ act(() => vi.advanceTimersByTime(180));+ expect(screen.getByRole("list")).toBeInTheDocument();+ fireEvent.pointerLeave(target === "rail" ? nav : card);+ act(() => vi.advanceTimersByTime(180));+ expect(screen.queryByRole("list")).not.toBeInTheDocument();+ } finally {+ vi.useRealTimers();+ }+ });++ it("keeps keyboard focus after activating an outline title", () => {+ vi.useFakeTimers();+ try {+ const onJump = vi.fn();+ renderWithI18n(+ <ThreadMinimap threads={threads} scrollContainerEl={null} onJump={onJump} />,+ );+ act(() => screen.getByRole("button", { name: "First thread opener" }).focus());+ const card = screen.getByRole("list").parentElement!;+ const button = within(card).getByRole("button", { name: "Second thread opener" });+ act(() => button.focus());+ fireEvent.click(button, { detail: 0 });+ fireEvent.pointerLeave(card);+ act(() => vi.advanceTimersByTime(180));+ expect(onJump).toHaveBeenCalledWith("c2");+ expect(button).toHaveFocus();+ expect(screen.getByRole("list")).toBeInTheDocument();+ } finally {+ vi.useRealTimers();+ }+ });++ it("opens on keyboard focus and dismisses with Escape, returning focus to the matching tick", () => {+ renderWithI18n(+ <ThreadMinimap threads={threads} scrollContainerEl={null} onJump={vi.fn()} />,+ );+ const nav = screen.getByRole("navigation");+ act(() => within(nav).getByRole("button", { name: "First thread opener" }).focus());+ const list = screen.getByRole("list");+ const second = within(list).getByRole("button", { name: "Second thread opener" });+ act(() => second.focus());+ fireEvent.keyDown(second, { key: "Escape" });+ expect(screen.queryByRole("list")).not.toBeInTheDocument();+ expect(within(nav).getByRole("button", { name: "Second thread opener" })).toHaveFocus();+ });++ it("shows member and agent avatars with overflow alongside resolution", () => {+ const participants = [+ { ...comment("alice", ""), actor_name: "Alice", actor_avatar_url: "https://example.com/alice.png" },+ { ...comment("agent", ""), actor_type: "agent", actor_name: "Design agent" },+ { ...comment("bob", ""), actor_name: "Bob" },+ { ...comment("carol", ""), actor_name: "Carol" },+ ];+ renderWithI18n(+ <ThreadMinimap+ threads={[{ ...threads[0]!, resolved: true, participants }, ...threads.slice(1)]}+ scrollContainerEl={null}+ onJump={vi.fn()}+ />,+ );+ act(() => screen.getByRole("button", { name: "First thread opener (resolved)" }).focus());+ const row = within(screen.getByRole("list"))+ .getByRole("button", { name: "First thread opener (resolved)" });+ expect(row).toHaveAttribute("aria-description", "Alice, Design agent, Bob, Carol");+ expect(within(row).getByAltText("Alice")).toHaveAttribute("src", "https://example.com/alice.png");+ expect(within(row).getByTitle("Design agent").querySelector(".lucide-bot")).not.toBeNull();+ expect(within(row).getByTitle("Bob")).toBeInTheDocument();+ expect(within(row).getByTitle("Carol")).toHaveTextContent("+1");+ expect(within(row).getByLabelText("Resolved")).toBeInTheDocument();+ expect(within(row).queryByRole("link")).not.toBeInTheDocument();+ });+it("carries the resolved state in the tick's accessible name", () => {renderWithI18n(<ThreadMinimap@@ -194,7 +322,7 @@ describe("ThreadMinimap", () => {/>,);- // The card is visual only — a screen reader gets the state from the tick.+ // The collapsed rail announces resolution before the outline is opened.expect(screen.getByRole("button", { name: "First thread opener (resolved)" }),).toBeInTheDocument();diff --git a/packages/views/issues/components/thread-minimap.tsx b/packages/views/issues/components/thread-minimap.tsxindex 12e7aac7ca..65c4700897 100644--- a/packages/views/issues/components/thread-minimap.tsx+++ b/packages/views/issues/components/thread-minimap.tsx@@ -3,37 +3,15 @@ import { CheckCircle2 } from "lucide-react";import type { TimelineEntry } from "@multica/core/types";import { useActorName } from "@multica/core/workspace/hooks";import { cn } from "@multica/ui/lib/utils";+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import { useT } from "../../i18n";// ----------------------------------------------------------------------------// ThreadMinimap — Linear-style quick-jump rail for comment threads-// ----------------------------------------------------------------------------//-// A vertical column of tick marks overlaid on the right edge of the issue-// detail scroll area, just inside the scrollbar, one tick per top-level-// comment thread (folded resolved bars included — they are jump targets too).-// Ticks whose thread is currently inside the scroll viewport render darker, so-// the rail doubles as a "you are here" minimap. Hovering magnifies ticks in a-// Dock-style wave around the cursor (the hovered tick peaks, neighbours taper-// off) and shows a preview card (bold first line + muted body excerpt, plus a-// "Resolved" badge when the thread carries a resolution — the rail is the one-// place a folded resolved thread is otherwise indistinguishable from an open-// one); clicking jumps the timeline to that thread.-//-// It rides the scrollbar side on purpose: it looks and behaves like a scroll-// affordance, and every precedent for that (the scrollbar itself, editor-// minimaps, floating outlines) lives on the right — so the pointer is already-// there, and the travel from scrolling to jumping is short (MUL-4522).-//-// The preview is ONE card owned by the rail, not a popover per tick: the-// open-intent delay is paid once when the pointer enters the rail, and while-// the pointer glides across ticks the card swaps content instantly and-// slides to the hovered tick. Per-tick popovers re-paid the open delay and-// exit/enter animations on every tick crossed, which read as lag when-// scanning the rail continuously.-//-// The rail deliberately skips activity groups: they are timeline noise, not-// navigation destinations.+// ThreadMinimap — quick-jump rail with a complete thread outline.+// The rail shows viewport position; hovering or focusing any tick opens one+// stationary, scrollable list of every thread title. Rows jump to the same+// timeline anchors as the ticks, including folded resolved threads./** Minimum number of threads before the rail is worth its pixels. */const MIN_THREADS = 2;@@ -119,6 +97,8 @@ export interface ThreadMinimapThread {* a folded resolved thread expanded.*/resolved: boolean;+ /** Unique authors across the root and every nested reply, in first-seen order. */+ participants: TimelineEntry[];}interface ThreadMinimapProps {@@ -126,12 +106,6 @@ interface ThreadMinimapProps {/** The issue detail scroll container; null until its callback ref populates. */scrollContainerEl: HTMLElement | null;onJump: (threadId: string) => void;- /**- * Thread the header panel's pointer is currently resting on. The rail lights- * that tick in the brand colour so the two navigators read as one coordinate- * system rather than two competing lists (MUL-5755).- */- highlightedThreadId?: string | null;/** Positioning within the page (e.g. `absolute right-3 top-12 bottom-0`) — owned by the caller, like FindBar. */className?: string;}@@ -142,8 +116,7 @@ interface ThreadMinimapProps {//// Which threads intersect the scroll viewport, so the rail can darken their// ticks. Deliberately the rail's alone: "on screen" is a set, not a point, and-// only a column of ticks can show a span honestly — the header panel tried to-// render the same set as list rows and it read as a broken multi-select.+// only a column of ticks can show a span without suggesting multiple selection.//// Computed from DOM rects on scroll/resize instead of an IntersectionObserver// because Virtuoso mounts/unmounts rows while scrolling — an observer would@@ -200,26 +173,22 @@ function useVisibleThreadIds(return visibleIds;}-/** The rail-owned preview card's target: which tick, anchored at which shim-relative Y. */+/** The thread currently highlighted in the outline and rail. */interface PreviewAnchor {index: number;- y: number;}function MinimapTick({label,inViewport,- isPreviewOpen,isHighlighted,onClick,}: {label: string;inViewport: boolean;- /** This tick's preview is the open card — hold the grown state even when the pointer is on the card. */- isPreviewOpen: boolean;- /** The header panel is hovering this thread's row. */+ /** The corresponding outline row is active. */isHighlighted: boolean;- onClick: () => void;+ onClick: React.MouseEventHandler<HTMLButtonElement>;}) {return (<button@@ -242,19 +211,14 @@ function MinimapTick({// pointer samples and as the settle on leave."h-0.5 w-3 origin-right rounded-full transition-[scale,background-color] duration-100 ease-out",inViewport ? "bg-foreground/70" : "bg-muted-foreground/30",- "group-hover/tick:bg-foreground",+ !isHighlighted && "group-hover/tick:bg-foreground",// CSS floor states for when no inline wave value is present:// the open card's tick stays grown while the pointer rests on the// card, keyboard focus grows without a pointer, and reduced-motion// swaps the wave for a plain hover grow.- isPreviewOpen && "scale-x-[1.7] bg-foreground",- // Panel-driven highlight. Brand colour, not foreground: it marks- // "the panel is pointing here", which is a different statement from- // the rail's own hover/viewport greys and must stay distinguishable- // from both. Wins over `inViewport` because it is the more specific,- // user-driven state.isHighlighted && "scale-x-[1.7] bg-brand",- "group-focus-visible/tick:scale-x-[1.7] group-focus-visible/tick:bg-foreground",+ "group-focus-visible/tick:scale-x-[1.7]",+ !isHighlighted && "group-focus-visible/tick:bg-foreground","motion-reduce:group-hover/tick:scale-x-[1.7]",)}/>@@ -266,11 +230,10 @@ export function ThreadMinimap({threads,scrollContainerEl,onJump,- highlightedThreadId,className,}: ThreadMinimapProps) {const { t } = useT("issues");- const { getActorName } = useActorName();+ const { getActorName, getActorInitials, getActorAvatarUrl } = useActorName();const threadIds = useMemo(() => threads.map((th) => th.id), [threads]);const visibleIds = useVisibleThreadIds(threadIds, scrollContainerEl);@@ -299,8 +262,7 @@ export function ThreadMinimap({// Hover wave + preview targeting. Pointer position lives in refs and ticks// are scaled with direct style writes so pointermove never re-renders the// component; the rAF guard coalesces bursts to one batched read-then-write- // per frame. The same rect pass derives which tick the card should anchor- // to, so the card and the wave can never disagree about the hovered tick.+ // per frame. The same rect pass selects the corresponding outline row.const waveRafRef = useRef(0);const pointerYRef = useRef<number | null>(null);const reducedMotionRef = useRef(false);@@ -314,7 +276,7 @@ export function ThreadMinimap({const showPreview = useCallback((anchor: PreviewAnchor | null) => {previewRef.current = anchor;setPreview((prev) =>- prev?.index === anchor?.index && prev?.y === anchor?.y ? prev : anchor,+ prev?.index === anchor?.index ? prev : anchor,);}, []);@@ -341,10 +303,21 @@ export function ThreadMinimap({}closeTimerRef.current = window.setTimeout(() => {closeTimerRef.current = null;- showPreview(null);+ if (!shimRef.current?.contains(document.activeElement)) showPreview(null);}, PREVIEW_CLOSE_DELAY_MS);}, [cancelClose, showPreview]);+ const handleJump = useCallback((threadId: string, event: React.MouseEvent<HTMLButtonElement>) => {+ // Mouse clicks must not pin a hover outline through leftover button focus.+ // Keyboard activation keeps focus so the reader can continue navigating.+ if (event.detail > 0) {+ event.currentTarget.blur();+ // Blur schedules a close; keep the card until the pointer actually leaves.+ cancelClose();+ }+ onJump(threadId);+ }, [cancelClose, onJump]);+const runWave = useCallback(() => {waveRafRef.current = 0;const nav = navRef.current;@@ -353,11 +326,8 @@ export function ThreadMinimap({const y = pointerYRef.current;const buttons = nav.querySelectorAll<HTMLButtonElement>("button");// Read pass, then write pass — never interleaved, one reflow at most.- const shimTop = shim.getBoundingClientRect().top;- const shimHeight = shim.clientHeight;- const cardHalf = (cardRef.current?.offsetHeight ?? 96) / 2;const scales: string[] = [];- let nearest: { index: number; centerY: number; dist: number } | null = null;+ let nearest: { index: number; dist: number } | null = null;buttons.forEach((b, i) => {if (y === null) {scales.push("");@@ -368,7 +338,7 @@ export function ThreadMinimap({const dist = Math.abs(y - centerY);const s = reducedMotionRef.current ? 1 : waveScale(y - centerY);scales.push(s > 1.001 ? `${s.toFixed(3)} 1` : "");- if (!nearest || dist < nearest.dist) nearest = { index: i, centerY, dist };+ if (!nearest || dist < nearest.dist) nearest = { index: i, dist };});buttons.forEach((b, i) => {const tick = b.firstElementChild as HTMLElement | null;@@ -380,17 +350,12 @@ export function ThreadMinimap({else tick.style.removeProperty("scale");});- // Preview targeting from the same pass. Clamp the anchor so the card- // never sticks out of the rail's column at the extremes.if (y === null || !nearest) return;- const { index, centerY } = nearest as { index: number; centerY: number };- const anchor: PreviewAnchor = {- index,- y: Math.min(Math.max(centerY - shimTop, cardHalf + 6), shimHeight - cardHalf - 6),- };+ const { index } = nearest as { index: number };+ const anchor: PreviewAnchor = { index };pendingAnchorRef.current = anchor;if (previewRef.current) {- // Already open: gliding retargets the card instantly — no re-delay.+ // Already open: gliding highlights the matching row without moving the card.showPreview(anchor);} else if (openTimerRef.current === null) {openTimerRef.current = window.setTimeout(() => {@@ -416,7 +381,7 @@ export function ThreadMinimap({scheduleClose();}, [scheduleWave, scheduleClose]);- // Keyboard parity: focusing a tick anchors the card to it immediately —+ // Keyboard parity: focusing a tick opens its outline row immediately —// there is no pointer, so there is no accidental-hover to debounce.const handleFocus = useCallback((e: React.FocusEvent) => {@@ -428,31 +393,49 @@ export function ThreadMinimap({const buttons = [...nav.querySelectorAll<HTMLButtonElement>("button")];const index = buttons.indexOf(btn as HTMLButtonElement);if (index < 0) return;- const r = btn.getBoundingClientRect();- const cardHalf = (cardRef.current?.offsetHeight ?? 96) / 2;- const y = r.top + r.height / 2 - shim.getBoundingClientRect().top;- showPreview({- index,- y: Math.min(Math.max(y, cardHalf + 6), shim.clientHeight - cardHalf - 6),- });+ showPreview({ index });},[cancelClose, showPreview],);- if (threads.length < MIN_THREADS) return null;+ useEffect(() => {+ const card = cardRef.current;+ if (!card || !preview) return;+ // Rail navigation should reveal its row in a long outline. Moving within+ // the list itself must leave its scroll position under the reader's control.+ if (pointerYRef.current === null && !navRef.current?.contains(document.activeElement)) return;+ const row = card.querySelectorAll("li")[preview.index];+ if (!row) return;+ if (row.offsetTop < card.scrollTop) card.scrollTop = row.offsetTop;+ else if (row.offsetTop + row.offsetHeight > card.scrollTop + card.clientHeight) {+ card.scrollTop = row.offsetTop + row.offsetHeight - card.clientHeight;+ }+ }, [preview]);- const activeThread = preview ? threads[preview.index] : undefined;- const activePreview = preview ? previews[preview.index] : undefined;- const activeTitle = activeThread && activePreview- ? activePreview.title ||- activeThread.entry.actor_name ||- getActorName(activeThread.entry.actor_type, activeThread.entry.actor_id)- : undefined;+ if (threads.length < MIN_THREADS) return null;return (// Positioning shim; only the nav and the card take pointer events so the// strip never blocks content clicks.- <div ref={shimRef} className={cn("pointer-events-none z-10 flex flex-col justify-center py-6", className)}>+ <div+ ref={shimRef}+ onKeyDown={(event) => {+ if (event.key !== "Escape") return;+ event.preventDefault();+ event.stopPropagation();+ const activeIndex = previewRef.current?.index;+ if (cardRef.current?.contains(document.activeElement) && activeIndex !== undefined) {+ navRef.current?.querySelectorAll("button")[activeIndex]?.focus();+ }+ cancelClose();+ if (openTimerRef.current !== null) {+ window.clearTimeout(openTimerRef.current);+ openTimerRef.current = null;+ }+ showPreview(null);+ }}+ className={cn("pointer-events-none z-10 flex flex-col justify-center py-6", className)}+ ><navref={navRef}aria-label={t(($) => $.detail.thread_nav_label)}@@ -472,50 +455,95 @@ export function ThreadMinimap({return (<MinimapTickkey={thread.id}- // The card is the visual channel for the resolved state, but a- // screen reader never sees it — the tick's name is the only- // thing announced on focus, so it carries the state too.+ // Announce resolution on the tick as well as in the outline.label={thread.resolved? t(($) => $.detail.thread_nav_resolved_label, { title }): title}inViewport={visibleIds.has(thread.id)}- isPreviewOpen={preview?.index === i}- isHighlighted={highlightedThreadId === thread.id}- onClick={() => onJump(thread.id)}+ isHighlighted={preview?.index === i}+ onClick={(event) => handleJump(thread.id, event)}/>);})}</nav>- {/* The rail's single preview card. Mounted without an enter animation- (the open-intent delay already gates accidental flashes; once the- user waited, showing content instantly is the responsive choice)- and slid between ticks with a short transform transition. Hovering- the card keeps it open so its text stays selectable. It opens- inward (leftward, over the content) — the only direction with room- next to the scrollbar. The resolved badge leads so the state is read- before the content, in the same `text-success` CommentCard uses for- its Resolution badge. */}- {preview && activeThread && activePreview && (+ {preview && (<divref={cardRef}onPointerEnter={cancelClose}onPointerLeave={scheduleClose}- className="pointer-events-auto absolute right-8 top-0 w-72 rounded-lg bg-popover p-2.5 text-body text-popover-foreground shadow-md ring-1 ring-foreground/10 transition-transform duration-150 ease-out motion-reduce:transition-none"- style={{ transform: `translateY(${preview.y}px) translateY(-50%)` }}+ onFocusCapture={cancelClose}+ onBlurCapture={scheduleClose}+ className="pointer-events-auto absolute right-8 top-1/2 max-h-[calc(100%-3rem)] w-80 max-w-[calc(100vw-4rem)] -translate-y-1/2 overflow-y-auto overscroll-contain rounded-xl bg-popover p-2 text-body text-popover-foreground shadow-lg ring-1 ring-foreground/10">- {activeThread.resolved && (- <p className="mb-1 flex items-center gap-1.5 text-caption font-medium text-success">- <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />- {t(($) => $.comment.resolve.thread_resolved_badge)}- </p>- )}- <p className="truncate text-body font-semibold text-foreground">{activeTitle}</p>- {activePreview.body && (- <p className="mt-1 line-clamp-3 text-body text-muted-foreground">{activePreview.body}</p>- )}+ <ul>+ {threads.map((thread, index) => {+ const title = previews[index]!.title || thread.entry.actor_name ||+ getActorName(thread.entry.actor_type, thread.entry.actor_id);+ const participantNames = thread.participants.map((participant) =>+ participant.actor_name || getActorName(participant.actor_type, participant.actor_id),+ );+ return (+ <li key={thread.id}>+ <button+ type="button"+ onPointerEnter={() => showPreview({ index })}+ onFocus={() => showPreview({ index })}+ onClick={(event) => handleJump(thread.id, event)}+ data-active={preview.index === index || undefined}+ aria-label={thread.resolved+ ? t(($) => $.detail.thread_nav_resolved_label, { title })+ : title}+ aria-description={participantNames.join(", ") || undefined}+ className="flex w-full items-start gap-3 rounded-md px-3 py-2 text-left text-body text-muted-foreground transition-colors hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring data-active:font-medium data-active:text-brand"+ >+ <span className="min-w-0 flex-1 break-words">+ {title}+ {thread.resolved && (+ <CheckCircle2+ className="ml-1.5 inline-block size-3.5 align-text-bottom text-success"+ aria-label={t(($) => $.comment.resolve.thread_resolved_badge)}+ />+ )}+ </span>+ <span className="inline-flex shrink-0 items-center -space-x-1.5" aria-hidden="true">+ {thread.participants.slice(0, 3).map((participant, participantIndex) => {+ const name = participantNames[participantIndex]!;+ const avatarUrl = participant.actor_avatar_url?.startsWith("/")+ ? resolvePublicFileUrl(participant.actor_avatar_url)+ : participant.actor_avatar_url ?? getActorAvatarUrl(participant.actor_type, participant.actor_id);+ return (+ <span+ key={`${participant.actor_type}:${participant.actor_id}`}+ title={name}+ className="inline-flex rounded-full ring-2 ring-popover"+ >+ <ActorAvatar+ name={name}+ initials={getActorInitials(participant.actor_type, participant.actor_id, name)}+ avatarUrl={avatarUrl}+ isAgent={participant.actor_type === "agent"}+ size="sm"+ />+ </span>+ );+ })}+ {thread.participants.length > 3 && (+ <span+ title={participantNames.slice(3).join(", ")}+ className="inline-flex h-5 min-w-5 items-center justify-center rounded-full bg-muted px-0.5 text-micro font-medium tabular-nums text-muted-foreground ring-2 ring-popover"+ >+ +{thread.participants.length - 3}+ </span>+ )}+ </span>+ </button>+ </li>+ );+ })}+ </ul></div>)}</div>diff --git a/packages/views/issues/components/thread-nav-panel.test.tsx b/packages/views/issues/components/thread-nav-panel.test.tsxdeleted file mode 100644index 0d08148e5d..0000000000--- a/packages/views/issues/components/thread-nav-panel.test.tsx+++ /dev/null@@ -1,688 +0,0 @@-// @vitest-environment jsdom--import { useState, type ReactElement, type ReactNode } from "react";-import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { TimelineEntry } from "@multica/core/types";-import {- createShortcutChord,- useShortcutStore,-} from "@multica/core/shortcuts";-import { renderWithI18n } from "../../test/i18n";-import {- ThreadNavPanel,- formatStamp,- highlightMatches,- matchesFilter,- mentionsUser,- threadDayGroup,- type ThreadNavThread,-} from "./thread-nav-panel";--type OpenChange = (open: boolean, details: { reason: string }) => void;--const mockState = vi.hoisted(() => ({- open: false,- triggerProps: undefined as Record<string, unknown> | undefined,- onOpenChange: undefined as ((open: boolean, details: { reason: string }) => void) | undefined,-}));--// ActorAvatar resolves workspace-scoped profile paths, which needs a route-// provider this component test has no reason to stand up. The row's identity-// rendering is not what is under test here.-vi.mock("../../common/actor-avatar", () => ({- ActorAvatar: ({ actorId }: { actorId: string }) => (- <span data-testid={`avatar-${actorId}`} />- ),-}));--vi.mock("@multica/core/workspace/hooks", () => ({- useActorName: () => ({- getActorName: (_type: string, id: string) =>- ({ "user-1": "Jiayuan", "agent-1": "Lambda" })[id] ?? "Unknown",- getActorInitials: () => "XX",- getActorAvatarUrl: () => null,- }),-}));--// Base UI owns hover timing and focus trapping; those are its tests, not ours.-// The mock keeps the parts this component actually drives — the controlled-// `open` prop, the reason-carrying `onOpenChange`, and the content's keyboard-// and focus handlers — so the open/pin state machine is what gets exercised.-vi.mock("@multica/ui/components/ui/tooltip", () => ({- Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,- TooltipTrigger: ({ render }: { render: ReactElement }) => render,- TooltipContent: ({ children }: { children: ReactNode }) => (- <div data-testid="tooltip">{children}</div>- ),-}));--vi.mock("@multica/ui/components/ui/popover", async () => {- const React = await vi.importActual<typeof import("react")>("react");- return {- Popover: ({- children,- open,- onOpenChange,- }: {- children: React.ReactNode;- open: boolean;- onOpenChange: OpenChange;- }) => {- mockState.open = open;- mockState.onOpenChange = onOpenChange;- return <div data-testid="popover">{children}</div>;- },- // Base UI's trigger toggles on press and reports the reason; reproduce- // exactly that so the component's own press handling is under test.- PopoverTrigger: ({- render,- children,- ...props- }: {- render: React.ReactElement;- children: React.ReactNode;- } & Record<string, unknown>) => {- mockState.triggerProps = props;- return React.cloneElement(- render as React.ReactElement<Record<string, unknown>>,- {- onClick: () =>- mockState.onOpenChange?.(!mockState.open, { reason: "trigger-press" }),- },- children,- );- },- PopoverContent: ({- children,- onKeyDown,- onFocusCapture,- }: {- children: React.ReactNode;- onKeyDown?: React.KeyboardEventHandler;- onFocusCapture?: React.FocusEventHandler;- }) =>- mockState.open ? (- <div data-testid="panel" onKeyDown={onKeyDown} onFocusCapture={onFocusCapture}>- {children}- </div>- ) : null,- };-});--function comment(- id: string,- content: string,- overrides: Partial<TimelineEntry> = {},-): TimelineEntry {- return {- type: "comment",- id,- actor_type: "member",- actor_id: "user-1",- created_at: new Date().toISOString(),- content,- ...overrides,- };-}--function thread(- id: string,- content: string,- overrides: Partial<ThreadNavThread> = {},-): ThreadNavThread {- return {- id,- entry: comment(id, content),- resolved: false,- replyCount: 0,- involvesMe: false,- ...overrides,- };-}--const THREADS: ThreadNavThread[] = [- thread("t1", "Invite links require a workspace first"),- thread("t2", "Move the required check into the service layer", { replyCount: 3 }),- thread("t3", "Expiry: 7 days or 14 days?", { resolved: true }),- thread("t4", "Mail template CTA collapses in Outlook", { involvesMe: true }),-];--/** Mirrors how issue-detail owns the panel's open/pinned pair. */-function Harness({- threads = THREADS,- onJump = vi.fn(),- onHoverThread = vi.fn(),-}: {- threads?: ThreadNavThread[];- onJump?: (id: string) => void;- onHoverThread?: (id: string | null) => void;-}) {- const [state, setState] = useState({ open: false, pinned: false });- return (- <ThreadNavPanel- threads={threads}- onJump={onJump}- onHoverThread={onHoverThread}- open={state.open}- pinned={state.pinned}- onOpenChange={(open, pinned) => setState({ open, pinned })}- />- );-}--/** Drive the state machine the way Base UI would, with a reason attached. */-function emit(open: boolean, reason: string) {- act(() => {- mockState.onOpenChange?.(open, { reason });- });-}--beforeEach(() => {- mockState.open = false;- mockState.triggerProps = undefined;- mockState.onOpenChange = undefined;-});--afterEach(cleanup);--describe("threadDayGroup", () => {- const now = new Date("2026-08-05T12:00:00").getTime();-- it("buckets by local calendar day", () => {- expect(threadDayGroup(new Date("2026-08-05T00:30:00").toISOString(), now)).toBe("today");- expect(threadDayGroup(new Date("2026-08-04T23:30:00").toISOString(), now)).toBe("yesterday");- expect(threadDayGroup(new Date("2026-08-03T23:30:00").toISOString(), now)).toBe("earlier");- });-- it("treats an unparseable timestamp as earlier rather than throwing", () => {- expect(threadDayGroup("not-a-date", now)).toBe("earlier");- });-});--describe("formatStamp", () => {- // The row's stamp and its group header must agree about what day it is. A- // second "less than 48 hours ago" test disagreed with the calendar-day- // grouping for most of the day, and an "earlier" row could render a bare- // clock time with nothing saying which day it belonged to.- const at = (iso: string) => new Date(iso).toISOString();-- it("shows a clock time under today and yesterday", () => {- expect(formatStamp(at("2026-08-05T14:20:00"), "today", "en")).toMatch(/\d/);- expect(formatStamp(at("2026-08-05T14:20:00"), "today", "en")).not.toMatch(/[A-Za-z]{3}/);- expect(formatStamp(at("2026-08-04T14:20:00"), "yesterday", "en")).not.toMatch(/[A-Za-z]{3}/);- });-- it("always shows a date under earlier, even when it is under 48 hours old", () => {- // The regression: 23:41 the day before yesterday is < 48h but groups as- // "earlier", and used to render as a bare clock time.- expect(formatStamp(at("2026-08-03T23:41:00"), "earlier", "en")).toMatch(/[A-Za-z]{3}|\d+\/\d+|月/);- });-- it("formats earlier entries with the selected UI language", () => {- expect(- formatStamp(at("2026-08-03T23:41:00"), "earlier", "zh-Hans"),- ).toContain("月");- });-- it("returns an empty string for an unparseable timestamp", () => {- expect(formatStamp("not-a-date", "today", "en")).toBe("");- });-});--describe("matchesFilter", () => {- it("splits on resolution and participation", () => {- const open = thread("a", "x");- const done = thread("b", "x", { resolved: true });- const mine = thread("c", "x", { involvesMe: true });-- expect(matchesFilter(open, "all")).toBe(true);- expect(matchesFilter(open, "unresolved")).toBe(true);- expect(matchesFilter(done, "unresolved")).toBe(false);- expect(matchesFilter(done, "resolved")).toBe(true);- expect(matchesFilter(mine, "mine")).toBe(true);- expect(matchesFilter(open, "mine")).toBe(false);- });-- it("keeps every thread for an unknown filter instead of emptying the list", () => {- expect(matchesFilter(thread("a", "x"), "sideways" as never)).toBe(true);- });-});--describe("highlightMatches", () => {- it("returns the text untouched when there is no query", () => {- expect(highlightMatches("Invite links", "")).toBe("Invite links");- expect(highlightMatches("Invite links", " ")).toBe("Invite links");- });-- it("splits on every occurrence, case-insensitively", () => {- const parts = highlightMatches("Workspace and workspace_id", "workspace");- expect(Array.isArray(parts)).toBe(true);- const marks = (parts as ReactNode[]).filter(- (p): p is ReactElement<{ children: string }> =>- typeof p === "object" && p !== null && "type" in p && p.type === "mark",- );- expect(marks).toHaveLength(2);- // Source casing survives — the reader sees their text, not their typing.- expect(marks[0]!.props.children).toBe("Workspace");- expect(marks[1]!.props.children).toBe("workspace");- });-- it("does not drop text before, between, or after matches", () => {- const parts = highlightMatches("ab X cd X ef", "X") as ReactNode[];- const text = parts- .map((p) =>- typeof p === "string"- ? p- : (p as ReactElement<{ children: string }>).props.children,- )- .join("");- expect(text).toBe("ab X cd X ef");- });-});--describe("mentionsUser", () => {- it("matches the markdown mention link form", () => {- expect(mentionsUser("hey [@Jiayuan](mention://member/user-1) look", "user-1")).toBe(true);- });-- it("matches the legacy shortcode form still sitting in the database", () => {- // preprocessMarkdown migrates `[@ id=... label=...]` on READ, not before- // storage, so the timeline hands this straight through.- expect(mentionsUser('hey [@ id="user-1" label="Jiayuan"] look', "user-1")).toBe(true);- expect(mentionsUser('[@ id="user-2" label="Wei"]', "user-1")).toBe(false);- });-- it("does not match another member or an agent mention", () => {- expect(mentionsUser("[@Wei](mention://member/user-2)", "user-1")).toBe(false);- expect(mentionsUser("[@Lambda](mention://agent/user-1)", "user-1")).toBe(false);- });-- it("is false for empty content or a missing user id", () => {- expect(mentionsUser(undefined, "user-1")).toBe(false);- expect(mentionsUser("[@x](mention://member/)", "")).toBe(false);- });-});--describe("ThreadNavPanel", () => {- it("renders nothing when the issue has no threads", () => {- renderWithI18n(<Harness threads={[]} />);- expect(screen.queryByRole("button")).toBeNull();- });-- it("shows the thread count on the trigger", () => {- renderWithI18n(<Harness />);- expect(screen.getByRole("button", { name: /Comment threads \(4\)/ })).toBeTruthy();- });-- // getShortcut() is a getState() snapshot with no subscription, so a rebind in- // Settings left the tooltip advertising the old key while the keydown handler- // already honoured the new one. useShortcut subscribes.- it("re-renders the shortcut hint when the binding changes", () => {- renderWithI18n(<Harness />);- const keys = () =>- [...screen.getByTestId("tooltip").querySelectorAll("kbd")]- .map((k) => k.textContent?.trim())- .join("");- expect(keys()).toContain("O");-- act(() => {- useShortcutStore- .getState()- .setShortcut("openThreadNav", createShortcutChord("G", { primary: true, shift: true }));- });- expect(keys()).toContain("G");- expect(keys()).not.toContain("O");-- act(() => {- useShortcutStore.getState().setShortcut("openThreadNav", null);- });- // Unbound: the label stays, the keycaps go.- expect(screen.getByTestId("tooltip").querySelectorAll("kbd")).toHaveLength(0);-- // The store is a module singleton; leaving an override here would follow- // every later test in this file.- act(() => {- useShortcutStore.getState().resetShortcut("openThreadNav");- });- });-- it("wires the trigger to open on hover, not only on press", () => {- renderWithI18n(<Harness />);- expect(mockState.triggerProps?.openOnHover).toBe(true);- expect(mockState.triggerProps?.delay).toBeGreaterThan(0);- expect(mockState.triggerProps?.closeDelay).toBeGreaterThan(0);- });-- it("lists every thread once open", () => {- renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- expect(screen.getByText("Invite links require a workspace first")).toBeTruthy();- expect(screen.getByText("Expiry: 7 days or 14 days?")).toBeTruthy();- });-- it("focuses search when opened by a press", async () => {- renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- const search = screen.getByPlaceholderText("Search threads or authors");- await waitFor(() => expect(document.activeElement).toBe(search));- });-- // The open model is the part of this design that differs from the original- // "hover shows the list" request, so it carries the most test weight.- describe("hover previews, press pins", () => {- it("does not take focus when opened by hover", async () => {- renderWithI18n(<Harness />);- const before = document.activeElement;- emit(true, "trigger-hover");- expect(screen.getByTestId("panel")).toBeTruthy();- // A hover preview over a half-written comment must leave the caret alone.- await waitFor(() => {- expect(document.activeElement).toBe(before);- });- });-- it("closes again when the pointer leaves an unpinned preview", () => {- renderWithI18n(<Harness />);- emit(true, "trigger-hover");- emit(false, "trigger-hover");- expect(screen.queryByTestId("panel")).toBeNull();- });-- it("pins instead of closing when the trigger is pressed over a preview", async () => {- renderWithI18n(<Harness />);- emit(true, "trigger-hover");- // Base UI reports a press on an open popover as a close request; over an- // unpinned preview that means "keep this", not "dismiss".- emit(false, "trigger-press");- expect(screen.getByTestId("panel")).toBeTruthy();- await waitFor(() =>- expect(document.activeElement).toBe(- screen.getByPlaceholderText("Search threads or authors"),- ),- );- });-- it("survives the pointer leaving once pinned", () => {- renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- emit(false, "trigger-hover");- expect(screen.getByTestId("panel")).toBeTruthy();- });-- it("closes a pinned panel on a second press, escape, or outside press", () => {- const { unmount } = renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- expect(screen.queryByTestId("panel")).toBeNull();- unmount();-- for (const reason of ["escape-key", "outside-press"]) {- renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- emit(false, reason);- expect(screen.queryByTestId("panel")).toBeNull();- cleanup();- }- });-- it("upgrades a preview to pinned when focus lands inside it", async () => {- renderWithI18n(<Harness />);- emit(true, "trigger-hover");- fireEvent.focus(screen.getByTestId("panel"));- // Now pinned: a pointer-out no longer closes it.- emit(false, "trigger-hover");- expect(screen.getByTestId("panel")).toBeTruthy();- await waitFor(() =>- expect(document.activeElement).toBe(- screen.getByPlaceholderText("Search threads or authors"),- ),- );- });- });-- it("filters rows by the search query and reports the match count", () => {- const { container } = renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- fireEvent.change(screen.getByPlaceholderText("Search threads or authors"), {- target: { value: "outlook" },- });- // Assert on the row identity, not its text: highlighting splits the title- // across elements, so a whole-string text query would miss it.- const rows = [...container.querySelectorAll("[data-thread-id]")].map((el) =>- el.getAttribute("data-thread-id"),- );- expect(rows).toEqual(["t4"]);- expect(screen.getByText("1 match")).toBeTruthy();- });-- it("tints the matched term in the title and the excerpt", () => {- const { container } = renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- fireEvent.change(screen.getByPlaceholderText("Search threads or authors"), {- target: { value: "workspace" },- });- const marks = [...container.querySelectorAll("mark")];- expect(marks.length).toBeGreaterThan(0);- // Case-insensitive match keeps the source casing rather than the query's.- expect(marks.every((m) => m.textContent?.toLowerCase() === "workspace")).toBe(true);- });-- it("matches on the author name as well as the content", () => {- renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- fireEvent.change(screen.getByPlaceholderText("Search threads or authors"), {- target: { value: "jiayuan" },- });- expect(screen.getByText("4 matches")).toBeTruthy();- });-- it("narrows to unresolved threads", () => {- renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- fireEvent.click(screen.getByRole("button", { name: /^Unresolved/ }));- expect(screen.queryByText("Expiry: 7 days or 14 days?")).toBeNull();- expect(screen.getByText("Invite links require a workspace first")).toBeTruthy();- });-- it("narrows to threads the reader is involved in", () => {- renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- fireEvent.click(screen.getByRole("button", { name: /^@me/ }));- expect(screen.getByText("Mail template CTA collapses in Outlook")).toBeTruthy();- expect(screen.queryByText("Invite links require a workspace first")).toBeNull();- });-- it("shows an empty state rather than a blank list when nothing matches", () => {- renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- fireEvent.change(screen.getByPlaceholderText("Search threads or authors"), {- target: { value: "zzzz" },- });- expect(screen.getByText("No threads match")).toBeTruthy();- });-- it("jumps to the clicked thread and closes", () => {- const onJump = vi.fn();- renderWithI18n(<Harness onJump={onJump} />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- fireEvent.click(screen.getByText("Expiry: 7 days or 14 days?"));- expect(onJump).toHaveBeenCalledWith("t3");- expect(screen.queryByTestId("panel")).toBeNull();- });-- it("moves the cursor with arrow keys and jumps on Enter", () => {- const onJump = vi.fn();- renderWithI18n(<Harness onJump={onJump} />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- const search = screen.getByPlaceholderText("Search threads or authors");- fireEvent.keyDown(search, { key: "ArrowDown" });- fireEvent.keyDown(search, { key: "Enter" });- expect(onJump).toHaveBeenCalledWith("t2");- });-- // Same chords cmdk's vimBindings give the command palette, so the muscle- // memory carries across every list-with-a-highlight in the product.- it.each([- ["n", "t2"],- ["j", "t2"],- ["p", "t4"],- ["k", "t4"],- ])("moves the cursor on Ctrl+%s", (key, expected) => {- const onJump = vi.fn();- renderWithI18n(<Harness onJump={onJump} />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- const search = screen.getByPlaceholderText("Search threads or authors");- fireEvent.keyDown(search, { key, ctrlKey: true });- fireEvent.keyDown(search, { key: "Enter" });- expect(onJump).toHaveBeenCalledWith(expected);- });-- it("leaves the letters alone without Ctrl, so they can be typed into search", () => {- const onJump = vi.fn();- renderWithI18n(<Harness onJump={onJump} />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- const search = screen.getByPlaceholderText("Search threads or authors");- fireEvent.keyDown(search, { key: "n" });- fireEvent.keyDown(search, { key: "Enter" });- expect(onJump).toHaveBeenCalledWith("t1");- });-- it("ignores the aliases when another modifier is held", () => {- const onJump = vi.fn();- renderWithI18n(<Harness onJump={onJump} />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- const search = screen.getByPlaceholderText("Search threads or authors");- // Ctrl+Shift+N is the browser's incognito window, not our navigation.- fireEvent.keyDown(search, { key: "n", ctrlKey: true, shiftKey: true });- fireEvent.keyDown(search, { key: "Enter" });- expect(onJump).toHaveBeenCalledWith("t1");- });-- it("wraps the cursor at the top of the list", () => {- const onJump = vi.fn();- renderWithI18n(<Harness onJump={onJump} />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- const search = screen.getByPlaceholderText("Search threads or authors");- fireEvent.keyDown(search, { key: "ArrowUp" });- fireEvent.keyDown(search, { key: "Enter" });- expect(onJump).toHaveBeenCalledWith("t4");- });-- // The panel used to mark every thread inside the scroll viewport as "you are- // here". A tall viewport holds several at once, so the marker landed on two or- // three rows and read as a broken multi-select; absolute position is the- // rail's job now. Guard against it coming back.- it("marks no row as a current position", () => {- const { container } = renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- expect(screen.queryByText(/you are here/i)).toBeNull();- expect(container.querySelector(".bg-brand")).toBeNull();- });-- // Enter used to be handled for every keydown bubbling up to the popup, and- // preventDefault on a button's keydown cancels the click the browser is about- // to synthesize — so Enter on a filter pill jumped away instead of filtering.- it("lets Enter activate a focused filter pill instead of jumping", () => {- const onJump = vi.fn();- const { container } = renderWithI18n(<Harness onJump={onJump} />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- const resolved = screen.getByRole("button", { name: /^Resolved/ });- resolved.focus();- fireEvent.keyDown(resolved, { key: "Enter" });- // A real browser turns that keydown into a click on the focused button.- fireEvent.click(resolved);- expect(onJump).not.toHaveBeenCalled();- const rows = [...container.querySelectorAll("[data-thread-id]")].map((el) =>- el.getAttribute("data-thread-id"),- );- expect(rows).toEqual(["t3"]);- });-- // One cursor, structurally: rows cannot take DOM focus, so focus and the- // highlight cannot drift apart. Tab reaches the filter pills and then leaves.- it("keeps rows out of the tab order and points at the active one", () => {- const { container } = renderWithI18n(<Harness />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- const rows = [...container.querySelectorAll("[data-thread-id]")];- expect(rows.length).toBeGreaterThan(0);- expect(rows.every((r) => r.getAttribute("tabindex") === "-1")).toBe(true);- expect(rows.every((r) => r.getAttribute("role") === "option")).toBe(true);-- const search = screen.getByPlaceholderText("Search threads or authors");- expect(search.getAttribute("aria-activedescendant")).toBe(rows[0]!.id);- expect(rows[0]!.getAttribute("aria-selected")).toBe("true");-- fireEvent.keyDown(search, { key: "ArrowDown" });- expect(search.getAttribute("aria-activedescendant")).toBe(rows[1]!.id);- expect(rows[1]!.getAttribute("aria-selected")).toBe("true");- expect(rows[0]!.getAttribute("aria-selected")).toBe("false");- });-- // The reviewer's repro: with focus on a child control, an arrow key must not- // move a highlight that Enter will then ignore.- it("does not move the highlight from a focused filter pill", () => {- const onJump = vi.fn();- const { container } = renderWithI18n(<Harness onJump={onJump} />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- const search = screen.getByPlaceholderText("Search threads or authors");- const pill = screen.getByRole("button", { name: /^Unresolved/ });- pill.focus();-- fireEvent.keyDown(pill, { key: "ArrowDown" });- fireEvent.keyDown(pill, { key: "n", ctrlKey: true });- // Highlight untouched — the search field owns it.- const rows = [...container.querySelectorAll("[data-thread-id]")];- expect(search.getAttribute("aria-activedescendant")).toBe(rows[0]!.id);-- // And Enter still activates the pill rather than jumping.- fireEvent.keyDown(pill, { key: "Enter" });- fireEvent.click(pill);- expect(onJump).not.toHaveBeenCalled();- });-- // CJK users commit an IME candidate with Enter. Acting on it jumped away and- // closed the panel mid-word, which makes the search field unusable for them.- it("ignores keys while an IME is composing", () => {- const onJump = vi.fn();- renderWithI18n(<Harness onJump={onJump} />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- const search = screen.getByPlaceholderText("Search threads or authors");-- fireEvent.keyDown(search, { key: "ArrowDown", isComposing: true });- fireEvent.keyDown(search, { key: "Enter", isComposing: true });- expect(onJump).not.toHaveBeenCalled();-- // Some IMEs report the commit as keyCode 229 rather than isComposing.- fireEvent.keyDown(search, { key: "Enter", keyCode: 229 });- expect(onJump).not.toHaveBeenCalled();-- // Composition over: Enter works again, and the cursor never moved.- fireEvent.keyDown(search, { key: "Enter" });- expect(onJump).toHaveBeenCalledWith("t1");- });-- it("reports the hovered row so the rail can light the matching tick", () => {- const onHoverThread = vi.fn();- renderWithI18n(<Harness onHoverThread={onHoverThread} />);- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));- const row = screen.getByText("Expiry: 7 days or 14 days?").closest("button")!;- fireEvent.pointerEnter(row);- expect(onHoverThread).toHaveBeenCalledWith("t3");- fireEvent.pointerLeave(row);- expect(onHoverThread).toHaveBeenCalledWith(null);- });-- it("resets the query and filter between openings", () => {- renderWithI18n(<Harness />);- const trigger = screen.getByRole("button", { name: /Comment threads/ });- fireEvent.click(trigger);- fireEvent.change(screen.getByPlaceholderText("Search threads or authors"), {- target: { value: "outlook" },- });- expect(screen.queryByText("Invite links require a workspace first")).toBeNull();- fireEvent.click(trigger);- fireEvent.click(trigger);- expect(screen.getByText("Invite links require a workspace first")).toBeTruthy();- });-});diff --git a/packages/views/issues/components/thread-nav-panel.tsx b/packages/views/issues/components/thread-nav-panel.tsxdeleted file mode 100644index d0cf478a44..0000000000--- a/packages/views/issues/components/thread-nav-panel.tsx+++ /dev/null@@ -1,709 +0,0 @@-"use client";--import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";-import { CheckCircle2, MessageSquare, MessagesSquare, Search } from "lucide-react";-import type { TimelineEntry } from "@multica/core/types";-import { useActorName } from "@multica/core/workspace/hooks";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@multica/ui/components/ui/popover";-import { Button } from "@multica/ui/components/ui/button";-import { cn } from "@multica/ui/lib/utils";-import { createShortcutChord, useShortcut } from "@multica/core/shortcuts";-import { preprocessMentionShortcodes } from "@multica/core/markdown";-import { isImeComposing } from "@multica/core/utils";-import {- Tooltip,- TooltipContent,- TooltipTrigger,-} from "@multica/ui/components/ui/tooltip";-import { ActorAvatar } from "../../common/actor-avatar";-import { pickerNavigationDirection } from "../../common/picker-keys";-import { ShortcutKeycaps } from "../../common/shortcut-keycaps";-import { useLocale, useT } from "../../i18n";-import { commentPreview } from "./thread-minimap";--// ----------------------------------------------------------------------------// ThreadNavPanel — header entry point for jumping between comment threads-// ----------------------------------------------------------------------------//-// The right-edge rail (ThreadMinimap) is a good position indicator and a bad-// finder: a tick carries no text, so locating a specific thread costs one-// hover per candidate, and once threads outgrow the rail's height the ticks-// compress to their 5px floor and stop being countable at all. A list fixes-// the cost model — 8-10 titles readable in one glance instead of one at a-// time — and search/filter make 24 threads and 240 threads cost the same-// (MUL-5755).-//-// The panel deliberately does NOT mark which threads are currently on screen.-// "On screen" is a set, not a point — a tall viewport holds several threads at-// once, so the marker landed on two or three rows simultaneously and read as a-// broken multi-select rather than as a position. Absolute position is the-// rail's job, where a column of ticks can show a span honestly; the panel's job-// is finding. Hovering a row still lights that thread's tick on the rail, which-// links the two without duplicating the rail's answer.-//-// Open model — hover previews, press pins:-//-// hover 200ms -> open, unpinned. Pointer-out closes it. No focus is moved,-// so a half-typed comment never loses the caret.-// press -> pinned. Search takes focus, arrow keys drive the list, and-// only Escape / outside press / a second press closes it.-// focus or scroll inside the panel -> pinned.-//-// Pure hover would have been the wrong trigger for a surface you must be able-// to scroll, type into, and arrow through: all three need the pointer free to-// leave the button. Pinning on *intent* (press, focus, scroll) rather than on-// mere pointer-entry keeps a pass-through glide from leaving the panel stuck-// open.--/** Below this the header button is noise — an issue with no discussion. */-const MIN_THREADS = 1;--/** Hover intent delay before the preview opens. */-const HOVER_OPEN_DELAY_MS = 200;-/** Grace period on leave — long enough to travel from the button into the panel. */-const HOVER_CLOSE_DELAY_MS = 200;--const DAY_MS = 24 * 60 * 60 * 1000;--// Footer hint keys. Built as real chords so ShortcutKeycaps renders each one-// with the platform's own glyph and keycap chrome.-const KEY_UP = createShortcutChord("Up");-const KEY_DOWN = createShortcutChord("Down");-const KEY_ENTER = createShortcutChord("Enter");-const KEY_ESCAPE = createShortcutChord("Escape");--export type ThreadNavFilter = "all" | "unresolved" | "resolved" | "mine";--export interface ThreadNavThread {- /** Root comment id — also the `comment-${id}` DOM anchor of the rendered row. */- id: string;- /** The thread's root comment entry (preview text, author, timestamp). */- entry: TimelineEntry;- /** Derived by the caller with `deriveThreadResolution` — covers reply resolutions too. */- resolved: boolean;- /** Replies under the root, excluding the root itself. */- replyCount: number;- /** The current user authored, replied to, or was @mentioned in this thread. */- involvesMe: boolean;-}--export type ThreadDayGroup = "today" | "yesterday" | "earlier";--/**- * Bucket a thread by the calendar day of its root comment, in the reader's- * local time zone. Only three buckets: past "yesterday" a per-day header- * would produce more headers than rows on a long-running issue, which is- * noise rather than structure — the timestamp on each row already carries- * the exact date once the reader is in "earlier".- */-export function threadDayGroup(createdAt: string, nowMs: number): ThreadDayGroup {- const ts = Date.parse(createdAt);- if (Number.isNaN(ts)) return "earlier";- const startOfToday = new Date(nowMs).setHours(0, 0, 0, 0);- if (ts >= startOfToday) return "today";- if (ts >= startOfToday - DAY_MS) return "yesterday";- return "earlier";-}--/** A thread plus everything the row and the filters need, computed once. */-interface PreparedThread {- thread: ThreadNavThread;- title: string;- excerpt: string;- authorName: string;- group: ThreadDayGroup;- /** Lowercased `title + excerpt + author`, the haystack the query runs against. */- haystack: string;-}--export function matchesFilter(thread: ThreadNavThread, filter: ThreadNavFilter): boolean {- switch (filter) {- case "unresolved":- return !thread.resolved;- case "resolved":- return thread.resolved;- case "mine":- return thread.involvesMe;- case "all":- return true;- default:- // Server-driven values never reach this union, but an exhaustive- // default keeps a future filter from silently hiding every thread.- return true;- }-}--/**- * Whether `content` @mentions `userId`.- *- * Current mentions serialize as markdown links to `mention://member/<uuid>`,- * but the legacy `[@ id="..." label="..."]` shortcode form is still sitting in- * the database — `preprocessMarkdown` migrates it *on read*, not before- * storage, and the timeline hands us raw content. Matching only the link form- * silently dropped every thread whose sole mention of the reader was written in- * the old format. `preprocessMentionShortcodes` returns its input untouched- * when there is no `[@ ` in it, so the normal path costs one substring scan.- */-export function mentionsUser(content: string | undefined, userId: string): boolean {- if (!content || !userId) return false;- return preprocessMentionShortcodes(content).includes(`mention://member/${userId}`);-}--/**- * Split `text` on every case-insensitive occurrence of `query`, tinting the- * matches. Without this a filtered list asks the reader to re-find the term- * they just typed — the row that matched on its excerpt looks identical to the- * one that matched on its title. Uses the same `--find-match` tint as the- * in-page find bar so "this is your search term" reads the same everywhere.- */-export function highlightMatches(text: string, query: string): ReactNode {- const needle = query.trim();- if (needle === "") return text;- const lowerText = text.toLowerCase();- const lowerNeedle = needle.toLowerCase();- const out: ReactNode[] = [];- let from = 0;- let at = lowerText.indexOf(lowerNeedle);- while (at !== -1) {- if (at > from) out.push(text.slice(from, at));- out.push(- <mark- key={at}- className="rounded-[3px] bg-[var(--find-match)] px-px text-[var(--find-match-foreground)]"- >- {text.slice(at, at + needle.length)}- </mark>,- );- from = at + needle.length;- at = lowerText.indexOf(lowerNeedle, from);- }- if (from < text.length) out.push(text.slice(from));- return out;-}--function ThreadRow({- prepared,- isActive,- optionId,- query,- onJump,- onHover,-}: {- prepared: PreparedThread;- /** Keyboard cursor is on this row. */- isActive: boolean;- /** Stable DOM id so the search field can point at this row. */- optionId: string;- /** Active search term, tinted inside the title and excerpt. */- query: string;- onJump: () => void;- onHover: (threadId: string | null) => void;-}) {- const { t } = useT("issues");- const locale = useLocale();- const { thread, title, excerpt, authorName } = prepared;- return (- <button- type="button"- // Not a tab stop, and role=option: the search field keeps DOM focus and- // names this row through aria-activedescendant. Leaving the rows- // focusable produced two cursors — Tab to row 3, ArrowDown highlights- // row 2, Enter clicks row 3 — because DOM focus and the highlight were- // separate pieces of state with nothing keeping them in step.- tabIndex={-1}- role="option"- id={optionId}- aria-selected={isActive}- data-thread-id={thread.id}- data-active={isActive || undefined}- onClick={onJump}- onPointerEnter={() => onHover(thread.id)}- onPointerLeave={() => onHover(null)}- className={cn(- "relative flex w-full items-start gap-2.5 rounded-md px-2 py-2 text-left outline-none transition-colors",- "hover:bg-surface-hover data-active:bg-surface-hover",- )}- >- <ActorAvatar- actorType={thread.entry.actor_type}- actorId={thread.entry.actor_id}- name={thread.entry.actor_name}- avatarUrl={thread.entry.actor_avatar_url}- size="sm"- profileLink={false}- className="mt-0.5 shrink-0"- />- <span className="flex min-w-0 flex-1 flex-col">- <span className="flex items-baseline gap-1.5">- <span- className={cn(- "min-w-0 flex-1 truncate text-body",- thread.resolved ? "text-muted-foreground" : "font-medium text-foreground",- )}- >- {highlightMatches(title, query)}- </span>- <span className="shrink-0 text-micro tabular-nums text-faint-foreground">- {formatStamp(prepared.thread.entry.created_at, prepared.group, locale)}- </span>- </span>- <span className="mt-1 flex min-w-0 items-center gap-1.5 text-caption text-muted-foreground">- <span className="shrink-0">{authorName}</span>- {thread.replyCount > 0 && (- <span className="flex shrink-0 items-center gap-0.5 tabular-nums text-faint-foreground">- <MessageSquare className="h-3 w-3" />- {thread.replyCount}- </span>- )}- {thread.resolved && (- <span className="flex shrink-0 items-center gap-0.5 text-success">- <CheckCircle2 className="h-3 w-3" />- {t(($) => $.comment.resolve.thread_resolved_badge)}- </span>- )}- {excerpt && (- <span className="min-w-0 truncate text-faint-foreground">- {highlightMatches(excerpt, query)}- </span>- )}- </span>- </span>- </button>- );-}--/**- * Wall-clock under a today/yesterday header, calendar date under "earlier" —- * the header already names the day in the first two cases, so repeating it per- * row would be redundant where it is known and missing where it is not.- *- * Driven by the row's own group rather than a second "less than 48 hours ago"- * test. Those two boundaries disagree for most of the day: an entry from- * 23:41 the day before yesterday is under 48 hours old but groups under- * "earlier", and it rendered as a bare `11:41 PM` with nothing saying which- * day. One boundary, decided once, cannot drift from itself.- */-export function formatStamp(createdAt: string, group: ThreadDayGroup, locale: string): string {- const ts = Date.parse(createdAt);- if (Number.isNaN(ts)) return "";- const d = new Date(ts);- return group === "earlier"- ? d.toLocaleDateString(locale, { month: "short", day: "numeric" })- : d.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit" });-}--interface ThreadNavPanelProps {- threads: ThreadNavThread[];- onJump: (threadId: string) => void;- /** Lights the matching tick on the right-edge rail. */- onHoverThread: (threadId: string | null) => void;- /** Controlled open state, so the global shortcut can pin the panel open. */- open: boolean;- onOpenChange: (open: boolean, pinned: boolean) => void;- /** True when `open` was reached by a press / shortcut rather than by hover. */- pinned: boolean;-}--export function ThreadNavPanel({- threads,- onJump,- onHoverThread,- open,- onOpenChange,- pinned,-}: ThreadNavPanelProps) {- const { t } = useT("issues");- const { getActorName } = useActorName();- // Subscribed, not snapshotted: `getShortcut` reads the store once with no- // subscription, so a rebind in Settings left this tooltip showing the old- // key while the actual keydown handler already used the new one.- const openShortcutChord = useShortcut("openThreadNav");- const listId = useId();- const optionId = useCallback((threadId: string) => `${listId}-${threadId}`, [listId]);-- const [tooltipOpen, setTooltipOpen] = useState(false);- const [query, setQuery] = useState("");- const [filter, setFilter] = useState<ThreadNavFilter>("all");- const [activeIndex, setActiveIndex] = useState(0);- const searchRef = useRef<HTMLInputElement | null>(null);- const listRef = useRef<HTMLDivElement | null>(null);-- // Previews are cached by content so an unrelated timeline update (a reaction,- // a reply in another thread) doesn't re-flatten every root comment.- const previewCacheRef = useRef(- new Map<string, { content: string | undefined; preview: { title: string; body: string } }>(),- );- const prepared = useMemo<PreparedThread[]>(() => {- const nowMs = Date.now();- const nextCache = new Map<- string,- { content: string | undefined; preview: { title: string; body: string } }- >();- const rows = threads.map((thread) => {- const cached = previewCacheRef.current.get(thread.id);- const preview =- cached && cached.content === thread.entry.content- ? cached.preview- : commentPreview(thread.entry.content ?? "");- nextCache.set(thread.id, { content: thread.entry.content, preview });- const authorName =- thread.entry.actor_name ||- getActorName(thread.entry.actor_type, thread.entry.actor_id);- const title = preview.title || authorName;- return {- thread,- title,- excerpt: preview.body,- authorName,- group: threadDayGroup(thread.entry.created_at, nowMs),- haystack: `${title}\n${preview.body}\n${authorName}`.toLowerCase(),- };- });- previewCacheRef.current = nextCache;- return rows;- }, [threads, getActorName]);-- const rows = useMemo(() => {- const needle = query.trim().toLowerCase();- return prepared.filter(- (row) =>- matchesFilter(row.thread, filter) &&- (needle === "" || row.haystack.includes(needle)),- );- }, [prepared, filter, query]);-- const counts = useMemo(- () => ({- all: threads.length,- unresolved: threads.filter((th) => !th.resolved).length,- resolved: threads.filter((th) => th.resolved).length,- mine: threads.filter((th) => th.involvesMe).length,- }),- [threads],- );-- // Each opening starts clean: no carried-over query, filter, or cursor.- const openRef = useRef(open);- useEffect(() => {- if (open && !openRef.current) {- setQuery("");- setFilter("all");- setActiveIndex(0);- }- openRef.current = open;- }, [open]);-- // Filtering shrinks the list under the cursor; clamp instead of leaving it- // pointing past the end, where ↵ would do nothing.- useEffect(() => {- setActiveIndex((prev) => (prev >= rows.length ? Math.max(0, rows.length - 1) : prev));- }, [rows.length]);-- // Keep the keyboard cursor in view — it can be driven far past the visible- // slice by held arrow keys.- useEffect(() => {- if (!open) return;- const row = rows[activeIndex];- if (!row) return;- listRef.current- ?.querySelector<HTMLElement>(`[data-thread-id="${CSS.escape(row.thread.id)}"]`)- ?.scrollIntoView({ block: "nearest" });- }, [activeIndex, open, rows]);-- const pin = useCallback(() => onOpenChange(true, true), [onOpenChange]);-- // Focus follows `pinned`, not the press handler, so the global shortcut —- // which sets the pinned state directly — lands the caret in search too.- // Deferred a frame because Base UI runs its own focus pass on open and would- // otherwise take the caret back.- useEffect(() => {- if (!open || !pinned) return;- const raf = requestAnimationFrame(() => searchRef.current?.focus());- return () => cancelAnimationFrame(raf);- }, [open, pinned]);-- const close = useCallback(() => {- onHoverThread(null);- onOpenChange(false, false);- }, [onHoverThread, onOpenChange]);-- const jump = useCallback(- (threadId: string) => {- onHoverThread(null);- onJump(threadId);- onOpenChange(false, false);- },- [onHoverThread, onJump, onOpenChange],- );-- const handleOpenChange = useCallback(- (next: boolean, details: { reason?: string }) => {- const reason = details?.reason;- if (next) {- if (reason === "trigger-press") pin();- else onOpenChange(true, false);- return;- }- // Pressing the trigger of a hover-preview means "keep this, I want to- // work in it" — not "close". Only a press on an already-pinned panel- // closes it.- if (reason === "trigger-press" && !pinned) {- pin();- return;- }- // A pinned panel outlives the pointer: the user has to be able to reach- // the scrollbar and the rows without the panel evaporating behind them.- if (pinned && reason === "trigger-hover") return;- close();- },- [close, pin, pinned, onOpenChange],- );-- const handleKeyDown = useCallback(- (e: React.KeyboardEvent) => {- // An IME commit arrives as Enter (and the aliases as plain letters) while- // composing. Acting on those would jump away mid-word and close the panel- // the moment a CJK user picked a candidate — the search field is the one- // place in this panel people type prose.- if (isImeComposing(e)) return;- // The search field owns the list keyboard, arrows included. Letting the- // arrows fire from anywhere in the popup while Enter fired only from the- // search field was the worst of both: focus on a filter pill, ArrowDown- // moved the highlight, and Enter then activated the pill — two cursors,- // disagreeing.- if (e.target !== searchRef.current) return;- // Arrow keys plus the Ctrl+N/J and Ctrl+P/K aliases, from the same policy- // the editor's pickers use — which in turn mirrors what cmdk's- // `vimBindings` gives the command bar for free. One list-with-a-highlight- // should not navigate differently from the next.- const direction = pickerNavigationDirection(e.nativeEvent);- if (direction) {- // preventDefault matters for the letter aliases specifically: focus is- // in the search field, where Ctrl+K/N/P are readline editing commands- // that would otherwise mangle the query while moving the cursor.- e.preventDefault();- if (rows.length === 0) return;- const step = direction === "next" ? 1 : -1;- setActiveIndex((prev) => (prev + step + rows.length) % rows.length);- return;- }- // Enter is gated by the same target check above, which is what keeps the- // filter pills activatable: `preventDefault` on a button's keydown- // cancels the click the browser was about to synthesize, so handling- // Enter for the whole popup made "Resolved" jump instead of filter.- if (e.key === "Enter") {- const row = rows[activeIndex];- if (!row) return;- e.preventDefault();- jump(row.thread.id);- }- // Escape is Base UI's job — it already routes through onOpenChange and- // restores focus to the trigger.- //- // Tab is deliberately NOT an accept key here, unlike the editor pickers:- // this is a popover, and Tab has to stay focus navigation so the filter- // pills remain keyboard-reachable.- },- [activeIndex, jump, rows],- );-- if (threads.length < MIN_THREADS) return null;-- const buttonLabel = t(($) => $.detail.thread_nav.button_label, { count: threads.length });- const openShortcut = openShortcutChord;-- const filterPills: { id: ThreadNavFilter; label: string; count: number }[] = [- { id: "all", label: t(($) => $.detail.thread_nav.filter_all), count: counts.all },- { id: "unresolved", label: t(($) => $.detail.thread_nav.filter_unresolved), count: counts.unresolved },- { id: "resolved", label: t(($) => $.detail.thread_nav.filter_resolved), count: counts.resolved },- { id: "mine", label: t(($) => $.detail.thread_nav.filter_mine), count: counts.mine },- ];-- return (- <Popover open={open} onOpenChange={handleOpenChange}>- {/* Base UI puts the hover config on the Trigger, not the Root (a popover- may have several triggers). The trigger stays a real button so press- and keyboard still work for touch and a11y. */}- {/* Tooltip like every other control in this header, and the only place- the open shortcut is discoverable — same label + keycaps shape the- chat launcher uses. Held controlled for its whole life (never- `undefined`, which would flip it uncontrolled mid-flight) and forced- shut while the panel is open, so the tip never sits on top of it. */}- <Tooltip open={tooltipOpen && !open} onOpenChange={setTooltipOpen}>- <TooltipTrigger- render={- <PopoverTrigger- openOnHover- delay={HOVER_OPEN_DELAY_MS}- closeDelay={HOVER_CLOSE_DELAY_MS}- render={- <Button- variant={open ? "secondary" : "ghost"}- size="sm"- aria-label={buttonLabel}- className={cn("h-7 gap-1.5 px-2", !open && "text-muted-foreground")}- />- }- >- {/* Explicit `size-4` so the icon matches the neighbouring header- action buttons instead of the `sm` button's smaller default. */}- <MessagesSquare className="size-4" />- <span className="text-caption font-medium tabular-nums">{threads.length}</span>- </PopoverTrigger>- }- />- <TooltipContent side="bottom">- {buttonLabel}- {openShortcut ? (- <ShortcutKeycaps shortcut={openShortcut} decorative className="ml-1.5" />- ) : null}- </TooltipContent>- </Tooltip>- <PopoverContent- align="end"- // Step inside the right-edge rail's 32px strip so the two navigators- // stay readable together: the rail keeps showing absolute position- // while the panel does the finding. On the alignment axis a positive- // offset moves the popup toward the edge opposite the aligned one, so- // with `align="end"` this shifts left, away from the rail.- alignOffset={24}- // Hover previews must never steal the caret from a half-written- // comment; `pin()` focuses the search field explicitly instead.- initialFocus={false}- onKeyDown={handleKeyDown}- // Any deliberate interaction inside the panel upgrades a preview to- // pinned. Pointer-entry alone deliberately does not: a glide across- // the panel on the way somewhere else should not leave it stuck open.- onFocusCapture={pinned ? undefined : pin}- // Every band insets its content to the same 14px: the search icon and- // the footer sit at px-3.5, while the pill row and the list reach it as- // container padding + item padding (6 + 8). At 10 / 18 / 12 the three- // bands were close enough to read as a mistake and far enough apart to- // see, which is what made the panel feel unsettled rather than dense.- // 400px rather than 380 so the wider inset costs no excerpt width.- className="flex w-[400px] flex-col gap-0 p-0"- >- {/* Search and filters are one header block, so the rule that used to- sit between them is gone: at three dividers a 380px popover read as- stacked bands rather than as one surface, and the filter row was the- thinnest band of the three. */}- <div className="flex h-11 shrink-0 items-center gap-2.5 px-3.5">- <Search className="size-4 shrink-0 text-faint-foreground" />- <input- ref={searchRef}- role="combobox"- aria-expanded- aria-controls={listId}- aria-activedescendant={rows[activeIndex] ? optionId(rows[activeIndex]!.thread.id) : undefined}- value={query}- onChange={(e) => {- setQuery(e.target.value);- setActiveIndex(0);- }}- placeholder={t(($) => $.detail.thread_nav.search_placeholder)}- aria-label={t(($) => $.detail.thread_nav.search_placeholder)}- className="min-w-0 flex-1 bg-transparent text-body text-foreground outline-none placeholder:text-faint-foreground"- />- {query.trim() !== "" && (- <span className="shrink-0 text-caption tabular-nums text-faint-foreground">- {t(($) => $.detail.thread_nav.match_count, { count: rows.length })}- </span>- )}- </div>-- {/* This divider stays: it is the top edge of a scroll region, and- without it the list slides under the pills with nothing marking the- boundary. */}- <div className="flex shrink-0 items-center gap-1 border-b border-border px-1.5 py-2">- {filterPills.map((pill) => (- <button- key={pill.id}- type="button"- onClick={() => {- setFilter(pill.id);- setActiveIndex(0);- }}- data-active={filter === pill.id || undefined}- className={cn(- "flex h-7 items-center gap-1 rounded-full px-2 text-caption text-muted-foreground transition-colors",- "hover:bg-surface-hover",- "data-active:bg-surface-selected data-active:font-medium data-active:text-foreground data-active:hover:bg-surface-selected",- )}- >- {pill.label}- <span className="tabular-nums text-faint-foreground">{pill.count}</span>- </button>- ))}- </div>-- <div- ref={listRef}- id={listId}- role="listbox"- aria-label={t(($) => $.detail.thread_nav.search_placeholder)}- // Scrolling is an intent signal: the reader is working the list, so- // the panel should survive the pointer leaving afterwards.- onScroll={pinned ? undefined : pin}- className="max-h-[26rem] min-h-0 flex-1 overflow-y-auto p-1.5"- >- {rows.length === 0 ? (- <p className="px-2 py-8 text-center text-caption text-muted-foreground">- {t(($) => $.detail.thread_nav.empty)}- </p>- ) : (- rows.map((row, i) => {- const prev = rows[i - 1];- const showHeader = !prev || prev.group !== row.group;- return (- <div key={row.thread.id}>- {/* Asymmetric on purpose — a day label belongs to the group- under it, so it sits closer to its own first row than to- the previous group's last one. */}- {showHeader && (- <p className="px-2 pb-1 pt-3 text-micro font-medium text-faint-foreground">- {t(($) => $.detail.thread_nav.group[row.group])}- </p>- )}- <ThreadRow- prepared={row}- isActive={i === activeIndex}- optionId={optionId(row.thread.id)}- query={query}- onJump={() => jump(row.thread.id)}- onHover={onHoverThread}- />- </div>- );- })- )}- </div>-- {/* Keycaps come from the shared ShortcutKeycaps, so these read as the- same keys the sidebar, command palette, and confirm dialogs draw —- real keycap chrome and the platform's own glyphs, not arrows typed- into a translation string. */}- <div className="flex h-9 shrink-0 items-center gap-4 border-t border-border px-3.5 text-micro text-muted-foreground">- <span className="flex items-center gap-1.5">- <span className="flex items-center gap-0.5">- <ShortcutKeycaps shortcut={KEY_UP} />- <ShortcutKeycaps shortcut={KEY_DOWN} />- </span>- {t(($) => $.detail.thread_nav.hint_select)}- </span>- <span className="flex items-center gap-1.5">- <ShortcutKeycaps shortcut={KEY_ENTER} />- {t(($) => $.detail.thread_nav.hint_jump)}- </span>- <span className="flex items-center gap-1.5">- <ShortcutKeycaps shortcut={KEY_ESCAPE} />- {t(($) => $.detail.thread_nav.hint_close)}- </span>- </div>- </PopoverContent>- </Popover>- );-}diff --git a/packages/views/issues/components/thread-utils.test.ts b/packages/views/issues/components/thread-utils.test.tsindex 6e86314bca..cb79f765d5 100644--- a/packages/views/issues/components/thread-utils.test.ts+++ b/packages/views/issues/components/thread-utils.test.ts@@ -2,6 +2,7 @@import { describe, expect, it } from "vitest";import type { TimelineEntry } from "@multica/core/types";import {+ collectThreadParticipants,collectThreadReplies,resolvedThreadRootIds,rootCommentIds,@@ -128,3 +129,19 @@ describe("resolvedThreadRootIds", () => {expect(resolvedThreadRootIds([root, reply, nested])).toEqual(["root"]);});});++describe("collectThreadParticipants", () => {+ it("includes nested member and agent authors once, preserving identity and first-seen order", () => {+ const root = {+ ...comment("root", "2026-06-11T09:00:00Z", null),+ actor_name: "Alice",+ actor_avatar_url: "https://example.com/alice.png",+ };+ const repeat = comment("repeat", "2026-06-11T10:00:00Z", "root");+ const agent = { ...comment("agent", "2026-06-11T10:01:00Z", "repeat"), actor_type: "agent" };+ const member = { ...comment("member", "2026-06-11T10:02:00Z", "agent"), actor_id: "user-2" };+ const system = { ...comment("system", "2026-06-11T10:03:00Z", "root"), actor_type: "system" };+ const replies = collectThreadReplies("root", bucketByParent([repeat, agent, member, system]));+ expect(collectThreadParticipants(root, replies)).toEqual([root, agent, member]);+ });+});diff --git a/packages/views/issues/components/thread-utils.ts b/packages/views/issues/components/thread-utils.tsindex e711831f7a..a45a303264 100644--- a/packages/views/issues/components/thread-utils.ts+++ b/packages/views/issues/components/thread-utils.ts@@ -31,6 +31,21 @@ export function collectThreadReplies(return sortTimelineEntriesAsc(out);}+/** Unique member and agent authors, root first, followed by all nested replies. */+export function collectThreadParticipants(+ root: TimelineEntry,+ replies: readonly TimelineEntry[],+): TimelineEntry[] {+ const seen = new Set<string>();+ return [root, ...replies].filter((entry) => {+ if (entry.actor_type !== "member" && entry.actor_type !== "agent") return false;+ const key = `${entry.actor_type}:${entry.actor_id}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}+/*** A thread's resolution, derived purely from `resolved_at`. Two user actions* write the same field:diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex e879acb69b..822a7f8900 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -406,26 +406,6 @@"unpin_tooltip": "Unpin from sidebar","thread_nav_label": "Jump to comment thread","thread_nav_resolved_label": "{{title}} (resolved)",- "thread_nav": {- "button_label_one": "Comment threads ({{count}})",- "button_label_other": "Comment threads ({{count}})",- "search_placeholder": "Search threads or authors",- "match_count_one": "{{count}} match",- "match_count_other": "{{count}} matches",- "filter_all": "All",- "filter_unresolved": "Unresolved",- "filter_resolved": "Resolved",- "filter_mine": "@me",- "group": {- "today": "Today",- "yesterday": "Yesterday",- "earlier": "Earlier"- },- "empty": "No threads match",- "hint_select": "select",- "hint_jump": "jump",- "hint_close": "close"- },"sidebar_tooltip": "Toggle right sidebar","find": {"placeholder": "Find in issue...",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 705a741e74..eee1affad9 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -188,10 +188,6 @@"label": "Find in issue","description": "Search within the open issue detail."},- "openThreadNav": {- "label": "Open thread navigator",- "description": "List, search, and jump between the comment threads of the open issue."- },"archiveInboxItem": {"label": "Archive notification","description": "Archive the open inbox notification, or restore it while reading the archive."diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 327ced5a2c..2ba63d11e7 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -402,24 +402,6 @@"unpin_tooltip": "サイドバーのピン留めを解除","thread_nav_label": "スレッドへ移動","thread_nav_resolved_label": "{{title}}(解決済み)",- "thread_nav": {- "button_label_other": "スレッド({{count}})",- "search_placeholder": "スレッド・作成者を検索",- "match_count_other": "{{count}} 件ヒット",- "filter_all": "すべて",- "filter_unresolved": "未解決",- "filter_resolved": "解決済み",- "filter_mine": "@自分",- "group": {- "today": "今日",- "yesterday": "昨日",- "earlier": "それ以前"- },- "empty": "一致するスレッドはありません",- "hint_select": "選択",- "hint_jump": "移動",- "hint_close": "閉じる"- },"sidebar_tooltip": "右サイドバーの開閉","find": {"placeholder": "タスク内を検索...",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 07ea8aea73..77b987e340 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -188,10 +188,6 @@"label": "タスク内を検索","description": "開いているタスクの詳細を検索します。"},- "openThreadNav": {- "label": "スレッドナビゲーターを開く",- "description": "開いているタスクのコメントスレッドを一覧・検索して移動します。"- },"archiveInboxItem": {"label": "通知をアーカイブ","description": "開いているインボックス通知をアーカイブします。アーカイブ表示中はアーカイブを解除します。"diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex ce308e7e8f..94788b57a9 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -402,24 +402,6 @@"unpin_tooltip": "사이드바 고정 해제","thread_nav_label": "스레드로 이동","thread_nav_resolved_label": "{{title}} (해결됨)",- "thread_nav": {- "button_label_other": "스레드 ({{count}})",- "search_placeholder": "스레드 또는 작성자 검색",- "match_count_other": "{{count}}개 일치",- "filter_all": "전체",- "filter_unresolved": "미해결",- "filter_resolved": "해결됨",- "filter_mine": "@나",- "group": {- "today": "오늘",- "yesterday": "어제",- "earlier": "이전"- },- "empty": "일치하는 스레드가 없습니다",- "hint_select": "선택",- "hint_jump": "이동",- "hint_close": "닫기"- },"sidebar_tooltip": "오른쪽 사이드바 열기/닫기","find": {"placeholder": "태스크에서 찾기...",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 6707dbc1b0..24c23cc703 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -188,10 +188,6 @@"label": "태스크에서 찾기","description": "열린 태스크 상세 내용에서 검색합니다."},- "openThreadNav": {- "label": "스레드 내비게이터 열기",- "description": "열린 태스크의 댓글 스레드를 나열하고 검색해 이동합니다."- },"archiveInboxItem": {"label": "알림 보관","description": "열린 인박스 알림을 보관합니다. 보관함을 보는 중에는 보관을 해제합니다."diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex bcf417b1df..fcd1438bf6 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -400,24 +400,6 @@"unpin_tooltip": "从侧边栏取消固定","thread_nav_label": "快速跳转到讨论","thread_nav_resolved_label": "{{title}}(已解决)",- "thread_nav": {- "button_label_other": "讨论({{count}})",- "search_placeholder": "搜索讨论或作者",- "match_count_other": "{{count}} 条命中",- "filter_all": "全部",- "filter_unresolved": "未解决",- "filter_resolved": "已解决",- "filter_mine": "@我",- "group": {- "today": "今天",- "yesterday": "昨天",- "earlier": "更早"- },- "empty": "没有匹配的讨论",- "hint_select": "选择",- "hint_jump": "跳转",- "hint_close": "关闭"- },"sidebar_tooltip": "切换右侧边栏","find": {"placeholder": "在任务中查找...",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 2f7a2272ba..7d16eef7d0 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -188,10 +188,6 @@"label": "在任务中查找","description": "搜索当前打开的任务详情。"},- "openThreadNav": {- "label": "打开讨论导航",- "description": "列出、搜索并跳转当前任务的评论讨论。"- },"archiveInboxItem": {"label": "归档通知","description": "归档当前打开的收件箱通知;在归档列表中则取消归档。"diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.goindex 89e88192b3..70eaf671b5 100644--- a/server/internal/handler/auth.go+++ b/server/internal/handler/auth.go@@ -18,6 +18,7 @@ import ("unicode/utf8""github.com/golang-jwt/jwt/v5"+ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/auth"@@ -465,8 +466,14 @@ func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {}user, err := h.Queries.GetUser(r.Context(), parseUUID(userID))+ if errors.Is(err, pgx.ErrNoRows) {+ // The credential no longer identifies an existing user. Return the+ // same terminal status as an expired token so clients can sign in again.+ writeError(w, http.StatusUnauthorized, "user not found")+ return+ }if err != nil {- writeError(w, http.StatusNotFound, "user not found")+ writeError(w, http.StatusInternalServerError, "failed to load user")return}diff --git a/server/internal/handler/auth_session_test.go b/server/internal/handler/auth_session_test.gonew file mode 100644index 0000000000..bcd926c6ce--- /dev/null+++ b/server/internal/handler/auth_session_test.go@@ -0,0 +1,33 @@+package handler++import (+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestGetMeSessionFailures(t *testing.T) {+ for _, tt := range []struct {+ name string+ err error+ wantStatus int+ }{+ {"missing user", pgx.ErrNoRows, http.StatusUnauthorized},+ {"wrapped missing user", fmt.Errorf("lookup: %w", pgx.ErrNoRows), http.StatusUnauthorized},+ {"database unavailable", errors.New("connection refused"), http.StatusInternalServerError},+ } {+ t.Run(tt.name, func(t *testing.T) {+ h := newTestHandler(Config{})+ h.Queries = db.New(&mockDB{getUserErr: tt.err})+ req := httptest.NewRequest(http.MethodGet, "/api/me", nil)+ req.Header.Set("X-User-ID", "00000000-0000-4000-8000-000000000001")+ testutil.Call(t, h.GetMe, req).Want(tt.wantStatus)+ })+ }+}