Skip to content

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

Go

MUL-8951: Jump to latest on desktop issues and in chat (#10291)

Jiayuan Zhang6329aa2802b6
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index 1a2f8fbc99..9a627e1bb4 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -50,6 +50,7 @@ import { TaskStatusPill } from "./task-status-pill";
import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";
import { FOLLOW_EDGE_THRESHOLD } from "../../common/task-transcript/transcript-follow";
import { LIVE_END_ROW_ATTR, useStickToBottom } from "./stick-to-bottom";
+import { JumpToLiveEndButton, useJumpToLiveEnd } from "./jump-to-live-end";
import { formatElapsedMs } from "../lib/format";
import {
canonicalAnswerText,
@@ -296,7 +297,17 @@ export function ChatMessageList({
}, [messages, hasLive, pendingTaskId]);
const firstIndex = renderItems.length > 0 ? firstItemIndex : 0;
- const liveEndKey = renderItems[renderItems.length - 1]?.key ?? null;
+ const tailItem = renderItems[renderItems.length - 1];
+ const liveEndKey = tailItem?.key ?? null;
+ // Changes when the last row is new or a live reply streamed more output.
+ const tailKey = tailItem
+ ? `${tailItem.key}:${tailItem.kind === "live" ? (liveTaskMessages?.length ?? 0) : "persisted"}`
+ : null;
+ const jumpToLiveEnd = useJumpToLiveEnd(scrollContainerEl, pinToLiveEnd, {
+ enabled: active && hasReachedLiveEnd,
+ tailKey,
+ tailIsReply: tailItem?.kind === "live" || tailItem?.message.role === "assistant",
+ });
const listContext: ChatListContext = {
isFetchingOlderMessages,
@@ -327,6 +338,9 @@ export function ChatMessageList({
return (
<PreviewSequenceProvider items={previewSequence}>
+ {/* Positioning box for the floating "Jump to latest" button, so it stays
+ * pinned above the composer instead of scrolling with the rows. */}
+ <div className="relative flex min-h-0 flex-1 flex-col">
<div
ref={setScrollContainerRef}
data-tab-scroll-root
@@ -414,6 +428,14 @@ export function ChatMessageList({
</RichContentScrollRootProvider>
)}
</div>
+ {jumpToLiveEnd.visible && (
+ <JumpToLiveEndButton
+ hasNewReply={jumpToLiveEnd.hasNewReply}
+ onClick={jumpToLiveEnd.jump}
+ className="absolute bottom-3 left-1/2 z-10 -translate-x-1/2"
+ />
+ )}
+ </div>
</PreviewSequenceProvider>
);
}
diff --git a/packages/views/chat/components/jump-to-live-end.test.tsx b/packages/views/chat/components/jump-to-live-end.test.tsx
new file mode 100644
index 0000000000..223c367296
--- /dev/null
+++ b/packages/views/chat/components/jump-to-live-end.test.tsx
@@ -0,0 +1,168 @@
+import { useState } from "react";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { JUMP_MAX_FRAMES, useJumpToLiveEnd } from "./jump-to-live-end";
+
+let rafCallbacks: FrameRequestCallback[] = [];
+
+function flushFrame() {
+ act(() => {
+ const callbacks = rafCallbacks;
+ rafCallbacks = [];
+ callbacks.forEach((cb) => cb(0));
+ });
+}
+
+type Metrics = { scrollHeight: number; clientHeight: number };
+
+// jsdom has no layout: fixed metrics, with scrollTop clamped like a browser.
+function defineMetrics(el: HTMLElement, metrics: Metrics) {
+ let top = 0;
+ Object.defineProperty(el, "clientHeight", { configurable: true, get: () => metrics.clientHeight });
+ Object.defineProperty(el, "scrollHeight", { configurable: true, get: () => metrics.scrollHeight });
+ Object.defineProperty(el, "scrollTop", {
+ configurable: true,
+ get: () => top,
+ set: (v: number) => {
+ top = Math.max(0, Math.min(v, metrics.scrollHeight - metrics.clientHeight));
+ },
+ });
+}
+
+function Harness({
+ metrics,
+ pin,
+ tailKey = "t1",
+ tailIsReply = true,
+}: {
+ metrics: Metrics;
+ pin: (el: HTMLElement) => void;
+ tailKey?: string;
+ tailIsReply?: boolean;
+}) {
+ const [el, setEl] = useState<HTMLDivElement | null>(null);
+ const { visible, hasNewReply, jump } = useJumpToLiveEnd(el, () => el && pin(el), {
+ enabled: true,
+ tailKey,
+ tailIsReply,
+ });
+ return (
+ <div
+ data-testid="scroller"
+ ref={(node) => {
+ if (node && node !== el) {
+ defineMetrics(node, metrics);
+ setEl(node);
+ }
+ }}
+ >
+ {visible && <button onClick={jump}>{hasNewReply ? "new reply" : "latest"}</button>}
+ </div>
+ );
+}
+
+function scrollTo(scroller: HTMLElement, top: number) {
+ scroller.scrollTop = top;
+ fireEvent.scroll(scroller);
+ flushFrame();
+}
+
+beforeEach(() => {
+ rafCallbacks = [];
+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {
+ rafCallbacks.push(cb);
+ return rafCallbacks.length;
+ });
+ vi.stubGlobal("cancelAnimationFrame", () => {});
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+const toBottom = (el: HTMLElement) => {
+ el.scrollTop = el.scrollHeight - el.clientHeight;
+};
+
+describe("useJumpToLiveEnd", () => {
+ it("shows only when the reader is more than a screen above the live end", () => {
+ render(<Harness metrics={{ scrollHeight: 3000, clientHeight: 500 }} pin={toBottom} />);
+ const scroller = screen.getByTestId("scroller");
+ scrollTo(scroller, 2500);
+ expect(screen.queryByRole("button")).toBeNull();
+
+ scrollTo(scroller, 2100); // 400px up: still within a screen
+ expect(screen.queryByRole("button")).toBeNull();
+
+ scrollTo(scroller, 1000);
+ expect(screen.getByRole("button", { name: "latest" })).toBeTruthy();
+ });
+
+ it("flags a reply that lands while the reader is away, and drops it back at the end", () => {
+ const metrics = { scrollHeight: 3000, clientHeight: 500 };
+ const { rerender } = render(<Harness metrics={metrics} pin={toBottom} tailKey="t1" />);
+ const scroller = screen.getByTestId("scroller");
+ scrollTo(scroller, 1000);
+
+ rerender(<Harness metrics={metrics} pin={toBottom} tailKey="t2" />);
+ expect(screen.getByRole("button", { name: "new reply" })).toBeTruthy();
+
+ scrollTo(scroller, 2500);
+ scrollTo(scroller, 1000);
+ expect(screen.getByRole("button", { name: "latest" })).toBeTruthy();
+ });
+
+ it("does not flag the reader's own message", () => {
+ const metrics = { scrollHeight: 3000, clientHeight: 500 };
+ const { rerender } = render(<Harness metrics={metrics} pin={toBottom} tailKey="t1" />);
+ const scroller = screen.getByTestId("scroller");
+ scrollTo(scroller, 1000);
+
+ rerender(<Harness metrics={metrics} pin={toBottom} tailKey="u1" tailIsReply={false} />);
+ expect(screen.getByRole("button", { name: "latest" })).toBeTruthy();
+ });
+
+ it("re-aims until the list holds at the live end", () => {
+ const metrics = { scrollHeight: 3000, clientHeight: 500 };
+ const pin = vi.fn((el: HTMLElement) => {
+ toBottom(el);
+ // Virtuoso measures the rows it lands on: the first aim falls short.
+ if (pin.mock.calls.length === 1) metrics.scrollHeight = 4000;
+ });
+ render(<Harness metrics={metrics} pin={pin} />);
+ const scroller = screen.getByTestId("scroller");
+ scrollTo(scroller, 0);
+
+ fireEvent.click(screen.getByRole("button", { name: "latest" }));
+ expect(scroller.scrollTop).toBe(2500);
+ flushFrame();
+ expect(scroller.scrollTop).toBe(3500);
+ flushFrame();
+ flushFrame();
+ expect(pin).toHaveBeenCalledTimes(2);
+ });
+
+ it("gives up after a bounded number of frames", () => {
+ const pin = vi.fn();
+ render(<Harness metrics={{ scrollHeight: 3000, clientHeight: 500 }} pin={pin} />);
+ scrollTo(screen.getByTestId("scroller"), 0);
+
+ fireEvent.click(screen.getByRole("button", { name: "latest" }));
+ for (let i = 0; i < JUMP_MAX_FRAMES + 5; i++) flushFrame();
+ expect(pin.mock.calls.length).toBeLessThanOrEqual(JUMP_MAX_FRAMES);
+ });
+
+ it("stops re-aiming once the reader scrolls", () => {
+ const pin = vi.fn();
+ render(<Harness metrics={{ scrollHeight: 3000, clientHeight: 500 }} pin={pin} />);
+ const scroller = screen.getByTestId("scroller");
+ scrollTo(scroller, 0);
+
+ fireEvent.click(screen.getByRole("button", { name: "latest" }));
+ fireEvent.wheel(scroller);
+ flushFrame();
+ flushFrame();
+ expect(pin).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/views/chat/components/jump-to-live-end.tsx b/packages/views/chat/components/jump-to-live-end.tsx
new file mode 100644
index 0000000000..f5f7103769
--- /dev/null
+++ b/packages/views/chat/components/jump-to-live-end.tsx
@@ -0,0 +1,161 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { ArrowDown } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import { cn } from "@multica/ui/lib/utils";
+import { distanceFromBottom, isAtLiveEnd } from "./stick-to-bottom";
+import { useT } from "../../i18n";
+
+// "Jump to latest" for the chat list (MUL-8951).
+//
+// The button shows once the reader is more than a screen above the live end.
+// A jump only has to reach the live end: arriving within its edge zone
+// re-engages the stick-to-bottom follow, which keeps the list pinned from
+// there as the reply streams on.
+
+/** Most frames a jump keeps re-aiming at the last row while Virtuoso measures it. */
+export const JUMP_MAX_FRAMES = 30;
+
+export interface JumpToLiveEnd {
+ visible: boolean;
+ /** The agent replied while the reader was away from the live end. */
+ hasNewReply: boolean;
+ jump(): void;
+}
+
+/**
+ * `pinToLiveEnd` must scroll through Virtuoso (see `useStickToBottom`): the
+ * container's `scrollHeight` is an estimate, so a jump re-aims each frame
+ * until the list holds at the live end. `tailKey` changes whenever the last
+ * row is new or has grown, and `tailIsReply` says whether that row is the
+ * agent's — together they flag a reply landing out of view.
+ */
+export function useJumpToLiveEnd(
+ scrollEl: HTMLElement | null,
+ pinToLiveEnd: () => void,
+ {
+ enabled,
+ tailKey,
+ tailIsReply,
+ }: { enabled: boolean; tailKey: string | null; tailIsReply: boolean },
+): JumpToLiveEnd {
+ const [visible, setVisible] = useState(false);
+ const [hasNewReply, setHasNewReply] = useState(false);
+ const visibleRef = useRef(visible);
+ visibleRef.current = visible;
+ const cancelJumpRef = useRef<(() => void) | null>(null);
+
+ useEffect(() => {
+ if (!enabled || !scrollEl) {
+ setVisible(false);
+ return;
+ }
+ let frame = 0;
+ const measure = () => {
+ frame = 0;
+ setVisible(distanceFromBottom(scrollEl) > scrollEl.clientHeight);
+ };
+ const schedule = () => {
+ if (frame === 0) frame = requestAnimationFrame(measure);
+ };
+ measure();
+ scrollEl.addEventListener("scroll", schedule, { passive: true });
+ // Streaming growth and older pages change the extent without a scroll event.
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
+ observer?.observe(scrollEl);
+ for (const child of Array.from(scrollEl.children)) observer?.observe(child);
+ return () => {
+ scrollEl.removeEventListener("scroll", schedule);
+ observer?.disconnect();
+ if (frame !== 0) cancelAnimationFrame(frame);
+ };
+ }, [enabled, scrollEl]);
+
+ const lastTailKeyRef = useRef(tailKey);
+ useEffect(() => {
+ if (lastTailKeyRef.current === tailKey) return;
+ lastTailKeyRef.current = tailKey;
+ if (visibleRef.current && tailIsReply) setHasNewReply(true);
+ }, [tailKey, tailIsReply]);
+
+ useEffect(() => {
+ if (!visible) setHasNewReply(false);
+ }, [visible]);
+
+ useEffect(() => () => cancelJumpRef.current?.(), []);
+
+ const jump = useCallback(() => {
+ const el = scrollEl;
+ if (!el) return;
+ cancelJumpRef.current?.();
+ let frame = 0;
+ let frames = 0;
+ let cancelled = false;
+ const userInputs = ["wheel", "touchstart", "pointerdown"] as const;
+ const stop = () => {
+ cancelled = true;
+ cancelAnimationFrame(frame);
+ for (const type of userInputs) el.removeEventListener(type, stop);
+ if (cancelJumpRef.current === stop) cancelJumpRef.current = null;
+ };
+ const tick = () => {
+ if (cancelled) return;
+ if (!el.isConnected || isAtLiveEnd(el) || ++frames >= JUMP_MAX_FRAMES) {
+ stop();
+ return;
+ }
+ pinToLiveEnd();
+ frame = requestAnimationFrame(tick);
+ };
+ for (const type of userInputs) el.addEventListener(type, stop, { passive: true });
+ cancelJumpRef.current = stop;
+ setHasNewReply(false);
+ pinToLiveEnd();
+ frame = requestAnimationFrame(tick);
+ }, [scrollEl, pinToLiveEnd]);
+
+ return { visible, hasNewReply, jump };
+}
+
+const FLOATING = "rounded-full bg-background shadow-md dark:bg-background dark:hover:bg-muted";
+
+export function JumpToLiveEndButton({
+ hasNewReply,
+ onClick,
+ className,
+}: {
+ hasNewReply: boolean;
+ onClick: () => void;
+ className?: string;
+}) {
+ const { t } = useT("chat");
+ if (hasNewReply) {
+ return (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={onClick}
+ className={cn(FLOATING, className)}
+ >
+ <span aria-hidden="true" className="size-1.5 rounded-full bg-brand" />
+ {t(($) => $.message_list.new_reply)}
+ <ArrowDown />
+ </Button>
+ );
+ }
+ return (
+ <IconButton
+ type="button"
+ variant="outline"
+ size="icon"
+ label={t(($) => $.message_list.jump_to_latest)}
+ onClick={onClick}
+ className={cn(FLOATING, className)}
+ >
+ <ArrowDown />
+ </IconButton>
+ );
+}
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 3ed330e649..b9d731bc10 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -204,6 +204,7 @@ import { useIssueDetailScrollRestore } from "../hooks/use-issue-detail-scroll-re
import { useIssueTimelineAnchor } from "../hooks/use-issue-timeline-anchor";
import { scrollToTimelineComment } from "../utils/scroll-to-timeline-comment";
import { useJumpToLatest } from "../hooks/use-jump-to-latest";
+import { useNewCommentsWhileAway } from "../hooks/use-new-comments-while-away";
import { useInPageFind } from "../hooks/use-in-page-find";
import { useStickyComposer } from "../hooks/use-sticky-composer";
import { FindBar } from "./find-bar";
@@ -596,7 +597,16 @@ function shallowEqualEntries(a: TimelineEntry[], b: TimelineEntry[]): boolean {
return true;
}
-function JumpToLatestButton({ onClick, label }: { onClick: () => void; label: string }) {
+function JumpToLatestButton({
+ onClick,
+ label,
+ hasNew = false,
+}: {
+ onClick: () => void;
+ label: string;
+ /** New comments arrived while the reader was away; `label` counts them. */
+ hasNew?: boolean;
+}) {
return (
<Button
type="button"
@@ -605,8 +615,18 @@ function JumpToLatestButton({ onClick, label }: { onClick: () => void; label: st
onClick={onClick}
className="absolute bottom-full left-1/2 mb-6 -translate-x-1/2 bg-background shadow-md dark:bg-background dark:hover:bg-muted"
>
- <ArrowDown />
- {label}
+ {hasNew ? (
+ <>
+ <span aria-hidden="true" className="size-1.5 rounded-full bg-brand" />
+ {label}
+ <ArrowDown />
+ </>
+ ) : (
+ <>
+ <ArrowDown />
+ {label}
+ </>
+ )}
</Button>
);
}
@@ -1578,10 +1598,10 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
// User preference: pin the bottom comment bar to the scroll viewport. Off
// below `md` regardless of the preference — see the hook.
const stickyComposer = useStickyComposer();
- // Mobile only: desktop already reaches the latest entry through the
- // ThreadMinimap rail, which is not rendered below `md`. Passing null keeps
- // the hook's scroll and resize listeners off on desktop.
- const jumpToLatest = useJumpToLatest(isMobile ? scrollContainerEl : null);
+ // Mobile shows it only near the top of the page, where it covers the text
+ // column the least; desktop shows it whenever the latest entry is more than
+ // a screen away.
+ const jumpToLatest = useJumpToLatest(scrollContainerEl, { nearTopOnly: isMobile });
// Per-session: which resolved threads the user has temporarily expanded.
// Not persisted (matches Linear) — reload collapses everything back to bars.
@@ -1755,6 +1775,12 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
submitComment, submitReply,
editComment, deleteComment, toggleResolveComment, toggleReaction: handleToggleReaction,
} = useIssueTimeline(id, user?.id, activeDeliverableJump?.commentId);
+ const newComments = useNewCommentsWhileAway(timeline, {
+ ready: !timelineLoading,
+ away: jumpToLatest.visible,
+ userId: user?.id,
+ resetKey: id,
+ });
const { data: commentTasks, isLoading: commentTasksLoading } = useQuery(issueTasksOptions(id));
const enteringRunIds = useNewRunIds(id, commentTasks);
@@ -2212,6 +2238,22 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
replyToRoot.has(commentId) ? jumpToReply(commentId) : jumpToThread(commentId),
[replyToRoot, jumpToReply, jumpToThread],
);
+ // With comments that arrived while the reader was away, land on the first
+ // of them so they read in order; otherwise go to the very end.
+ const firstNewCommentId = newComments.ids[0];
+ const clearNewComments = newComments.clear;
+ const jumpLatest = jumpToLatest.jump;
+ const onJumpToLatest = useCallback(() => {
+ if (firstNewCommentId) {
+ clearNewComments();
+ jumpToMinimapTarget(firstNewCommentId);
+ } else {
+ jumpLatest();
+ }
+ }, [firstNewCommentId, clearNewComments, jumpToMinimapTarget, jumpLatest]);
+ const jumpToLatestLabel = newComments.ids.length > 0
+ ? t(($) => $.timeline.new_comments, { count: newComments.ids.length })
+ : t(($) => $.timeline.jump_to_latest);
// Header chip jump to a run's block. A run is either its own top-level row
// or a slot inside the thread it answers, so find that row, undo whatever
// folds the thread, scroll the row into place, then let the effect below
@@ -4071,13 +4113,13 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
page background and is invisible), and pb-4 so the card floats
off the viewport edge — with -mb-4 giving the padding back to
the column's py-8 so the at-rest layout doesn't shift. */}
- {/* "Jump to latest" (MUL-8324, mobile only) floats centered just above the
+ {/* "Jump to latest" (MUL-8324, MUL-8951) floats centered just above the
composer's top edge. With the sticky composer it rides the
composer itself; without it, a zero-height sticky anchor pins
it to the viewport bottom until the composer scrolls in. */}
{!stickyComposer && jumpToLatest.visible && (
<div className="sticky bottom-0 z-10 h-0">
- <JumpToLatestButton onClick={jumpToLatest.jump} label={t(($) => $.timeline.jump_to_latest)} />
+ <JumpToLatestButton onClick={onJumpToLatest} label={jumpToLatestLabel} hasNew={!!firstNewCommentId} />
</div>
)}
<IssueAppRequests issueId={id} highlightId={highlightAppRequestId} highlightToken={highlightRequestToken} />
@@ -4095,7 +4137,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
next keystroke would flush it into the new issue's
draft key. */}
{stickyComposer && jumpToLatest.visible && (
- <JumpToLatestButton onClick={jumpToLatest.jump} label={t(($) => $.timeline.jump_to_latest)} />
+ <JumpToLatestButton onClick={onJumpToLatest} label={jumpToLatestLabel} hasNew={!!firstNewCommentId} />
)}
<CommentInput
key={id}
diff --git a/packages/views/issues/hooks/use-jump-to-latest.test.tsx b/packages/views/issues/hooks/use-jump-to-latest.test.tsx
index c5b4e6acce..752160c518 100644
--- a/packages/views/issues/hooks/use-jump-to-latest.test.tsx
+++ b/packages/views/issues/hooks/use-jump-to-latest.test.tsx
@@ -31,9 +31,15 @@ function defineMetrics(el: HTMLElement, metrics: { scrollHeight: number; clientH
});
}
-function Harness({ metrics }: { metrics: { scrollHeight: number; clientHeight: number } }) {
+function Harness({
+ metrics,
+ nearTopOnly = false,
+}: {
+ metrics: { scrollHeight: number; clientHeight: number };
+ nearTopOnly?: boolean;
+}) {
const [el, setEl] = useState<HTMLDivElement | null>(null);
- const { visible, jump } = useJumpToLatest(el);
+ const { visible, jump } = useJumpToLatest(el, { nearTopOnly });
return (
<div
data-testid="scroller"
@@ -77,10 +83,20 @@ describe("useJumpToLatest", () => {
expect(screen.queryByRole("button", { name: "latest" })).toBeNull();
});
- it("hides once the reader has scrolled past the top fifth of the page", () => {
+ it("stays up anywhere more than a screen from the bottom", () => {
render(<Harness metrics={{ scrollHeight: 4000, clientHeight: 500 }} />);
const scroller = screen.getByTestId("scroller");
+ scroller.scrollTop = 2900; // 600px from the bottom, far past the top fifth
+ fireEvent.scroll(scroller);
+ flushFrame();
+ expect(screen.getByRole("button", { name: "latest" })).toBeTruthy();
+ });
+
+ it("near-top-only: hides once the reader has scrolled past the top fifth of the page", () => {
+ render(<Harness metrics={{ scrollHeight: 4000, clientHeight: 500 }} nearTopOnly />);
+ const scroller = screen.getByTestId("scroller");
+
scroller.scrollTop = 800; // exactly 20% of the page
fireEvent.scroll(scroller);
flushFrame();
@@ -92,8 +108,8 @@ describe("useJumpToLatest", () => {
expect(screen.queryByRole("button", { name: "latest" })).toBeNull();
});
- it("stays hidden when the view opens restored past the top fifth", () => {
- render(<Harness metrics={{ scrollHeight: 4000, clientHeight: 500 }} />);
+ it("near-top-only: stays hidden when the view opens restored past the top fifth", () => {
+ render(<Harness metrics={{ scrollHeight: 4000, clientHeight: 500 }} nearTopOnly />);
const scroller = screen.getByTestId("scroller");
scroller.scrollTop = 2000;
fireEvent.scroll(scroller);
diff --git a/packages/views/issues/hooks/use-jump-to-latest.ts b/packages/views/issues/hooks/use-jump-to-latest.ts
index 4696709e90..1ec680b9cd 100644
--- a/packages/views/issues/hooks/use-jump-to-latest.ts
+++ b/packages/views/issues/hooks/use-jump-to-latest.ts
@@ -1,10 +1,11 @@
import { useCallback, useEffect, useRef, useState } from "react";
/**
- * Drives the issue timeline's "Jump to latest" affordance (MUL-8324).
+ * Drives the issue timeline's "Jump to latest" affordance (MUL-8324, MUL-8951).
*
- * `visible` is on while the reader is still near the top of the page and the
- * newest entry is more than one screen away; see `shouldShow`.
+ * `visible` is on while the newest entry is more than one screen away. With
+ * `nearTopOnly` (mobile) the reader must also still be near the top of the
+ * page; see `shouldShow`.
*
* `jump` drives scrollTop to the bottom directly instead of asking Virtuoso
* for the last index: with `customScrollParent`, writing scrollTop is what
@@ -15,7 +16,10 @@ import { useCallback, useEffect, useRef, useState } from "react";
/** How long a jump keeps re-pinning the bottom while late content lands. */
export const JUMP_FOLLOW_MS = 2000;
-export function useJumpToLatest(scrollContainerEl: HTMLElement | null) {
+export function useJumpToLatest(
+ scrollContainerEl: HTMLElement | null,
+ { nearTopOnly = false }: { nearTopOnly?: boolean } = {},
+) {
const [visible, setVisible] = useState(false);
const cancelJumpRef = useRef<(() => void) | null>(null);
@@ -27,7 +31,7 @@ export function useJumpToLatest(scrollContainerEl: HTMLElement | null) {
let frame = 0;
const measure = () => {
frame = 0;
- setVisible(shouldShow(scrollContainerEl));
+ setVisible(shouldShow(scrollContainerEl, nearTopOnly));
};
const schedule = () => {
if (frame === 0) frame = requestAnimationFrame(measure);
@@ -44,7 +48,7 @@ export function useJumpToLatest(scrollContainerEl: HTMLElement | null) {
observer?.disconnect();
if (frame !== 0) cancelAnimationFrame(frame);
};
- }, [scrollContainerEl]);
+ }, [scrollContainerEl, nearTopOnly]);
useEffect(() => () => cancelJumpRef.current?.(), []);
@@ -98,17 +102,16 @@ export function useJumpToLatest(scrollContainerEl: HTMLElement | null) {
}
/**
- * Show only near the top of the page: the viewport's top edge must still be
- * within the first `SHOW_WITHIN_TOP_RATIO` of the page, and more than one
- * screen must be left below. Once the reader has scrolled further on their
- * own they are reading, not hunting for the latest entry, so the button gets
- * out of the way; short pages never show it at all.
+ * Show while more than one screen is left below; short pages never show it.
+ *
+ * `nearTopOnly` also requires the viewport's top edge to be within the first
+ * `SHOW_WITHIN_TOP_RATIO` of the page: on mobile the button covers the text
+ * column, so once the reader has scrolled further on their own they are
+ * reading, not hunting for the latest entry, and it gets out of the way.
*/
-function shouldShow(el: HTMLElement) {
- return (
- el.scrollTop <= el.scrollHeight * SHOW_WITHIN_TOP_RATIO &&
- distanceFromBottom(el) > el.clientHeight
- );
+function shouldShow(el: HTMLElement, nearTopOnly: boolean) {
+ if (distanceFromBottom(el) <= el.clientHeight) return false;
+ return !nearTopOnly || el.scrollTop <= el.scrollHeight * SHOW_WITHIN_TOP_RATIO;
}
/** Share of the page the reader can scroll through before the button hides. */
diff --git a/packages/views/issues/hooks/use-new-comments-while-away.test.tsx b/packages/views/issues/hooks/use-new-comments-while-away.test.tsx
new file mode 100644
index 0000000000..a028f16eac
--- /dev/null
+++ b/packages/views/issues/hooks/use-new-comments-while-away.test.tsx
@@ -0,0 +1,109 @@
+import { act, renderHook } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import type { TimelineEntry } from "@multica/core/types";
+import { useNewCommentsWhileAway } from "./use-new-comments-while-away";
+
+const ME = "user-me";
+let clock = Date.parse("2026-11-10T00:00:00Z");
+
+function comment(id: string, actor: { type?: string; id?: string } = {}, extra: Partial<TimelineEntry> = {}): TimelineEntry {
+ clock += 1000;
+ return {
+ type: "comment",
+ id,
+ actor_type: actor.type ?? "agent",
+ actor_id: actor.id ?? "agent-1",
+ created_at: new Date(clock).toISOString(),
+ content: id,
+ ...extra,
+ } as TimelineEntry;
+}
+
+type Props = { timeline: TimelineEntry[]; ready: boolean; away: boolean; resetKey: string };
+
+function setup(initial: Props) {
+ return renderHook(
+ (props: Props) => useNewCommentsWhileAway(props.timeline, { ...props, userId: ME }),
+ { initialProps: initial },
+ );
+}
+
+describe("useNewCommentsWhileAway", () => {
+ it("treats the loaded timeline as the baseline and counts later arrivals while away", () => {
+ const base = [comment("c1"), comment("c2")];
+ const { result, rerender } = setup({ timeline: base, ready: true, away: true, resetKey: "i1" });
+ expect(result.current.ids).toEqual([]);
+
+ rerender({ timeline: [...base, comment("c3"), comment("c4")], ready: true, away: true, resetKey: "i1" });
+ expect(result.current.ids).toEqual(["c3", "c4"]);
+ });
+
+ it("ignores an older thread merged into the bounded timeline", () => {
+ const old = comment("old", {}, { created_at: "2026-01-01T00:00:00Z" });
+ const base = [comment("c1")];
+ const { result, rerender } = setup({ timeline: base, ready: true, away: true, resetKey: "i1" });
+ rerender({ timeline: [old, ...base], ready: true, away: true, resetKey: "i1" });
+ expect(result.current.ids).toEqual([]);
+
+ rerender({ timeline: [old, ...base, comment("c2")], ready: true, away: true, resetKey: "i1" });
+ expect(result.current.ids).toEqual(["c2"]);
+ });
+
+ it("waits for the timeline to load before taking the baseline", () => {
+ const { result, rerender } = setup({ timeline: [], ready: false, away: true, resetKey: "i1" });
+ rerender({ timeline: [comment("c1"), comment("c2")], ready: true, away: true, resetKey: "i1" });
+ expect(result.current.ids).toEqual([]);
+ });
+
+ it("ignores arrivals while the reader is at the latest entry", () => {
+ const base = [comment("c1")];
+ const { result, rerender } = setup({ timeline: base, ready: true, away: false, resetKey: "i1" });
+ rerender({ timeline: [...base, comment("c2")], ready: true, away: false, resetKey: "i1" });
+ rerender({ timeline: [...base, comment("c2")], ready: true, away: true, resetKey: "i1" });
+ expect(result.current.ids).toEqual([]);
+ });
+
+ it("never counts the reader's own comments", () => {
+ const base = [comment("c1")];
+ const { result, rerender } = setup({ timeline: base, ready: true, away: true, resetKey: "i1" });
+ rerender({
+ timeline: [...base, comment("mine", { type: "member", id: ME }), comment("theirs", { type: "member", id: "other" })],
+ ready: true,
+ away: true,
+ resetKey: "i1",
+ });
+ expect(result.current.ids).toEqual(["theirs"]);
+ });
+
+ it("empties once the reader is back and drops comments deleted meanwhile", () => {
+ const base = [comment("c1")];
+ const { result, rerender } = setup({ timeline: base, ready: true, away: true, resetKey: "i1" });
+ rerender({ timeline: [...base, comment("c2"), comment("c3")], ready: true, away: true, resetKey: "i1" });
+ rerender({
+ timeline: [...base, comment("c2", {}, { deleted_at: "2026-11-10T00:01:00Z" }), comment("c3")],
+ ready: true,
+ away: true,
+ resetKey: "i1",
+ });
+ expect(result.current.ids).toEqual(["c3"]);
+
+ rerender({ timeline: [...base, comment("c3")], ready: true, away: false, resetKey: "i1" });
+ expect(result.current.ids).toEqual([]);
+ });
+
+ it("clears on demand", () => {
+ const base = [comment("c1")];
+ const { result, rerender } = setup({ timeline: base, ready: true, away: true, resetKey: "i1" });
+ rerender({ timeline: [...base, comment("c2")], ready: true, away: true, resetKey: "i1" });
+ act(() => result.current.clear());
+ expect(result.current.ids).toEqual([]);
+ });
+
+ it("starts a fresh baseline for another issue", () => {
+ const { result, rerender } = setup({ timeline: [comment("a1")], ready: true, away: true, resetKey: "i1" });
+ rerender({ timeline: [comment("b1"), comment("b2")], ready: true, away: true, resetKey: "i2" });
+ expect(result.current.ids).toEqual([]);
+ rerender({ timeline: [comment("b1"), comment("b2"), comment("b3")], ready: true, away: true, resetKey: "i2" });
+ expect(result.current.ids).toEqual(["b3"]);
+ });
+});
diff --git a/packages/views/issues/hooks/use-new-comments-while-away.ts b/packages/views/issues/hooks/use-new-comments-while-away.ts
new file mode 100644
index 0000000000..77058dada1
--- /dev/null
+++ b/packages/views/issues/hooks/use-new-comments-while-away.ts
@@ -0,0 +1,90 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type { TimelineEntry } from "@multica/core/types";
+import { isDeletedComment } from "@multica/core/issues/comment-deletion";
+
+/**
+ * Comments that arrived while the reader was away from the latest entry
+ * (MUL-8951), oldest first, so "Jump to latest" can say how many landed and
+ * take the reader to the first of them.
+ *
+ * The comments present once the timeline has loaded are the baseline; only
+ * later arrivals count, and only while `away`. The reader's own comments never
+ * count — posting one already scrolls to it. The list empties as soon as the
+ * reader is no longer away, and starts over when `resetKey` (the issue)
+ * changes, since the issue page is reused across issues.
+ */
+export function useNewCommentsWhileAway(
+ timeline: readonly TimelineEntry[],
+ {
+ ready,
+ away,
+ userId,
+ resetKey,
+ }: { ready: boolean; away: boolean; userId: string | undefined; resetKey: string },
+): { ids: readonly string[]; clear: () => void } {
+ const [ids, setIds] = useState<string[]>([]);
+ const seenRef = useRef<Set<string> | null>(null);
+ // The timeline is bounded, and an older thread can be merged in later (a
+ // deliverable or deep-link landing); only comments newer than everything
+ // seen so far are arrivals.
+ const newestRef = useRef(Number.NEGATIVE_INFINITY);
+ const keyRef = useRef(resetKey);
+ // Read inside the timeline effect: an arrival grows the page before the
+ // away flag is re-measured, so this is still the state the reader was in.
+ const awayRef = useRef(away);
+ awayRef.current = away;
+
+ useEffect(() => {
+ if (keyRef.current !== resetKey) {
+ keyRef.current = resetKey;
+ seenRef.current = null;
+ newestRef.current = Number.NEGATIVE_INFINITY;
+ setIds((prev) => (prev.length === 0 ? prev : []));
+ }
+ if (!ready) return;
+ const comments = timeline.filter((entry) => entry.type === "comment");
+ if (seenRef.current === null) {
+ seenRef.current = new Set(comments.map((entry) => entry.id));
+ newestRef.current = comments.reduce((newest, entry) => {
+ const at = createdAt(entry);
+ return at > newest ? at : newest;
+ }, Number.NEGATIVE_INFINITY);
+ return;
+ }
+ const seen = seenRef.current;
+ const since = newestRef.current;
+ const arrived: string[] = [];
+ for (const entry of comments) {
+ if (seen.has(entry.id)) continue;
+ seen.add(entry.id);
+ const at = createdAt(entry);
+ if (!(at > since)) continue;
+ if (at > newestRef.current) newestRef.current = at;
+ if (!awayRef.current || isDeletedComment(entry)) continue;
+ if (entry.actor_type === "member" && entry.actor_id === userId) continue;
+ arrived.push(entry.id);
+ }
+ if (arrived.length > 0) setIds((prev) => [...prev, ...arrived]);
+ }, [timeline, ready, resetKey, userId]);
+
+ useEffect(() => {
+ if (!away) setIds((prev) => (prev.length === 0 ? prev : []));
+ }, [away]);
+
+ const clear = useCallback(() => setIds((prev) => (prev.length === 0 ? prev : [])), []);
+
+ // A new comment deleted before the reader gets to it no longer counts.
+ const live = useMemo(() => {
+ if (ids.length === 0) return ids;
+ const present = new Set(
+ timeline.filter((entry) => entry.type === "comment" && !isDeletedComment(entry)).map((entry) => entry.id),
+ );
+ return ids.filter((id) => present.has(id));
+ }, [ids, timeline]);
+
+ return { ids: live, clear };
+}
+
+function createdAt(entry: TimelineEntry): number {
+ return Date.parse(entry.created_at);
+}
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index 4acc9069d6..72a418c4fa 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -52,6 +52,8 @@
"action_failed_toast": "Couldn't update the queued message"
},
"message_list": {
+ "jump_to_latest": "Jump to latest",
+ "new_reply": "New reply",
"show_details": "Show details",
"replied_in": "Replied in {{elapsed}}",
"failed_after": "Failed after {{elapsed}}",
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index de04357864..6e1bd4fe01 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -587,7 +587,9 @@
},
"timeline": {
"loading": "Loading...",
- "jump_to_latest": "Jump to latest"
+ "jump_to_latest": "Jump to latest",
+ "new_comments_one": "{{count}} new comment",
+ "new_comments_other": "{{count}} new comments"
},
"activity": {
"created": "created this issue",
diff --git a/packages/views/locales/es/chat.json b/packages/views/locales/es/chat.json
index 57dee82a8a..159d13177f 100644
--- a/packages/views/locales/es/chat.json
+++ b/packages/views/locales/es/chat.json
@@ -52,6 +52,8 @@
"action_failed_toast": "No se ha podido actualizar el mensaje en cola"
},
"message_list": {
+ "jump_to_latest": "Ir a lo más reciente",
+ "new_reply": "Nueva respuesta",
"show_details": "Mostrar detalles",
"replied_in": "Respondió en {{elapsed}}",
"failed_after": "Falló tras {{elapsed}}",
diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.json
index 0be015db6b..d39d77a6cb 100644
--- a/packages/views/locales/es/issues.json
+++ b/packages/views/locales/es/issues.json
@@ -570,7 +570,9 @@
},
"timeline": {
"loading": "Cargando...",
- "jump_to_latest": "Ir a lo más reciente"
+ "jump_to_latest": "Ir a lo más reciente",
+ "new_comments_one": "{{count}} comentario nuevo",
+ "new_comments_other": "{{count}} comentarios nuevos"
},
"activity": {
"created": "creó esta tarea",
diff --git a/packages/views/locales/fr/chat.json b/packages/views/locales/fr/chat.json
index c33a602a4f..c533f1f044 100644
--- a/packages/views/locales/fr/chat.json
+++ b/packages/views/locales/fr/chat.json
@@ -52,6 +52,8 @@
"action_failed_toast": "Impossible de mettre à jour le message en file d'attente"
},
"message_list": {
+ "jump_to_latest": "Aller au plus récent",
+ "new_reply": "Nouvelle réponse",
"show_details": "Afficher les détails",
"replied_in": "Réponse en {{elapsed}}",
"failed_after": "Échec après {{elapsed}}",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index f19f45a94c..06512a6d32 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -587,7 +587,9 @@
},
"timeline": {
"loading": "Chargement...",
- "jump_to_latest": "Aller au plus récent"
+ "jump_to_latest": "Aller au plus récent",
+ "new_comments_one": "{{count}} nouveau commentaire",
+ "new_comments_other": "{{count}} nouveaux commentaires"
},
"activity": {
"created": "a créé cette tâche",
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index bbeb6ef094..c92dcbbd71 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -50,6 +50,8 @@
"action_failed_toast": "キュー内のメッセージを更新できませんでした"
},
"message_list": {
+ "jump_to_latest": "最新に移動",
+ "new_reply": "新しい返信",
"show_details": "詳細を表示",
"replied_in": "{{elapsed}}で返信",
"failed_after": "{{elapsed}}後に失敗",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 9399ee5195..8f8f5d6bc8 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -579,7 +579,8 @@
},
"timeline": {
"loading": "読み込み中...",
- "jump_to_latest": "最新に移動"
+ "jump_to_latest": "最新に移動",
+ "new_comments_other": "新しいコメント {{count}} 件"
},
"activity": {
"created": "このタスクを作成しました",
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index d2369bafa4..0135d666e2 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -50,6 +50,8 @@
"action_failed_toast": "대기 중인 메시지를 업데이트하지 못했습니다"
},
"message_list": {
+ "jump_to_latest": "최신으로 이동",
+ "new_reply": "새 답장",
"show_details": "세부 정보 보기",
"replied_in": "{{elapsed}} 만에 답변",
"failed_after": "{{elapsed}} 후 실패",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index f670120449..19b5e16a93 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -579,7 +579,8 @@
},
"timeline": {
"loading": "불러오는 중...",
- "jump_to_latest": "최신으로 이동"
+ "jump_to_latest": "최신으로 이동",
+ "new_comments_other": "새 댓글 {{count}}개"
},
"activity": {
"created": "이 태스크를 만들었습니다",
diff --git a/packages/views/locales/ru/chat.json b/packages/views/locales/ru/chat.json
index 0c11746c32..caa732b9d3 100644
--- a/packages/views/locales/ru/chat.json
+++ b/packages/views/locales/ru/chat.json
@@ -56,6 +56,8 @@
"title_many": "{{count}} сообщений в очереди"
},
"message_list": {
+ "jump_to_latest": "К последним сообщениям",
+ "new_reply": "Новый ответ",
"show_details": "Показать детали",
"replied_in": "Ответ за {{elapsed}}",
"failed_after": "Ошибка через {{elapsed}}",
diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.json
index 6d40bfdc14..625a44b57f 100644
--- a/packages/views/locales/ru/issues.json
+++ b/packages/views/locales/ru/issues.json
@@ -602,7 +602,11 @@
},
"timeline": {
"loading": "Загрузка...",
- "jump_to_latest": "К последним событиям"
+ "jump_to_latest": "К последним событиям",
+ "new_comments_one": "{{count}} новый комментарий",
+ "new_comments_few": "{{count}} новых комментария",
+ "new_comments_many": "{{count}} новых комментариев",
+ "new_comments_other": "{{count}} новых комментария"
},
"activity": {
"created": "создал(а) эту задачу",
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index 89852a1846..5db9814af4 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -50,6 +50,8 @@
"action_failed_toast": "无法更新排队消息"
},
"message_list": {
+ "jump_to_latest": "跳到最新",
+ "new_reply": "新回复",
"show_details": "查看详情",
"replied_in": "{{elapsed}} 内回复",
"failed_after": "{{elapsed}} 后失败",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 2b13e9f3fd..92bd6ea8ca 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -579,7 +579,8 @@
},
"timeline": {
"loading": "加载中…",
- "jump_to_latest": "跳到最新"
+ "jump_to_latest": "跳到最新",
+ "new_comments_other": "{{count}} 条新评论"
},
"activity": {
"created": "创建了这个任务",
diff --git a/packages/views/locales/zh-Hant/chat.json b/packages/views/locales/zh-Hant/chat.json
index 0a09045da0..5a2fadf0e5 100644
--- a/packages/views/locales/zh-Hant/chat.json
+++ b/packages/views/locales/zh-Hant/chat.json
@@ -50,6 +50,8 @@
"action_failed_toast": "無法更新排隊訊息"
},
"message_list": {
+ "jump_to_latest": "跳到最新",
+ "new_reply": "新回覆",
"show_details": "檢視詳情",
"replied_in": "{{elapsed}} 內回覆",
"failed_after": "{{elapsed}} 後失敗",
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index 298186776d..c13f0a3e21 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -579,7 +579,8 @@
},
"timeline": {
"loading": "載入中…",
- "jump_to_latest": "跳到最新"
+ "jump_to_latest": "跳到最新",
+ "new_comments_other": "{{count}} 則新評論"
},
"activity": {
"created": "建立了這個任務",