Skip to content

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

Go

fix(transcript): auto-follow live task output in transcript dialog (#5932)

Rusty Raven67d3952ee202
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index 5943d5779e..859f051e9b 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useRef, useCallback, useEffect, useMemo, forwardRef } from "react";
+import { useState, useRef, useCallback, useEffect, useLayoutEffect, useMemo, forwardRef } from "react";
import { Virtuoso, type VirtuosoHandle, type Components } from "react-virtuoso";
import {
Bot,
@@ -49,6 +49,11 @@ import {
import type { AgentTask, Agent, AgentRuntime } from "@multica/core/types/agent";
import { runtimeDisplayName } from "@multica/core/runtimes";
import { redactSecrets } from "./redact";
+import {
+ createNewestFirstFollow,
+ FOLLOW_EDGE_THRESHOLD,
+ LINE_SCROLL_PX,
+} from "./transcript-follow";
import type { TimelineItem } from "./build-timeline";
import {
traceEventCopyText,
@@ -234,6 +239,86 @@ export function AgentTranscriptDialog({
const density = useTranscriptViewStore((s) => s.density);
const setDensity = useTranscriptViewStore((s) => s.setDensity);
const virtuosoRef = useRef<VirtuosoHandle>(null);
+ // Newest-first live follow (#5921): all latch decisions live in the pure
+ // controller (see transcript-follow.ts for the model); this component only
+ // wires DOM events to it. A stable instance, never re-rendered by scroll
+ // traffic.
+ const followCtl = useMemo(() => createNewestFirstFollow(), []);
+ const detachScrollerRef = useRef<(() => void) | null>(null);
+
+ const handleScrollerRef = useCallback(
+ (el: HTMLElement | Window | null) => {
+ detachScrollerRef.current?.();
+ detachScrollerRef.current = null;
+ if (!(el instanceof HTMLElement)) return;
+ const onWheel = (e: WheelEvent) => {
+ const scale =
+ e.deltaMode === 1 ? LINE_SCROLL_PX : e.deltaMode === 2 ? el.clientHeight : 1;
+ followCtl.input(e.deltaY * scale);
+ };
+ let lastTouchY: number | null = null;
+ const onTouchStart = (e: TouchEvent) => {
+ lastTouchY = e.touches[0]?.clientY ?? null;
+ };
+ const onTouchMove = (e: TouchEvent) => {
+ const y = e.touches[0]?.clientY;
+ if (y === undefined) return;
+ // Finger moving up scrolls the content down (away from the live end).
+ if (lastTouchY !== null) followCtl.input(lastTouchY - y);
+ lastTouchY = y;
+ };
+ const onKeyDown = (e: KeyboardEvent) => {
+ // Only keys aimed at the scroller itself; Space/arrows bubbling from
+ // row controls (e.g. a collapsible trigger) are not scroll intent.
+ if (e.target !== el) return;
+ if (e.key === "ArrowDown") followCtl.input(LINE_SCROLL_PX);
+ else if (e.key === "ArrowUp") followCtl.input(-LINE_SCROLL_PX);
+ else if (e.key === "PageDown" || e.key === " ") followCtl.input(el.clientHeight);
+ else if (e.key === "PageUp") followCtl.input(-el.clientHeight);
+ else if (e.key === "End") followCtl.disengage();
+ };
+ // Scrollbar drags hit the scroller element itself; clicks on row
+ // content hit children (tracked too — enforcement must not fight text
+ // selection autoscroll while the button is held).
+ const onPointerDown = (e: MouseEvent) => {
+ followCtl.pointerDown(e.target === el);
+ };
+ const onPointerUp = () => {
+ followCtl.pointerUp();
+ };
+ const onScroll = () => {
+ // Enforce the follow here, on the scroll event itself: Virtuoso's
+ // prepend compensation lands after React effects, so an effect-timed
+ // snap alone stays one flush behind. NOTE: this direct write staying
+ // ahead of Virtuoso's own state relies on react-virtuoso registering
+ // its scroll listener after calling scrollerRef (true in 4.18.7); if
+ // that inverts, route the write through virtuosoRef.scrollTo instead.
+ if (followCtl.onScroll(el.scrollTop)) el.scrollTop = 0;
+ };
+ el.addEventListener("wheel", onWheel, { passive: true });
+ el.addEventListener("touchstart", onTouchStart, { passive: true });
+ el.addEventListener("touchmove", onTouchMove, { passive: true });
+ el.addEventListener("keydown", onKeyDown);
+ el.addEventListener("mousedown", onPointerDown);
+ window.addEventListener("mouseup", onPointerUp, { capture: true });
+ el.addEventListener("scroll", onScroll, { passive: true });
+ detachScrollerRef.current = () => {
+ el.removeEventListener("wheel", onWheel);
+ el.removeEventListener("touchstart", onTouchStart);
+ el.removeEventListener("touchmove", onTouchMove);
+ el.removeEventListener("keydown", onKeyDown);
+ el.removeEventListener("mousedown", onPointerDown);
+ window.removeEventListener("mouseup", onPointerUp, { capture: true });
+ el.removeEventListener("scroll", onScroll);
+ // The scroller can detach mid-drag (listEpoch remount); a stuck
+ // held-mouse flag would suppress enforcement forever.
+ followCtl.pointerUp();
+ };
+ },
+ [followCtl],
+ );
+
+ useEffect(() => () => detachScrollerRef.current?.(), []);
useEffect(() => {
setRowOverrides(new Map());
@@ -311,6 +396,31 @@ export function AgentTranscriptDialog({
[sortDirection, setSortDirection],
);
+ useLayoutEffect(() => {
+ followCtl.setActive(isLive && sortDirection === "newest_first");
+ }, [followCtl, isLive, sortDirection]);
+
+ // A new list instance (task/sort/filter change) mounts at its live end with
+ // the follow engaged — the same contract as first open.
+ useLayoutEffect(() => {
+ followCtl.reset();
+ }, [followCtl, listEpoch]);
+
+ // Live follow for newest-first (#5921): while the latch is engaged, every
+ // flush snaps back to the newest row — prepend anchoring would otherwise
+ // hold the viewport on the previous first row. Instant (not smooth): a
+ // smooth animation spans multiple flushes and its in-flight position reads
+ // as user displacement. The scroll-event enforcement in handleScrollerRef
+ // is the authoritative pin (Virtuoso's prepend compensation lands after
+ // React effects); this effect just shortens the first-paint gap.
+ // Chronological live follow is handled natively by Virtuoso's followOutput
+ // below; this pair is its prepend-side counterpart.
+ const displayCount = displayItems.length;
+ useLayoutEffect(() => {
+ if (!followCtl.isFollowing()) return;
+ virtuosoRef.current?.scrollToIndex({ index: 0, align: "start", behavior: "auto" });
+ }, [followCtl, displayCount]);
+
// Fetch agent and runtime metadata when dialog opens
useEffect(() => {
if (!open) return;
@@ -350,9 +460,13 @@ export function AgentTranscriptDialog({
setSelectedSeq(seq);
const index = displayItems.findIndex((item) => item.seq === seq);
if (index < 0) return;
+ // Explicit navigation away from the live end unlatches the newest-first
+ // follow — otherwise the scroll-event enforcement would pin the viewport
+ // straight back to the top. Scrolling back re-engages it as usual.
+ if (index > 0) followCtl.disengage();
virtuosoRef.current?.scrollToIndex({ index, align: "center", behavior: "smooth" });
},
- [displayItems],
+ [displayItems, followCtl],
);
// Copy all events as text. Use the displayed order so users get the same
@@ -801,6 +915,33 @@ export function AgentTranscriptDialog({
style={{ height: "100%" }}
data={displayItems}
firstItemIndex={firstItemIndex}
+ // Open a live chronological transcript pinned to the newest
+ // event (#5921); the per-listEpoch remount re-applies this after
+ // task / sort / filter changes. Completed tasks keep reading
+ // from the top, and newest-first has its live end there already.
+ initialTopMostItemIndex={
+ isLive && sortDirection !== "newest_first"
+ ? { index: "LAST", align: "end" }
+ : 0
+ }
+ // Follow appended events while the reader is at the bottom;
+ // scrolling up suspends the follow until they return (#5921).
+ // Instant, not smooth: transcript flushes append several rows at
+ // a time and a still-animating scroll makes the next evaluation
+ // read "not at bottom", permanently dropping the follow.
+ // Newest-first opts out — its growth is prepends, handled by the
+ // scrollToIndex effect above.
+ followOutput={(atBottom) =>
+ isLive && sortDirection !== "newest_first" && atBottom ? "auto" : false
+ }
+ atBottomThreshold={FOLLOW_EDGE_THRESHOLD}
+ atTopThreshold={FOLLOW_EDGE_THRESHOLD}
+ // Back within the top zone (any way you got there) re-engages
+ // the newest-first follow. Leaving it does NOT disengage:
+ // anchored prepends leave the top zone on their own — only
+ // accumulated user input may break the latch (transcript-follow.ts).
+ atTopStateChange={(atTop) => followCtl.onAtTopChange(atTop)}
+ scrollerRef={handleScrollerRef}
computeItemKey={(_, item) => item.seq}
components={LIST_COMPONENTS}
itemContent={(_, item) => (
diff --git a/packages/views/common/task-transcript/transcript-follow.test.ts b/packages/views/common/task-transcript/transcript-follow.test.ts
new file mode 100644
index 0000000000..ae7cba0763
--- /dev/null
+++ b/packages/views/common/task-transcript/transcript-follow.test.ts
@@ -0,0 +1,122 @@
+import { describe, it, expect } from "vitest";
+import { createNewestFirstFollow, FOLLOW_EDGE_THRESHOLD } from "./transcript-follow";
+
+function makeFollow(startAt = 0) {
+ let t = startAt;
+ const follow = createNewestFirstFollow(() => t);
+ const tick = (ms: number) => {
+ t += ms;
+ };
+ follow.setActive(true);
+ return { follow, tick };
+}
+
+describe("createNewestFirstFollow", () => {
+ it("starts following and pins system displacement back to the live end", () => {
+ const { follow, tick } = makeFollow();
+ tick(1000);
+ // A prepend-anchoring shift: no user input at all.
+ expect(follow.onScroll(500)).toBe(true);
+ expect(follow.isFollowing()).toBe(true);
+ });
+
+ it("does not disengage when a prepend shift lands inside the input window after an in-zone nudge", () => {
+ // Regression: absolute-position heuristics dropped the latch here — the
+ // user nudged 30px (still inside the zone), then a flush pushed the
+ // viewport past the threshold while their input was still fresh.
+ const { follow, tick } = makeFollow();
+ tick(1000);
+ follow.input(30);
+ tick(200); // inside the intent window
+ expect(follow.onScroll(500)).toBe(false); // user mid-gesture: no pin either
+ expect(follow.isFollowing()).toBe(true);
+ tick(400); // gesture over
+ expect(follow.onScroll(500)).toBe(true); // now pin back
+ expect(follow.isFollowing()).toBe(true);
+ });
+
+ it("disengages on accumulated user input beyond the threshold", () => {
+ const { follow } = makeFollow();
+ follow.input(80);
+ expect(follow.isFollowing()).toBe(true);
+ follow.input(80); // cumulative 160 > threshold
+ expect(follow.isFollowing()).toBe(false);
+ expect(follow.onScroll(400)).toBe(false); // no pinning once disengaged
+ });
+
+ it("upward input rolls the accumulator back instead of counting as intent", () => {
+ const { follow } = makeFollow();
+ follow.input(100);
+ follow.input(-90);
+ follow.input(100); // net 110 <= threshold
+ expect(follow.isFollowing()).toBe(true);
+ });
+
+ it("a pin clears sub-threshold residue so old nudges cannot accumulate", () => {
+ const { follow, tick } = makeFollow();
+ follow.input(100);
+ tick(1000);
+ expect(follow.onScroll(300)).toBe(true); // pinned; residue cleared
+ follow.input(100); // fresh gesture: 100 <= threshold on its own
+ expect(follow.isFollowing()).toBe(true);
+ });
+
+ it("re-engages when the viewport returns to the top zone", () => {
+ const { follow } = makeFollow();
+ follow.input(FOLLOW_EDGE_THRESHOLD + 1);
+ expect(follow.isFollowing()).toBe(false);
+ follow.onAtTopChange(true);
+ expect(follow.isFollowing()).toBe(true);
+ });
+
+ it("scrollbar drag past the threshold disengages", () => {
+ const { follow } = makeFollow();
+ follow.pointerDown(true);
+ expect(follow.onScroll(80)).toBe(false); // still in zone
+ expect(follow.isFollowing()).toBe(true);
+ follow.onScroll(200);
+ expect(follow.isFollowing()).toBe(false);
+ follow.pointerUp();
+ });
+
+ it("never pins while the mouse is held on row content (text selection autoscroll)", () => {
+ // Regression: selection-drag autoscroll has no wheel/touch input; pinning
+ // during it made text below the fold unselectable.
+ const { follow, tick } = makeFollow();
+ tick(1000);
+ follow.pointerDown(false); // mousedown on a row, not the scrollbar
+ expect(follow.onScroll(600)).toBe(false);
+ expect(follow.isFollowing()).toBe(true); // content drag is not scroll intent
+ follow.pointerUp();
+ expect(follow.onScroll(600)).toBe(true); // released: enforcement resumes
+ });
+
+ it("explicit disengage (segment navigation) stops the pinning", () => {
+ const { follow, tick } = makeFollow();
+ follow.disengage();
+ tick(1000);
+ expect(follow.isFollowing()).toBe(false);
+ expect(follow.onScroll(300)).toBe(false);
+ });
+
+ it("reset re-engages and clears held-pointer state", () => {
+ const { follow, tick } = makeFollow();
+ follow.pointerDown(false);
+ follow.input(500);
+ follow.reset();
+ tick(1000);
+ expect(follow.isFollowing()).toBe(true);
+ expect(follow.onScroll(50)).toBe(true); // mouseHeld cleared by reset
+ });
+
+ it("is fully inert when inactive (chronological or completed task)", () => {
+ const { follow, tick } = makeFollow();
+ follow.setActive(false);
+ tick(1000);
+ expect(follow.isFollowing()).toBe(false);
+ expect(follow.onScroll(500)).toBe(false);
+ follow.input(500); // ignored
+ follow.setActive(true);
+ expect(follow.isFollowing()).toBe(true); // latch untouched while inactive
+ });
+});
diff --git a/packages/views/common/task-transcript/transcript-follow.ts b/packages/views/common/task-transcript/transcript-follow.ts
new file mode 100644
index 0000000000..3563828116
--- /dev/null
+++ b/packages/views/common/task-transcript/transcript-follow.ts
@@ -0,0 +1,117 @@
+// Live-follow latch for the newest-first transcript (#5921).
+//
+// Newest-first shows live events as PREPENDS, and the list's firstItemIndex
+// anchoring holds the viewport across a prepend — which means every flush
+// moves the viewport away from the top on its own. "Am I at the top right
+// now" therefore cannot distinguish a reader who scrolled away from one the
+// anchoring pushed down. This controller keeps that distinction:
+//
+// - Follow disengages only on accumulated USER displacement away from the
+// live end (wheel/touch/key deltas, or a scrollbar drag) beyond the edge
+// threshold. System displacement never counts, no matter how far it moves
+// the viewport.
+// - While following, any non-user displacement is pinned straight back to
+// the live end (`pin` from onScroll) — but never while the user is
+// mid-gesture or holding the mouse down (text selection autoscroll must
+// not be fought).
+// - Arriving back within the edge zone (atTop) re-engages the follow.
+//
+// Pure state machine so the decision table is unit-testable; the dialog owns
+// wiring it to DOM events.
+
+// Forgiving "at the live end" zone, matching the chat list's atBottomThreshold:
+// within this distance of the live edge the reader counts as following.
+export const FOLLOW_EDGE_THRESHOLD = 120;
+
+// How long after the last wheel/touch/key input the viewport is still treated
+// as user-controlled (suppresses pinning mid-gesture, including momentum).
+const INPUT_INTENT_WINDOW_MS = 300;
+
+// WheelEvent.deltaMode 1 (lines) / 2 (pages) conversion.
+export const LINE_SCROLL_PX = 40;
+
+export interface NewestFirstFollow {
+ /** `isLive && sortDirection === "newest_first"`; everything is inert otherwise. */
+ setActive(active: boolean): void;
+ /** New list instance (task/sort/filter change): back to following. */
+ reset(): void;
+ isFollowing(): boolean;
+ /** Explicit navigation away from the live end (e.g. timeline segment click). */
+ disengage(): void;
+ /** User scroll input in px; positive = away from the live end. */
+ input(delta: number): void;
+ /** Mousedown inside the scroller; `onScroller` = on the element itself (scrollbar). */
+ pointerDown(onScroller: boolean): void;
+ pointerUp(): void;
+ onAtTopChange(atTop: boolean): void;
+ /** Every scroll event. Returns whether to pin the viewport back to the top. */
+ onScroll(scrollTop: number): boolean;
+}
+
+export function createNewestFirstFollow(now: () => number = () => Date.now()): NewestFirstFollow {
+ let active = false;
+ let following = true;
+ // Accumulated user-caused displacement away from the live end. Compared
+ // against the edge threshold instead of scrollTop: absolute position mixes
+ // user and system displacement (a prepend can land inside the intent
+ // window and push the viewport past any threshold on its own).
+ let pendingAway = 0;
+ let lastInputAt = -INPUT_INTENT_WINDOW_MS;
+ let mouseHeld = false;
+ let scrollbarDrag = false;
+
+ const userControlsViewport = () =>
+ mouseHeld || scrollbarDrag || now() - lastInputAt < INPUT_INTENT_WINDOW_MS;
+
+ return {
+ setActive(a: boolean) {
+ active = a;
+ },
+ reset() {
+ following = true;
+ pendingAway = 0;
+ mouseHeld = false;
+ scrollbarDrag = false;
+ },
+ isFollowing: () => active && following,
+ disengage() {
+ if (active) following = false;
+ },
+ input(delta: number) {
+ if (!active) return;
+ lastInputAt = now();
+ pendingAway = Math.max(0, pendingAway + delta);
+ if (following && pendingAway > FOLLOW_EDGE_THRESHOLD) following = false;
+ },
+ pointerDown(onScroller: boolean) {
+ if (!active) return;
+ mouseHeld = true;
+ if (onScroller) scrollbarDrag = true;
+ },
+ pointerUp() {
+ mouseHeld = false;
+ scrollbarDrag = false;
+ },
+ onAtTopChange(atTop: boolean) {
+ if (!active || !atTop) return;
+ following = true;
+ pendingAway = 0;
+ },
+ onScroll(scrollTop: number): boolean {
+ if (!active) return false;
+ // A scrollbar drag is fully user-controlled: absolute position is the
+ // user's displacement, so the plain threshold applies.
+ if (scrollbarDrag && scrollTop > FOLLOW_EDGE_THRESHOLD) {
+ following = false;
+ return false;
+ }
+ if (following && !userControlsViewport() && scrollTop > 0) {
+ // System displacement got corrected; drop any sub-threshold residue
+ // so old nudges don't accumulate into a spurious disengage later.
+ pendingAway = 0;
+ return true;
+ }
+ return false;
+ },
+ };
+}