Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(ui): fold runs of Harness messages in the chat transcript (#3118)

Call Whited05c1c4137a0
diff --git a/docs/plans/workbench-refinements.md b/docs/plans/workbench-refinements.md
index 82d91ac6d..522a48c2f 100644
--- a/docs/plans/workbench-refinements.md
+++ b/docs/plans/workbench-refinements.md
@@ -286,23 +286,38 @@ it is still delivered, listed, and unread.
that Turn ends without a reply its chip joins the group; if it replies, the
reply closes the group.
- A single row that becomes a run of two forms a collapsed group, unless that
- row was expanded, in which case the group starts expanded.
+ row was expanded, in which case the group starts expanded: what the reader is
+ reading is never folded away, and the content around it does not jump.
+ Closing that row afterwards keeps the group open; closing the group closes its
+ rows.
- Unread: Harness inputs are never unread (only `result` is), so groups carry no
unread mark and change no counts. Opening a Session still lands at the tail.
- Scroll: toggling keeps the group header in place (the existing anchor logic);
a reader following the tail stays pinned; a jump or search target inside a
group expands that group before scrolling and highlights the row; older pages
- prepended above can grow a group at its top.
-- State: the set of expanded member ids, in memory for the open Session. A
- group is expanded when any member is in the set, so growth at either end
- keeps its state. Nothing is persisted.
+ prepended above can grow a group at its top. A group keeps its element as it
+ grows at either end, so a scroll anchor held on it survives, and the anchor
+ search accepts a row that stands for several messages
+ (`data-transcript-row`). The anchor also names the message it holds, so a
+ row that an older page turns into a group member keeps its place: it is found
+ again inside the opened group, or the collapsed head takes its place
+ (`data-harness-members`). Closing a group from below its head (its trailing
+ control) brings the head back to the top of the view, since the anchored row
+ went with the members.
+- State: the set of expanded member ids and the set of opened Harness rows, in
+ memory for the open Session. A group is expanded when any member is in the
+ first set, so growth at either end keeps its state. Nothing is persisted.
- Web transcript only: search, copy, Retry eligibility, the API, and IM are
unchanged.
### Code that changes
-- `ChatPage.tsx` `Transcript`: render items instead of raw messages, route the
- members' after-chips into their group, and expand on jump.
-- A new `HarnessGroup` component reusing the Harness row and `ActivityChip`; a
- new `ui/src/lib/harnessGroups.ts` with unit tests for the break rules, the
- first-message rule, live growth, and anchor routing; `en`/`zh` strings.
+- `ChatPage.tsx` `Transcript`: render items instead of raw messages; an open
+ group draws its members, with their Activity chips, through the same row
+ rendering as any other row; expand on jump.
+- `ui/src/lib/harnessGroups.ts`: `groupHarnessRuns` and
+ `stableHarnessGroupKeys`, with unit tests for the break rules, the
+ first-message rule, and key stability.
+- A new `HarnessGroup` component for the group head and the collapsed stack;
+ `ui/src/lib/transcriptScrollAnchor.ts` accepts `data-transcript-row`;
+ `en`/`zh` strings.
diff --git a/ui/src/components/workbench/ChatHarnessGroups.test.tsx b/ui/src/components/workbench/ChatHarnessGroups.test.tsx
new file mode 100644
index 000000000..0a57e61c5
--- /dev/null
+++ b/ui/src/components/workbench/ChatHarnessGroups.test.tsx
@@ -0,0 +1,288 @@
+/** @vitest-environment jsdom */
+
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MemoryRouter } from 'react-router-dom';
+import { createRef, type ComponentProps } from 'react';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { count?: number }) => (options?.count === undefined ? key : `${key}:${options.count}`),
+ }),
+}));
+vi.mock('../../context/ApiContext', () => ({ useApi: () => ({}) }));
+vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));
+vi.mock('../../context/InstanceAuthorizationContext', () => ({
+ useInstanceAuthorization: () => ({
+ capabilities: { can_chat: true, can_manage_instance: false, can_use_show_pages: false, can_use_vault_secrets: false },
+ }),
+}));
+vi.mock('../../context/WindowManagerContext', () => ({
+ useWindowManager: () => ({ focusedId: null, focusCanvas: vi.fn() }),
+}));
+vi.mock('../../lib/useIsDesktop', () => ({ isDesktopViewport: () => false, useIsDesktop: () => false }));
+vi.mock('./Composer', () => ({ Composer: () => null }));
+
+import { Transcript } from './ChatPage';
+import type { WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
+import type { ActivityGroup } from '../../lib/agentActivity';
+
+type Props = ComponentProps<typeof Transcript>;
+
+let clock = 0;
+const message = (id: string, over: Partial<WorkbenchMessage>): WorkbenchMessage =>
+ ({
+ id,
+ session_id: 'session-1',
+ platform: 'avibe',
+ content: {},
+ metadata: {},
+ created_at: new Date(Date.UTC(2026, 9, 30, 4, 0, clock++)).toISOString(),
+ ...over,
+ }) as WorkbenchMessage;
+const watch = (id: string) =>
+ message(id, { author: 'harness', source: 'harness', type: 'harness', author_name: 'watch', text: `Watch ${id} finished` });
+const userMessage = (id: string) => message(id, { author: 'user', source: 'user', type: 'user', text: `User ${id}` });
+const reply = (id: string) => message(id, { author: 'agent', source: 'agent', type: 'result', text: `Reply ${id}` });
+
+const chip = (id: string, anchorMessageId: string, anchorPosition: 'before' | 'after'): ActivityGroup => ({
+ id,
+ anchorMessageId,
+ anchorPosition,
+ open: false,
+ status: 'done',
+ steps: 3,
+ durationMs: 1000,
+});
+
+const activity = (groups: ActivityGroup[]): NonNullable<Props['activity']> => {
+ const before = new Map<string, ActivityGroup[]>();
+ const after = new Map<string, ActivityGroup[]>();
+ for (const group of groups) (group.anchorPosition === 'before' ? before : after).set(group.anchorMessageId!, [group]);
+ return {
+ enabled: true,
+ beforeAnchor: before,
+ afterAnchor: after,
+ topGroups: [],
+ liveRows: [],
+ liveStartedAt: null,
+ cardExpanded: false,
+ onToggleCard: vi.fn(),
+ expanded: {},
+ loading: {},
+ error: {},
+ onToggleGroup: vi.fn(),
+ onRetryGroup: vi.fn(),
+ showToolCalls: false,
+ onToggleTools: vi.fn(),
+ };
+};
+
+const renderTranscript = (over: Partial<Props>) => {
+ const props: Props = {
+ messages: [],
+ session: { id: 'session-1', title: 'Session', agent_name: null, archived_at: null } as WorkbenchSession,
+ agentDisplayName: null,
+ working: false,
+ hasOlder: false,
+ loadingOlder: false,
+ onLoadOlder: vi.fn().mockResolvedValue(true),
+ needsLatestReload: false,
+ onReloadLatest: vi.fn().mockResolvedValue(true),
+ jumpTarget: null,
+ onJumpHandled: vi.fn(),
+ highlightedId: null,
+ messageFontSize: 14,
+ onQuickReply: vi.fn(),
+ provisionRequestsByMessage: new Map(),
+ onVaultRequestResolved: vi.fn(),
+ onQuoteSelection: vi.fn(),
+ onAskInNewSession: vi.fn(),
+ readOnly: false,
+ followingTailRef: createRef<boolean>() as React.MutableRefObject<boolean>,
+ ...over,
+ };
+ const view = render(<MemoryRouter><Transcript {...props} /></MemoryRouter>);
+ const rerender = (next: Partial<Props>) => {
+ Object.assign(props, next);
+ view.rerender(<MemoryRouter><Transcript {...props} /></MemoryRouter>);
+ };
+ return { ...view, rerender };
+};
+
+const groupToggle = (count: number) => screen.getByRole('button', { name: `chat.harnessGroup.count:${count}` });
+const rendered = (id: string) => document.querySelector(`[data-message-id="${id}"]`);
+
+describe('transcript Harness groups', () => {
+ beforeEach(() => {
+ clock = 0;
+ vi.stubGlobal('CSS', { escape: (value: string) => value });
+ vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
+ vi.stubGlobal('IntersectionObserver', class { observe() {} disconnect() {} unobserve() {} });
+ vi.stubGlobal('requestAnimationFrame', () => 0);
+ vi.stubGlobal('cancelAnimationFrame', () => {});
+ });
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ it('folds a run with its silent Turns and opens it in place', () => {
+ const brief = watch('brief');
+ const members = [watch('h1'), watch('h2'), watch('h3')];
+ const answer = reply('r1');
+ renderTranscript({
+ messages: [brief, ...members, answer],
+ activity: activity([chip('silent-1', 'h1', 'after'), chip('answering', 'r1', 'before')]),
+ });
+
+ // The Session's opening brief stays its own row; the three after it fold.
+ expect(rendered('brief')).toBeTruthy();
+ const toggle = groupToggle(3);
+ expect(toggle.getAttribute('aria-expanded')).toBe('false');
+ expect(toggle.textContent).toContain('Watch h3 finished');
+ for (const { id } of members) expect(rendered(id)).toBeNull();
+ // A silent Turn's chip folds with its trigger; the reply's own chip does not.
+ expect(screen.getAllByText(/chat\.agentActivity\.label/)).toHaveLength(1);
+
+ fireEvent.click(toggle);
+ expect(groupToggle(3).getAttribute('aria-expanded')).toBe('true');
+ for (const { id } of members) expect(rendered(id)).toBeTruthy();
+ expect(screen.getAllByText(/chat\.agentActivity\.label/)).toHaveLength(2);
+
+ fireEvent.click(screen.getByRole('button', { name: /chat\.harnessGroup\.collapseCount:3/ }));
+ for (const { id } of members) expect(rendered(id)).toBeNull();
+ });
+
+ it('grows in place as Harness messages arrive and as older ones load', () => {
+ const view = renderTranscript({ messages: [userMessage('u1'), watch('h3'), watch('h4')], hasOlder: true });
+ const row = groupToggle(2).closest('[data-transcript-row]');
+
+ view.rerender({ messages: [userMessage('u1'), watch('h3'), watch('h4'), watch('h5')] });
+ expect(groupToggle(3).getAttribute('aria-expanded')).toBe('false');
+ expect(groupToggle(3).textContent).toContain('Watch h5 finished');
+ // The same element, so a scroll anchor held on it survives the growth.
+ expect(groupToggle(3).closest('[data-transcript-row]')).toBe(row);
+
+ fireEvent.click(groupToggle(3));
+ view.rerender({ messages: [watch('h1'), watch('h2'), watch('h3'), watch('h4'), watch('h5'), watch('h6')] });
+ expect(groupToggle(6).getAttribute('aria-expanded')).toBe('true');
+ expect(groupToggle(6).closest('[data-transcript-row]')).toBe(row);
+ expect(rendered('h1')).toBeTruthy();
+ expect(rendered('h6')).toBeTruthy();
+ });
+
+ it('opens the group a jump lands in and keeps it open afterwards', () => {
+ const messages = [userMessage('u1'), watch('h1'), watch('h2'), watch('h3'), reply('r1')];
+ const view = renderTranscript({ messages });
+ expect(rendered('h2')).toBeNull();
+
+ act(() => view.rerender({ jumpTarget: 'h2', highlightedId: 'h2' }));
+ expect(rendered('h2')).toBeTruthy();
+
+ act(() => view.rerender({ jumpTarget: null, highlightedId: null }));
+ expect(rendered('h2')).toBeTruthy();
+ expect(groupToggle(3).getAttribute('aria-expanded')).toBe('true');
+ });
+
+ it('keeps the row a reader opened in view when the next Harness message folds it', () => {
+ const view = renderTranscript({ messages: [userMessage('u1'), watch('h1')], hasOlder: true });
+ const chipOf = (id: string) => rendered(id)!.querySelector<HTMLButtonElement>('button[aria-expanded]')!;
+ fireEvent.click(chipOf('h1'));
+ expect(chipOf('h1').getAttribute('aria-expanded')).toBe('true');
+
+ view.rerender({ messages: [userMessage('u1'), watch('h1'), watch('h2')] });
+ // The group opens in place: the row being read stays where it was, still open.
+ expect(groupToggle(2).getAttribute('aria-expanded')).toBe('true');
+ expect(chipOf('h1').getAttribute('aria-expanded')).toBe('true');
+ expect(rendered('h2')).toBeTruthy();
+
+ // Closing that row does not fold the group out from under the reader.
+ fireEvent.click(chipOf('h1'));
+ expect(groupToggle(2).getAttribute('aria-expanded')).toBe('true');
+
+ // Closing the group closes its rows, so reopening it starts them closed.
+ fireEvent.click(chipOf('h1'));
+ fireEvent.click(groupToggle(2));
+ expect(rendered('h1')).toBeNull();
+ fireEvent.click(groupToggle(2));
+ expect(chipOf('h1').getAttribute('aria-expanded')).toBe('false');
+ });
+
+ it('brings a group closed from below its head back to the top of the view', () => {
+ const members = Array.from({ length: 12 }, (_, index) => watch(`h${index + 1}`));
+ const view = renderTranscript({ messages: [userMessage('u1'), ...members, reply('r1')] });
+ fireEvent.click(groupToggle(12));
+
+ // jsdom has no layout: every direct child of the transcript column is 100px
+ // tall, stacked in DOM order, and the viewport is 800px tall at the top.
+ const scroller = view.getByTestId('chat-transcript');
+ const column = scroller.firstElementChild!;
+ let scrollTop = 0;
+ Object.defineProperties(scroller, {
+ clientHeight: { configurable: true, get: () => 800 },
+ scrollHeight: { configurable: true, get: () => column.children.length * 100 },
+ scrollTop: { configurable: true, get: () => scrollTop, set: (value: number) => { scrollTop = Math.max(0, value); } },
+ });
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
+ if (this === scroller) return { top: 0, bottom: 800, height: 800 } as DOMRect;
+ const index = Array.prototype.indexOf.call(column.children, this);
+ const top = index < 0 ? 0 : index * 100 - scrollTop;
+ return { top, bottom: top + 90, height: 90 } as DOMRect;
+ });
+
+ // Read down into the open group: its head (row 1) is far above the viewport.
+ fireEvent.pointerDown(scroller);
+ scroller.scrollTop = 500;
+ fireEvent.scroll(scroller);
+ fireEvent.click(screen.getByRole('button', { name: /chat\.harnessGroup\.collapseCount:12/ }));
+
+ expect(groupToggle(12).getAttribute('aria-expanded')).toBe('false');
+ // The collapsed group now sits at the top of the viewport, not off-screen above it.
+ expect(scrollTop).toBe(100);
+ });
+
+ // jsdom has no layout: every direct child of the transcript column is 100px
+ // tall, stacked in DOM order, and a nested element sits at its top-level
+ // ancestor's place. The viewport is 800px tall.
+ const layOut = (scroller: HTMLElement) => {
+ const column = scroller.firstElementChild!;
+ let scrollTop = 0;
+ Object.defineProperties(scroller, {
+ clientHeight: { configurable: true, get: () => 800 },
+ scrollHeight: { configurable: true, get: () => column.children.length * 100 },
+ scrollTop: { configurable: true, get: () => scrollTop, set: (value: number) => { scrollTop = Math.max(0, value); } },
+ });
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
+ if (this === scroller) return { top: 0, bottom: 800, height: 800 } as DOMRect;
+ const ancestor = [...column.children].find((child) => child === this || child.contains(this));
+ const index = ancestor ? Array.prototype.indexOf.call(column.children, ancestor) : -1;
+ const top = index < 0 ? 0 : index * 100 - scrollTop;
+ return { top, bottom: top + 90, height: 90 } as DOMRect;
+ });
+ return { top: () => scrollTop };
+ };
+ const tail = Array.from({ length: 10 }, (_, index) => reply(`r${index}`));
+
+ it.each([
+ ['opened, so it re-mounts inside the opened group', true, 400],
+ ['closed, so it folds into the collapsed head', false, 100],
+ ])('holds the reading position when an older page makes the anchored row a group member (%s)', (_label, opened, expected) => {
+ const view = renderTranscript({ messages: [watch('h5'), ...tail], hasOlder: true });
+ const scroller = view.getByTestId('chat-transcript');
+ const layout = layOut(scroller);
+ if (opened) fireEvent.click(rendered('h5')!.querySelector('button[aria-expanded]')!);
+ // Read at the top of the window: h5 is the anchored row, at the top of the view.
+ fireEvent.pointerDown(scroller);
+ scroller.scrollTop = 0;
+ fireEvent.scroll(scroller);
+
+ view.rerender({ messages: [userMessage('u1'), watch('h3'), watch('h4'), watch('h5'), ...tail] });
+
+ // u1 is row 0 and the group head row 1. Opened, h5 renders as row 4; closed,
+ // the head stands in for it. Either way it is back at the top of the view.
+ expect(groupToggle(3).getAttribute('aria-expanded')).toBe(opened ? 'true' : 'false');
+ expect(layout.top()).toBe(expected);
+ });
+});
+
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index c4f13b665..710b76bba 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -69,6 +69,8 @@ import { FailureRetry, type FailureRetryOptions } from './FailureRetry';
import { FailureNextStep } from './FailureNextStep';
import { AGENT_BUBBLE, SYSTEM_BUBBLE, USER_BUBBLE } from './chatBubble';
import { RoleAvatar } from './RoleAvatar';
+import { HARNESS_GROUP_RAIL, HarnessGroup, HarnessGroupCollapse } from './HarnessGroup';
+import { groupHarnessRuns, stableHarnessGroupKeys } from '../../lib/harnessGroups';
import { SenderHead } from './SenderHead';
import { useFileDrop } from '../../lib/useFileDrop';
import { quoteText } from '../../lib/quoteText';
@@ -78,7 +80,7 @@ import {
insertMessageOrdered,
reconcileWorkbenchClaimedDeliveries,
} from '../../lib/transcriptOrder';
-import { pickScrollAnchor } from '../../lib/transcriptScrollAnchor';
+import { pickScrollAnchor, resolveScrollAnchor, type ScrollAnchor } from '../../lib/transcriptScrollAnchor';
import { AgentRoutePicker } from './AgentRoutePicker';
import {
archiveSessionShortcutLabel,
@@ -4023,6 +4025,31 @@ function transcriptOwnsUpwardInput(target: EventTarget, root: HTMLElement): bool
}
const NO_AGENTS: VibeAgentBrief[] = [];
+const NO_IDS: ReadonlySet<string> = new Set();
+
+// A set of message ids the transcript remembers for the open Session only: a
+// Session switch reads as empty without an effect to clear it.
+function useSessionIdSet(sessionId: string) {
+ const [state, setState] = useState<{ sessionId: string; ids: ReadonlySet<string> }>(() => ({
+ sessionId,
+ ids: NO_IDS,
+ }));
+ const ids = state.sessionId === sessionId ? state.ids : NO_IDS;
+ const update = useCallback(
+ (messageIds: readonly string[], include: boolean) => {
+ setState((prev) => {
+ const next = new Set(prev.sessionId === sessionId ? prev.ids : NO_IDS);
+ for (const id of messageIds) {
+ if (include) next.add(id);
+ else next.delete(id);
+ }
+ return { sessionId, ids: next };
+ });
+ },
+ [sessionId],
+ );
+ return [ids, update] as const;
+}
interface TranscriptProps {
messages: WorkbenchMessage[];
@@ -4206,7 +4233,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
// any later content resize can put that exact row back where it was. This is a
// manual scroll-anchor: iOS Safari still ships no CSS ``overflow-anchor``, so a
// late-loading image would otherwise shift the page out from under the reader.
- const anchorRef = useRef<{ el: HTMLElement; top: number } | null>(null);
+ const anchorRef = useRef<ScrollAnchor | null>(null);
const lastSessionRef = useRef<string | null>(null);
const [showJump, setShowJump] = useState(false);
// Whether the transcript is actually scrollable. Measured by the same
@@ -4289,6 +4316,82 @@ export const Transcript: React.FC<TranscriptProps> = ({
onToggleTools={activity.onToggleTools}
/>
) : null;
+ // Runs of Harness input fold into one group (docs/plans/workbench-refinements.md
+ // §3). Which groups are open is this page's memory for the open Session only:
+ // a group is open while any of its members is in the set, so it stays open as
+ // it grows at either end, and a Session switch starts every group collapsed.
+ const transcriptItems = useMemo(() => groupHarnessRuns(messages, { hasOlder }), [messages, hasOlder]);
+ // Group keys carried from the previous grouping, so a group keeps its element
+ // as it grows (see ``stableHarnessGroupKeys``). Updated during render, the
+ // React pattern for state derived from the previous render's state.
+ const [harnessKeys, setHarnessKeys] = useState(() => ({
+ items: transcriptItems,
+ keys: stableHarnessGroupKeys(transcriptItems, new Map()),
+ }));
+ let harnessGroupKeys = harnessKeys.keys;
+ if (harnessKeys.items !== transcriptItems) {
+ harnessGroupKeys = stableHarnessGroupKeys(transcriptItems, harnessKeys.keys);
+ setHarnessKeys({ items: transcriptItems, keys: harnessGroupKeys });
+ }
+ // Two memories: which groups are open (a group is open while any member is in
+ // it) and which single Harness rows the reader opened to read their prompt.
+ const [openGroupIds, setGroupIdsOpen] = useSessionIdSet(session.id);
+ const [openRowIds, setRowIdsOpen] = useSessionIdSet(session.id);
+ const setHarnessRowOpen = useCallback(
+ (messageId: string, open: boolean) => setRowIdsOpen([messageId], open),
+ [setRowIdsOpen],
+ );
+ // A deep link or search hit opens the group it lands in, in the render that
+ // carries it (so the jump below finds the row) and for good.
+ if (jumpTarget && !openGroupIds.has(jumpTarget)) setGroupIdsOpen([jumpTarget], true);
+ // What the reader is reading is not folded away under them: a row they opened
+ // that a new message turns into a group opens that group, and keeps it open
+ // after they close the row again.
+ const groupsHoldingOpenRows = transcriptItems.flatMap((item) =>
+ item.kind === 'harnessGroup'
+ && item.members.some(({ message }) => openRowIds.has(message.id))
+ && !item.members.some(({ message }) => openGroupIds.has(message.id))
+ ? item.members.map(({ message }) => message.id)
+ : [],
+ );
+ if (groupsHoldingOpenRows.length > 0) setGroupIdsOpen(groupsHoldingOpenRows, true);
+ // Collapsing from below the fold removes the row the scroll anchor holds, so
+ // the group's head is brought back into view once it commits (see the layout
+ // effect next to the anchor restore).
+ const revealHarnessGroupRef = useRef<string | null>(null);
+ // One transcript row with the Activity chips positioned relative to it: 'before'
+ // it (done/failed, hugging the reply from above) and 'after' it (interrupted, or
+ // a Turn that did not reply, just below its trigger). A Harness group draws its
+ // members through this too, so an opened member looks exactly as it would alone.
+ const renderTranscriptRow = (message: WorkbenchMessage, index: number) => {
+ const before = activity?.enabled ? activity.beforeAnchor.get(message.id) : undefined;
+ const after = activity?.enabled ? activity.afterAnchor.get(message.id) : undefined;
+ // A reply keeps the Agent that wrote it, which a switch may have replaced.
+ const author = message.author === 'agent' ? messageAuthorAgent(message, agents) : null;
+ return (
+ <>
+ {before?.map((group) => renderActivityChip(group))}
+ <MessageRow
+ message={message}
+ session={session}
+ agentDisplayName={author ? author.displayName : agentDisplayName}
+ agentBackend={author?.backend ?? agentBackend}
+ messageFontSize={messageFontSize}
+ onQuickReply={onQuickReply}
+ onFailureRetry={onFailureRetry}
+ retryDisabled={working || index < latestRetryBoundary}
+ vaultRequests={provisionRequestsByMessage.get(message.id)}
+ onVaultRequestResolved={onVaultRequestResolved}
+ onOpenLocalFile={openLocalFile}
+ readOnly={readOnly}
+ highlighted={message.id === highlightedId}
+ harnessOpen={openRowIds.has(message.id)}
+ onHarnessOpenChange={setHarnessRowOpen}
+ />
+ {after?.map((group) => renderActivityChip(group))}
+ </>
+ );
+ };
const empty = messages.length === 0 && !working;
// The end-of-history line answers "why did paging stop?" — a question only a
// reader who actually scrolled can have asked. A chat that fits the viewport
@@ -4483,9 +4586,13 @@ export const Transcript: React.FC<TranscriptProps> = ({
el.scrollTop = el.scrollHeight;
} else {
const anchor = anchorRef.current;
- if (!anchor || !anchor.el.isConnected) return;
- const currentTop = anchor.el.getBoundingClientRect().top - el.getBoundingClientRect().top;
- const delta = currentTop - anchor.top;
+ const content = contentRef.current;
+ // The anchored row may have re-mounted elsewhere (a Harness row an older
+ // page made a group member); follow the message, not the element.
+ const target = anchor && content ? resolveScrollAnchor(anchor, content) : null;
+ if (!target) return;
+ const currentTop = target.el.getBoundingClientRect().top - el.getBoundingClientRect().top;
+ const delta = currentTop - target.top;
if (Math.abs(delta) >= 0.5) el.scrollTop += delta;
}
// A programmatic adjustment must not look like upward input when its
@@ -4493,6 +4600,25 @@ export const Transcript: React.FC<TranscriptProps> = ({
lastScrollTopRef.current = Math.max(0, el.scrollTop);
}, [jumpTarget, pinnedRef]);
+ // A group closed from its trailing control (or anywhere below its head) took
+ // the anchored row with it, so the restore below has nothing to hold. Bring
+ // the head back to the top of the viewport and anchor to it instead. Runs
+ // before the restore, which then finds an anchor that is still connected.
+ useLayoutEffect(() => {
+ const key = revealHarnessGroupRef.current;
+ if (!key) return;
+ revealHarnessGroupRef.current = null;
+ const el = scrollRef.current;
+ const head = contentRef.current?.querySelector<HTMLElement>(`[data-harness-group="${CSS.escape(key)}"]`);
+ if (!el || !head || pinnedRef.current) return;
+ const offset = head.getBoundingClientRect().top - el.getBoundingClientRect().top;
+ if (offset < 0) {
+ el.scrollTop += offset;
+ lastScrollTopRef.current = Math.max(0, el.scrollTop);
+ }
+ captureAnchor();
+ });
+
// Prepending and trimming can leave the total height unchanged. Restore after
// every DOM commit, before paint or a queued scroll can capture a different
// row. This also covers the loading slot being inserted or removed.
@@ -4632,35 +4758,39 @@ export const Transcript: React.FC<TranscriptProps> = ({
) : null}
{/* Degenerate null-anchor groups render at the TOP (never the tail). */}
{activity?.enabled && activity.topGroups.map((group) => renderActivityChip(group))}
- {messages.map((message, index) => {
- // Agent Activity chips positioned relative to THIS row: 'before' it
- // (done/failed, hugging the reply from above) and 'after' it (interrupted,
- // just below the turn's trigger).
- const before = activity?.enabled ? activity.beforeAnchor.get(message.id) : undefined;
- const after = activity?.enabled ? activity.afterAnchor.get(message.id) : undefined;
- // A reply keeps the Agent that wrote it, which a switch may have replaced.
- const author = message.author === 'agent' ? messageAuthorAgent(message, agents) : null;
- return (
- <Fragment key={message.id}>
- {before?.map((group) => renderActivityChip(group))}
- <MessageRow
- message={message}
- session={session}
- agentDisplayName={author ? author.displayName : agentDisplayName}
- agentBackend={author?.backend ?? agentBackend}
- messageFontSize={messageFontSize}
- onQuickReply={onQuickReply}
- onFailureRetry={onFailureRetry}
- retryDisabled={working || index < latestRetryBoundary}
- vaultRequests={provisionRequestsByMessage.get(message.id)}
- onVaultRequestResolved={onVaultRequestResolved}
- onOpenLocalFile={openLocalFile}
- readOnly={readOnly}
- highlighted={message.id === highlightedId}
- />
- {after?.map((group) => renderActivityChip(group))}
- </Fragment>
- );
+ {transcriptItems.map((item) => {
+ if (item.kind === 'harnessGroup') {
+ const memberIds = item.members.map(({ message }) => message.id);
+ const open = memberIds.some((id) => openGroupIds.has(id) || id === jumpTarget);
+ const key = harnessGroupKeys.get(memberIds[0]) ?? memberIds[0];
+ const toggle = () => {
+ if (!open) {
+ setGroupIdsOpen(memberIds, true);
+ return;
+ }
+ // Closing the group closes its rows too, so none holds it open.
+ setGroupIdsOpen(memberIds, false);
+ setRowIdsOpen(memberIds, false);
+ revealHarnessGroupRef.current = key;
+ };
+ return (
+ <Fragment key={key}>
+ <HarnessGroup
+ groupKey={key}
+ members={item.members.map(({ message }) => message)}
+ expanded={open}
+ onToggle={toggle}
+ />
+ {open && item.members.map(({ message, index }) => (
+ <div key={message.id} className={clsx(HARNESS_GROUP_RAIL, 'flex flex-col gap-3')}>
+ {renderTranscriptRow(message, index)}
+ </div>
+ ))}
+ {open && <HarnessGroupCollapse count={memberIds.length} onCollapse={toggle} />}
+ </Fragment>
+ );
+ }
+ return <Fragment key={item.message.id}>{renderTranscriptRow(item.message, item.index)}</Fragment>;
})}
{/* The transcript TAIL is reserved exclusively for the live running card
(or the ThinkingBubble fallback) — never a settled/interrupted chip. */}
@@ -4801,6 +4931,10 @@ type MessageRowProps = {
// message; included in the memo's shallow compare so the highlight on/off
// re-renders just this row.
highlighted?: boolean;
+ // A Harness row's prompt is open. Held by the Transcript rather than the row,
+ // because whether the reader is reading it decides whether a group may fold it.
+ harnessOpen?: boolean;
+ onHarnessOpenChange?: (messageId: string, open: boolean) => void;
};
// Memoized so a transcript re-render that doesn't touch THIS row — the scroll
@@ -4827,6 +4961,8 @@ export const MessageRow = memo(function MessageRow({
onOpenLocalFile,
readOnly,
highlighted,
+ harnessOpen = false,
+ onHarnessOpenChange,
}: MessageRowProps) {
const { t } = useTranslation();
const navigate = useNavigate();
@@ -4834,8 +4970,8 @@ export const MessageRow = memo(function MessageRow({
// row's memo, so a personal↔organization change repaints the transcript
// without the page having to re-create every row's props.
const { instanceKind } = useInstanceAuthorization();
- // Harness rows are collapsed by default; this tracks the per-row expand state.
- const [expanded, setExpanded] = useState(false);
+ // Harness rows are collapsed by default; the Transcript holds which are open.
+ const expanded = harnessOpen;
// Deep-link jump target dressing applied to every row's outer wrapper:
// - ``data-message-id`` lets the transcript locate the row to scroll to.
@@ -5131,7 +5267,7 @@ export const MessageRow = memo(function MessageRow({
type="button"
variant="ghost"
size="xs"
- onClick={() => setExpanded((v) => !v)}
+ onClick={() => onHarnessOpenChange?.(message.id, !expanded)}
aria-expanded={expanded}
className="h-auto max-w-[360px] justify-start gap-2 rounded-xl rounded-tl-md border border-dashed border-cyan/40 bg-cyan/[0.05] px-3 py-1.5 hover:bg-cyan/[0.10]"
>
diff --git a/ui/src/components/workbench/HarnessGroup.tsx b/ui/src/components/workbench/HarnessGroup.tsx
new file mode 100644
index 000000000..588e0d205
--- /dev/null
+++ b/ui/src/components/workbench/HarnessGroup.tsx
@@ -0,0 +1,178 @@
+import type { TranslationKey } from '@/i18n/types';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { ChevronDown, Layers } from 'lucide-react';
+import clsx from 'clsx';
+
+import type { WorkbenchMessage } from '../../context/ApiContext';
+import { chatTriggerLink, harnessChipLabelKey } from '../../lib/chatTrigger';
+import { formatLocalClockTime } from '../../lib/relativeTime';
+import { RoleAvatar } from './RoleAvatar';
+
+// The left rail that ties an expanded group's rows together. Each row draws its
+// own segment, reaching up through the column's 12px gap to the row above, so
+// the members stay direct children of the transcript column: the scroll anchor
+// and the deep-link jump find them exactly as they find any other row.
+export const HARNESS_GROUP_RAIL =
+ 'relative ml-3 pl-4 before:absolute before:-top-3 before:bottom-0 before:left-0 before:w-0.5 before:rounded-full before:bg-cyan/25';
+
+// An Agent callback reads "From · <session>" on its own row, but "From" alone
+// says nothing in a count, so the count uses the self-contained "From agent".
+const summaryKey = (message: WorkbenchMessage): TranslationKey => {
+ const key = harnessChipLabelKey(message);
+ return key === 'chat.source.from' ? 'chat.source.harness' : key;
+};
+
+const sameLocalDay = (a: string, b: string): boolean => {
+ const x = new Date(a);
+ const y = new Date(b);
+ return x.getFullYear() === y.getFullYear() && x.getMonth() === y.getMonth() && x.getDate() === y.getDate();
+};
+
+const localDay = (iso: string): string => {
+ const d = new Date(iso);
+ return `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
+};
+
+// First to last member, as wall-clock times; the day appears once the run
+// crosses midnight, which overnight Watch runs do.
+const timeSpan = (first: string, last: string): string => {
+ if (sameLocalDay(first, last)) return `${formatLocalClockTime(first)}–${formatLocalClockTime(last)}`;
+ return `${localDay(first)} ${formatLocalClockTime(first)}–${localDay(last)} ${formatLocalClockTime(last)}`;
+};
+
+/**
+ * The row a run of Harness messages folds into (docs/plans/workbench-refinements.md
+ * §3). Collapsed, it is the whole group: a count, where the messages came from,
+ * when, and the latest one, stacked over two sheets that say there is more
+ * underneath. Expanded, it is only the head; the Transcript draws the members
+ * below it on the rail.
+ */
+export function HarnessGroup({
+ groupKey,
+ members,
+ expanded,
+ onToggle,
+}: {
+ /** Stable across growth; the Transcript finds the head by it after a collapse. */
+ groupKey: string;
+ members: WorkbenchMessage[];
+ expanded: boolean;
+ onToggle: () => void;
+}) {
+ const { t } = useTranslation();
+ const latest = members[members.length - 1];
+ const sources = useMemo(() => {
+ const counts = new Map<TranslationKey, number>();
+ for (const message of members) {
+ const key = summaryKey(message);
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ return [...counts];
+ }, [members]);
+ const countLabel = t('chat.harnessGroup.count', { count: members.length });
+ const link = chatTriggerLink(latest, t('chat.source.agentFallback'));
+ const latestSource = link?.kind === 'source' ? link.label : t(harnessChipLabelKey(latest));
+
+ const head = (
+ <span className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 px-0.5 text-left">
+ <RoleAvatar tone="cyan">
+ <Layers />
+ </RoleAvatar>
+ <span className="shrink-0 text-[11px] font-semibold text-cyan-ink">{countLabel}</span>
+ <span className="inline-flex min-w-0 flex-wrap items-center gap-x-1.5 text-[11px] text-muted">
+ {sources.map(([key, count]) => (
+ <span key={key} className="whitespace-nowrap">
+ {t('chat.harnessGroup.sourceCount', { label: t(key), n: count })}
+ </span>
+ ))}
+ </span>
+ <span className="whitespace-nowrap font-mono text-[10px] text-muted">
+ {timeSpan(members[0].created_at, latest.created_at)}
+ </span>
+ </span>
+ );
+
+ // The head's identity for the transcript's scroll anchor: which group it is,
+ // and the messages it stands for, so an anchor held on one of them can find
+ // the head they collapsed into and the head can find them if it dissolves.
+ const rowAttributes = {
+ 'data-transcript-row': '',
+ 'data-harness-group': groupKey,
+ 'data-harness-members': members.map((message) => message.id).join(' '),
+ };
+
+ if (expanded) {
+ return (
+ <div {...rowAttributes} className="flex w-full justify-start">
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-expanded
+ aria-label={countLabel}
+ className="group/harness flex w-full max-w-[min(92%,860px)] items-center gap-2 rounded-lg text-left"
+ >
+ <span className="min-w-0 flex-1">{head}</span>
+ <span className="inline-flex shrink-0 items-center gap-0.5 rounded-md bg-cyan/[0.08] px-1.5 py-0.5 text-[11px] font-semibold text-cyan-ink group-hover/harness:bg-cyan/[0.14]">
+ {t('chat.collapse')}
+ <ChevronDown className="size-3.5 rotate-180" />
+ </span>
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div {...rowAttributes} className="flex w-full justify-start">
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-expanded={false}
+ aria-label={countLabel}
+ className="group/harness flex max-w-[min(92%,860px)] flex-col items-start gap-1.5 text-left"
+ >
+ {head}
+ <span className="relative block w-[min(100%,460px)] pb-3">
+ {/* Two offset sheets behind the latest message: more is folded in. */}
+ <span aria-hidden className="absolute inset-x-5 bottom-0 top-5 rounded-xl border border-cyan/25 bg-background opacity-60" />
+ <span aria-hidden className="absolute inset-x-2.5 bottom-1.5 top-2.5 rounded-xl border border-cyan/30 bg-background" />
+ <span className="relative block rounded-xl rounded-tl-md bg-background">
+ <span
+ className={clsx(
+ 'flex items-center gap-2 rounded-xl rounded-tl-md border border-dashed border-cyan/40 bg-cyan/[0.05] px-3 py-1.5 transition-colors',
+ 'group-hover/harness:bg-cyan/[0.10]',
+ )}
+ >
+ <span className="shrink-0 rounded bg-cyan/[0.10] px-1 text-[10px] font-bold text-cyan-ink">
+ {t('chat.harnessGroup.latest')}
+ </span>
+ <span className="max-w-[40%] shrink-0 truncate text-[11px] font-medium text-cyan-ink">{latestSource}</span>
+ <span className="min-w-0 flex-1 truncate text-[12px] text-muted">{latest.text?.trim()}</span>
+ <span className="inline-flex shrink-0 items-center gap-0.5 text-[11px] font-semibold text-cyan-ink">
+ {t('chat.harnessGroup.expand')}
+ <ChevronDown className="size-3.5" />
+ </span>
+ </span>
+ </span>
+ </span>
+ </button>
+ </div>
+ );
+}
+
+/** The trailing control of an expanded group, for when its head has scrolled away. */
+export function HarnessGroupCollapse({ count, onCollapse }: { count: number; onCollapse: () => void }) {
+ const { t } = useTranslation();
+ return (
+ <div className={HARNESS_GROUP_RAIL}>
+ <button
+ type="button"
+ onClick={onCollapse}
+ className="inline-flex items-center gap-0.5 text-[11px] font-semibold text-cyan-ink hover:underline"
+ >
+ {t('chat.harnessGroup.collapseCount', { count })}
+ <ChevronDown className="size-3.5 rotate-180" />
+ </button>
+ </div>
+ );
+}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 16d950616..40f7e226a 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -5139,6 +5139,13 @@
},
"retryFailed": "Could not request retry. You can try again safely.",
"collapse": "Collapse",
+ "harnessGroup": {
+ "count": "{{count}} Harness messages",
+ "latest": "Latest",
+ "sourceCount": "· {{label}} {{n}}",
+ "expand": "Expand",
+ "collapseCount": "Collapse these {{count}}"
+ },
"turnInProgress": "A turn is already running — wait for the reply.",
"stopFailed": "Couldn't reach the agent to stop it — it may still be running.",
"source": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 7bed0f7b1..be7bdd1a4 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -5139,6 +5139,13 @@
},
"retryFailed": "未能提交重试,可以再次点击。",
"collapse": "收起",
+ "harnessGroup": {
+ "count": "{{count}} 条 Harness 消息",
+ "latest": "最新",
+ "sourceCount": "· {{label}} {{n}}",
+ "expand": "展开",
+ "collapseCount": "收起这 {{count}} 条"
+ },
"turnInProgress": "当前回合还在进行中,请等待回复后再发送。",
"stopFailed": "没能联系到 Agent 来停止,它可能还在运行。",
"source": {
diff --git a/ui/src/lib/harnessGroups.test.ts b/ui/src/lib/harnessGroups.test.ts
new file mode 100644
index 000000000..287c0898c
--- /dev/null
+++ b/ui/src/lib/harnessGroups.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from 'vitest';
+
+import { groupHarnessRuns, stableHarnessGroupKeys, type TranscriptItem } from './harnessGroups';
+
+type Row = { id: string; type: string; author: string; source?: string | null; content?: unknown; metadata?: Record<string, unknown> | null };
+
+const harness = (id: string): Row => ({ id, type: 'harness', author: 'harness', source: 'harness' });
+const user = (id: string): Row => ({ id, type: 'user', author: 'user', source: 'user' });
+const reply = (id: string): Row => ({ id, type: 'result', author: 'agent', source: 'agent' });
+
+// The shape a reader sees: a bare id for a lone row, an array for a group.
+const shape = (items: TranscriptItem<Row>[]) =>
+ items.map((item) => (item.kind === 'message' ? item.message.id : item.members.map(({ message }) => message.id)));
+
+describe('groupHarnessRuns', () => {
+ it('folds runs of two or more Harness rows and leaves single ones alone', () => {
+ const messages = [user('u1'), harness('h1'), harness('h2'), reply('r1'), harness('h3'), user('u2'), harness('h4'), harness('h5'), harness('h6')];
+
+ const items = groupHarnessRuns(messages, { hasOlder: true });
+
+ expect(shape(items)).toEqual(['u1', ['h1', 'h2'], 'r1', 'h3', 'u2', ['h4', 'h5', 'h6']]);
+ // Positions in the loaded list survive grouping; Retry eligibility reads them.
+ expect(items[1]).toMatchObject({ members: [{ index: 1 }, { index: 2 }] });
+ expect(items[5]).toMatchObject({ members: [{ index: 6 }, { index: 7 }, { index: 8 }] });
+ });
+
+ it.each<[string, Row]>([
+ ['the user', user('x')],
+ ['an Agent reply', reply('x')],
+ ['mid-Turn Agent output', { id: 'x', type: 'output', author: 'agent', source: 'agent' }],
+ ['muted interim narration', { id: 'x', type: 'interim', author: 'agent', source: 'agent' }],
+ ['a status or failure notice', { id: 'x', type: 'notify', author: 'agent', source: 'agent', metadata: { event: 'backend_failure' } }],
+ ['an error row', { id: 'x', type: 'error', author: 'agent', source: 'agent' }],
+ // A forward annotation is authored by ``harness`` and still is not Harness input.
+ ['an annotation card', { id: 'x', type: 'annotation', author: 'harness', source: 'harness', content: { annotation: { direction: 'user' } } }],
+ ])('ends a run at %s', (_label, breaker) => {
+ const items = groupHarnessRuns([harness('h1'), harness('h2'), breaker, harness('h3'), harness('h4')], { hasOlder: true });
+
+ expect(shape(items)).toEqual([['h1', 'h2'], 'x', ['h3', 'h4']]);
+ });
+
+ it('counts a Vault callback as Harness input', () => {
+ const vault: Row = { id: 'v1', type: 'vault', author: 'harness', source: 'harness', metadata: { source_actor: 'vault:req_1' } };
+
+ expect(shape(groupHarnessRuns([harness('h1'), vault], { hasOlder: true }))).toEqual([['h1', 'v1']]);
+ });
+
+ it("keeps the Session's first message out of groups, once it is known to be first", () => {
+ const messages = [harness('brief'), harness('h1'), harness('h2')];
+
+ expect(shape(groupHarnessRuns(messages, { hasOlder: false }))).toEqual(['brief', ['h1', 'h2']]);
+ // With older pages still unloaded, the first loaded row is not the Session's first.
+ expect(shape(groupHarnessRuns(messages, { hasOlder: true }))).toEqual([['brief', 'h1', 'h2']]);
+ // A brief followed by a single Harness row leaves nothing to fold.
+ expect(shape(groupHarnessRuns(messages.slice(0, 2), { hasOlder: false }))).toEqual(['brief', 'h1']);
+ });
+});
+
+describe('stableHarnessGroupKeys', () => {
+ const keysFor = (messages: Row[], previous: ReadonlyMap<string, string> = new Map(), hasOlder = true) =>
+ stableHarnessGroupKeys(groupHarnessRuns(messages, { hasOlder }), previous);
+
+ it('keeps a group key while the group grows live and when older members load above it', () => {
+ const first = keysFor([harness('h3'), harness('h4')]);
+ const key = first.get('h3');
+
+ const grownLive = keysFor([harness('h3'), harness('h4'), harness('h5')], first);
+ expect(grownLive.get('h5')).toBe(key);
+
+ const olderLoaded = keysFor([harness('h1'), harness('h2'), harness('h3'), harness('h4'), harness('h5')], grownLive);
+ expect(new Set(olderLoaded.values())).toEqual(new Set([key]));
+ });
+
+ it('never hands one key to two groups when a run splits', () => {
+ const before = keysFor([harness('h1'), harness('h2'), harness('h3'), harness('h4')]);
+ const key = before.get('h1');
+
+ const after = keysFor([harness('h1'), harness('h2'), reply('r'), harness('h3'), harness('h4')], before);
+
+ expect(after.get('h1')).toBe(key);
+ expect(after.get('h2')).toBe(key);
+ expect(after.get('h3')).not.toBe(key);
+ expect(after.get('h4')).toBe(after.get('h3'));
+ });
+});
diff --git a/ui/src/lib/harnessGroups.ts b/ui/src/lib/harnessGroups.ts
new file mode 100644
index 000000000..89e40e508
--- /dev/null
+++ b/ui/src/lib/harnessGroups.ts
@@ -0,0 +1,78 @@
+// Folds runs of Harness input in a chat transcript into one group, so a stretch
+// of Watch results, scheduled runs and Agent callbacks the Agent answered
+// silently reads as one row instead of a column of blue chips.
+// docs/plans/workbench-refinements.md §3 owns the rules; this module is their
+// one implementation, pure so they are tested without the page.
+//
+// Grouping looks at consecutive transcript rows only. A Turn that did not reply
+// writes no row: its Activity chip anchors AFTER its trigger, which is a member
+// of the run, so it travels with that member and never separates two members.
+// Everything that does draw a row (the user, the Agent in any form, an
+// annotation) sits between members in this list and so ends the run.
+import type { WorkbenchMessage } from '../context/ApiContext';
+import { chatRowKind } from './chatRowKind';
+
+type Message = Pick<WorkbenchMessage, 'id' | 'type' | 'author' | 'source' | 'content' | 'metadata'>;
+
+export type TranscriptItem<M extends Message = WorkbenchMessage> =
+ | { kind: 'message'; message: M; index: number }
+ | { kind: 'harnessGroup'; members: { message: M; index: number }[] };
+
+/**
+ * ``index`` is each row's position in ``messages``, kept because callers key
+ * per-row decisions (Retry eligibility) on it.
+ *
+ * The Session's first message never joins a group: in a delegated Session it is
+ * the task brief, the one Harness row that says what the Session is for. It is
+ * only known to be first while no older page is left (``hasOlder`` false).
+ */
+export function groupHarnessRuns<M extends Message>(
+ messages: readonly M[],
+ { hasOlder }: { hasOlder: boolean },
+): TranscriptItem<M>[] {
+ const items: TranscriptItem<M>[] = [];
+ let run: { message: M; index: number }[] = [];
+ const flush = () => {
+ if (run.length >= 2) items.push({ kind: 'harnessGroup', members: run });
+ else for (const member of run) items.push({ kind: 'message', ...member });
+ run = [];
+ };
+ messages.forEach((message, index) => {
+ const opening = index === 0 && !hasOlder;
+ if (!opening && chatRowKind(message).kind === 'harness') {
+ run.push({ message, index });
+ return;
+ }
+ flush();
+ items.push({ kind: 'message', message, index });
+ });
+ flush();
+ return items;
+}
+
+/**
+ * React keys for groups that survive growth at either end. A group keyed by its
+ * first member would remount when an older page adds members above it, and one
+ * keyed by its last member would remount whenever a new message joins live; a
+ * remount drops the element the transcript's scroll anchor holds. So a group
+ * keeps the key any of its members carried last time, and only a group with no
+ * known member takes a new one. Pure: the caller stores the returned map.
+ */
+export function stableHarnessGroupKeys<M extends Message>(
+ items: readonly TranscriptItem<M>[],
+ previous: ReadonlyMap<string, string>,
+): Map<string, string> {
+ const next = new Map<string, string>();
+ const used = new Set<string>();
+ for (const item of items) {
+ if (item.kind !== 'harnessGroup') continue;
+ const inherited = item.members
+ .map(({ message }) => previous.get(message.id))
+ .find((key): key is string => key !== undefined && !used.has(key));
+ let key = inherited ?? `harness-group:${item.members[0].message.id}`;
+ while (used.has(key)) key = `${key}+`;
+ used.add(key);
+ for (const { message } of item.members) next.set(message.id, key);
+ }
+ return next;
+}
diff --git a/ui/src/lib/transcriptScrollAnchor.test.ts b/ui/src/lib/transcriptScrollAnchor.test.ts
index 52093ed6f..7eab94801 100644
--- a/ui/src/lib/transcriptScrollAnchor.test.ts
+++ b/ui/src/lib/transcriptScrollAnchor.test.ts
@@ -2,7 +2,7 @@
import { describe, expect, it } from 'vitest';
-import { pickScrollAnchor } from './transcriptScrollAnchor';
+import { pickScrollAnchor, resolveScrollAnchor } from './transcriptScrollAnchor';
// jsdom does no layout, so each child declares the rect it would have had. The
// numbers below mirror the real transcript column: the scroll container carries
@@ -34,7 +34,7 @@ describe('pickScrollAnchor', () => {
const firstVisible = row({ top: -8, height: 60, id: 'm2' });
const below = row({ top: 64, height: 60, id: 'm3' });
- expect(pickScrollAnchor([scrolledPast, firstVisible, below], CONTAINER_TOP)).toEqual({
+ expect(pickScrollAnchor([scrolledPast, firstVisible, below], CONTAINER_TOP)).toMatchObject({
el: firstVisible,
top: -8,
});
@@ -66,14 +66,14 @@ describe('pickScrollAnchor', () => {
const readersRow = row({ top: 20, height: 60, id: 'm2' });
for (const [name, above] of Object.entries(preMessageChrome)) {
- expect(pickScrollAnchor([above, readersRow], CONTAINER_TOP), name).toEqual({
+ expect(pickScrollAnchor([above, readersRow], CONTAINER_TOP), name).toMatchObject({
el: readersRow,
top: 20,
});
}
// ...and all of it at once, in render order, is still skipped.
- expect(pickScrollAnchor([...Object.values(preMessageChrome), readersRow], CONTAINER_TOP)).toEqual(
+ expect(pickScrollAnchor([...Object.values(preMessageChrome), readersRow], CONTAINER_TOP)).toMatchObject(
{ el: readersRow, top: 20 },
);
});
@@ -86,19 +86,81 @@ describe('pickScrollAnchor', () => {
const chipBetweenRows = chrome({ top: -8, height: 24 });
const nextRow = row({ top: 28, height: 60, id: 'm2' });
- expect(pickScrollAnchor([firstRow, chipBetweenRows, nextRow], CONTAINER_TOP)).toEqual({
+ expect(pickScrollAnchor([firstRow, chipBetweenRows, nextRow], CONTAINER_TOP)).toMatchObject({
el: chipBetweenRows,
top: -8,
});
});
+ // A collapsed Harness group stands for several messages in one element. At the
+ // head of the window it is the row a prepend pushes down, so skipping it as
+ // chrome would anchor the reader to whatever sits below it instead.
+ it('counts a row that stands for several messages as the first row', () => {
+ const group = chrome({ top: -8, height: 70 });
+ group.dataset.transcriptRow = '';
+ const nextRow = row({ top: 74, height: 60, id: 'm9' });
+
+ expect(pickScrollAnchor([chrome({ top: -40, height: 32 }), group, nextRow], CONTAINER_TOP)).toMatchObject({
+ el: group,
+ top: -8,
+ });
+ });
+
it('measures against the container top rather than the viewport', () => {
const offscreenAboveContainer = row({ top: 100, height: 40, id: 'm1' });
const firstVisible = row({ top: 152, height: 60, id: 'm2' });
- expect(pickScrollAnchor([offscreenAboveContainer, firstVisible], 150)).toEqual({
+ expect(pickScrollAnchor([offscreenAboveContainer, firstVisible], 150)).toMatchObject({
el: firstVisible,
top: 2,
});
});
});
+
+describe('resolveScrollAnchor', () => {
+ const content = (...children: HTMLElement[]) => {
+ const column = document.createElement('div');
+ column.append(...children);
+ document.body.append(column);
+ return column;
+ };
+
+ it('follows a message whose row re-mounted inside a group, or folded into its head', () => {
+ const anchor = pickScrollAnchor([row({ top: 12, height: 60, id: 'h5' })], CONTAINER_TOP)!;
+ expect(anchor).toMatchObject({ rowId: 'h5', rowTop: 12 });
+
+ // An older page made h5 a group member: a new element, nested in a wrapper.
+ const wrapper = document.createElement('div');
+ const remounted = row({ top: 412, height: 60, id: 'h5' });
+ wrapper.append(remounted);
+ expect(resolveScrollAnchor(anchor, content(wrapper))).toEqual({ el: remounted, top: 12 });
+
+ // ...or folded it into a collapsed group, which takes the row's place.
+ const head = chrome({ top: 100, height: 70 });
+ head.dataset.harnessMembers = 'h3 h4 h5';
+ expect(resolveScrollAnchor(anchor, content(head))).toEqual({ el: head, top: 12 });
+
+ // A message that left the transcript leaves nothing to hold.
+ expect(resolveScrollAnchor(anchor, content(chrome({ top: 0, height: 10 })))).toBeNull();
+ });
+
+ it('lets a dissolved group hand its place to its first message', () => {
+ const head = chrome({ top: -20, height: 70 });
+ head.dataset.transcriptRow = '';
+ head.dataset.harnessMembers = 'h1 h2';
+ const anchor = pickScrollAnchor([head], CONTAINER_TOP)!;
+ expect(anchor).toMatchObject({ el: head, rowId: 'h1', rowTop: -20 });
+
+ const standalone = row({ top: 80, height: 60, id: 'h1' });
+ expect(resolveScrollAnchor(anchor, content(standalone))).toEqual({ el: standalone, top: -20 });
+ });
+
+ it('keeps the anchored element while it is still mounted', () => {
+ const anchored = row({ top: 30, height: 60, id: 'm1' });
+ const anchor = pickScrollAnchor([anchored], CONTAINER_TOP)!;
+ content(anchored);
+
+ expect(resolveScrollAnchor(anchor, document.body)).toEqual({ el: anchored, top: 30 });
+ });
+});
+
diff --git a/ui/src/lib/transcriptScrollAnchor.ts b/ui/src/lib/transcriptScrollAnchor.ts
index 65d344ea4..037450770 100644
--- a/ui/src/lib/transcriptScrollAnchor.ts
+++ b/ui/src/lib/transcriptScrollAnchor.ts
@@ -23,7 +23,19 @@
// search starts at the first message row and never looks above it. Chrome added
// above the transcript later is excluded by construction instead of by someone
// remembering to mark it.
-export type ScrollAnchor = { el: HTMLElement; top: number };
+//
+// A row is a message row (``data-message-id``) or a row standing for several of
+// them (``data-transcript-row``): a collapsed Harness group is one element for
+// many messages, and it moves with a prepend exactly as the rows it holds would.
+//
+// The anchor also names the message row it holds (``rowId``, ``rowTop``), because
+// a message can change element without leaving the transcript: a Harness row
+// that an older page turns into a group member is re-mounted inside the group,
+// or folded into its collapsed head. ``resolveScrollAnchor`` follows it there.
+export type ScrollAnchor = { el: HTMLElement; top: number; rowId?: string; rowTop?: number };
+
+const isTranscriptRow = (el: HTMLElement): boolean =>
+ el.dataset.messageId !== undefined || el.dataset.transcriptRow !== undefined;
export const pickScrollAnchor = (
children: readonly HTMLElement[],
@@ -31,14 +43,48 @@ export const pickScrollAnchor = (
): ScrollAnchor | null => {
// Everything before the first row holds still while the content grows above it,
// so it can never restore anything.
- const firstRow = children.findIndex((child) => child.dataset.messageId !== undefined);
+ const firstRow = children.findIndex(isTranscriptRow);
if (firstRow < 0) return null;
for (let i = firstRow; i < children.length; i += 1) {
const child = children[i];
const rect = child.getBoundingClientRect();
// Entirely above the viewport top — scrolled past, not what the reader sees.
if (rect.bottom <= containerTop) continue;
- return { el: child, top: rect.top - containerTop };
+ const anchor: ScrollAnchor = { el: child, top: rect.top - containerTop };
+ const row = child.dataset.messageId !== undefined ? child : child.querySelector<HTMLElement>('[data-message-id]');
+ if (row?.dataset.messageId) {
+ anchor.rowId = row.dataset.messageId;
+ anchor.rowTop = row.getBoundingClientRect().top - containerTop;
+ } else if (child.dataset.harnessMembers) {
+ // A group head stands for its members; should the group dissolve, its
+ // first message's row takes the head's place.
+ anchor.rowId = child.dataset.harnessMembers.split(' ')[0];
+ anchor.rowTop = anchor.top;
+ }
+ return anchor;
}
return null;
};
+
+const byAttribute = (content: ParentNode, selector: string) => content.querySelector<HTMLElement>(selector);
+
+/**
+ * The element to restore against, and where its top belongs. The anchored
+ * element while it is still mounted; otherwise the same message's row wherever
+ * it now renders; otherwise the collapsed group that folded it in
+ * (``data-harness-members`` lists a group's message ids), placed where the row
+ * was. ``null`` when the message left the transcript.
+ */
+export const resolveScrollAnchor = (
+ anchor: ScrollAnchor,
+ content: ParentNode,
+): { el: HTMLElement; top: number } | null => {
+ if (anchor.el.isConnected) return { el: anchor.el, top: anchor.top };
+ if (anchor.rowId === undefined || anchor.rowTop === undefined) return null;
+ // Quoted attribute values need only quotes and backslashes escaped.
+ const id = anchor.rowId.replace(/["\\]/g, '\\$&');
+ const row =
+ byAttribute(content, `[data-message-id="${id}"]`) ??
+ byAttribute(content, `[data-harness-members~="${id}"]`);
+ return row ? { el: row, top: anchor.rowTop } : null;
+};