diff --git a/docs/styleguide/native-chat.md b/docs/styleguide/native-chat.md index 69600d8d006..4d367ca879e 100644 --- a/docs/styleguide/native-chat.md +++ b/docs/styleguide/native-chat.md @@ -27,4 +27,4 @@ The chat root (`.native-chat-appearance`) redefines these steps as ratios of the - **Focus rings:** full-width transcript rows use the inset ring (`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring`) so it isn't clipped by the scroll container; standalone controls use `focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`. Inside the chat `--ring` is `--chat-focus-ring`, which clears 3:1 on the canvas; don't lower its opacity. - **Theme overrides:** plugin themes can set `--chat-bold-foreground`, `--chat-muted-foreground`, `--chat-inline-code`, `--chat-inline-code-foreground`, `--chat-code-block`, `--chat-selection` and `--chat-selection-foreground`. They feed `text-chat-foreground-faint`, `bg-chat-inline-code-surface`, `bg-chat-code-surface` and the chat root's `::selection`, so use those rather than reading the theme tokens directly. - **Selection** inside the chat is the link hue mixed into the canvas (close to the system highlight), with selected text in the full foreground so every role stays 4.5:1. Don't add per-component `selection:` colors in transcript text. -- **State colours:** warnings use `text-chat-warning`; diff lines use `text-chat-diff-added` / `text-chat-diff-removed`. They are mixed toward the foreground so they pass text contrast in light and dark. Don't use raw palette colours (`text-yellow-500`) or the git decoration tokens for text on a tinted row. +- **State colours:** warnings use `text-chat-warning`; diff lines use `text-chat-diff-added` / `text-chat-diff-removed`; what the reader has not seen yet uses `text-chat-unread`. They are mixed toward the foreground so they pass text contrast in light and dark. Don't use raw palette colours (`text-yellow-500`) or the git decoration tokens for text on a tinted row. diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index f5412aa291f..59c6fd15fb5 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -61,6 +61,7 @@ --color-chat-foreground: var(--chat-foreground); --color-chat-foreground-strong: var(--chat-foreground-strong); --color-chat-foreground-faint: var(--chat-foreground-faint); + --color-chat-unread: var(--chat-unread); --color-chat-user-surface: var(--chat-user-surface); --color-chat-user-border: var(--chat-user-border); --color-chat-code-foreground: var(--chat-code-foreground); @@ -741,6 +742,8 @@ body[data-modal-overlay-open] /* Mixed toward the foreground so each clears text contrast on the canvas in either scheme. */ --chat-focus-ring: color-mix(in srgb, var(--chat-source-foreground) 50%, var(--chat-canvas)); --chat-warning: color-mix(in srgb, var(--status-warning) 70%, var(--chat-source-foreground)); + /* What the reader has not seen yet: the transcript's "New" marker, in the note hue. */ + --chat-unread: color-mix(in srgb, var(--callout-note) 70%, var(--chat-source-foreground)); --chat-diff-added: color-mix(in srgb, var(--diff-added) 70%, var(--chat-source-foreground)); --chat-diff-removed: color-mix(in srgb, var(--diff-removed) 70%, var(--chat-source-foreground)); --chat-link: color-mix( diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx index b8714c4e801..6bf6f01d074 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx @@ -4,13 +4,14 @@ import { NATIVE_CHAT_TRANSCRIPT_COLUMN_CLASS } from './appearance/native-chat-appearance-style' import { NativeChatJumpToLatest } from './viewport/scroll/NativeChatJumpToLatest' +import { NativeChatNewRowsAnnouncement } from './viewport/new-rows/NativeChatNewRowsMarker' +import { useNativeChatNewRowsMarker } from './viewport/new-rows/native-chat-new-rows-marker' import { withoutPullRequestEventRows } from '../../../../shared/native-chat/native-chat-pull-request-event' import { useNativeChatRowTypography } from './viewport/virtualization/use-native-chat-row-typography' import { useCallback, useMemo, useRef, useState } from 'react' import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store' import { - nativeChatScrollsToLatestOnSend, nativeChatShowsCiResultLines, nativeChatShowsTurnDiffSummary } from '../../../../shared/native-chat/native-chat-appearance-settings' @@ -243,12 +244,18 @@ export function NativeChatMessageList({ [allSlots, journalItems, stopping, journalSubmissions, latestTurn, hostWork] ) const navigationRequest = useNativeChatNavigationRequest(slots, messages, subagentSections) + const newRows = useNativeChatNewRowsMarker( + slots, + waitingSlots, + isVisible && session.readCurrent === true + ) const transcriptWindow = useNativeChatTranscriptWindow({ scrollRef, slots, isVisible, // Rail jumps, diff reveals and subagent reveals share one mutually exclusive pin. revealIndex: navigationRequest.revealIndex, + newRowsMarkerIndex: newRows.index, typography }) const transcriptScroll = useNativeChatTranscriptScroll({ @@ -326,25 +333,15 @@ export function NativeChatMessageList({ onLeaveEnd: readerLeavesEnd, onScrollGesture: transcriptScroll.forwardedGesture }) - // Off keeps a reader who scrolled up in place; one at the end still follows the reply. - const revealSent = useCallback( - (readerWasAtEnd = readerAtEnd()) => { - if (!nativeChatScrollsToLatestOnSend(useAppStore.getState().settings) && !readerWasAtEnd) { - return - } - beginNavigation() - scrollToBottom('send') - }, - [beginNavigation, readerAtEnd, scrollToBottom] - ) - useNativeChatMessageListHandle( - ref, - revealSent, - readerInput.revealFindMatch, - allSlots, + useNativeChatMessageListHandle(ref, { readerAtEnd, - navigation.revealSubagent - ) + beginNavigation, + scrollToBottom, + onSent: newRows.dismiss, + revealFindMatch: readerInput.revealFindMatch, + slots: allSlots, + revealSubagent: navigation.revealSubagent + }) const rowContext = useNativeChatTranscriptRowContext({ agent: session.agent, @@ -397,6 +394,7 @@ export function NativeChatMessageList({ loadedMessageIds={loadedMessageIds} context={rowContext} window={transcriptWindow} + newRowsMarker={newRows.marker} forwardGesture={readerInput.forwardedGesture} /> {liveLine ? ( @@ -417,6 +415,7 @@ export function NativeChatMessageList({ pendingId={navigation.pendingRailId} /> + diff --git a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts index 19b8e0e927f..5db0cd89263 100644 --- a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts +++ b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts @@ -1,5 +1,7 @@ import { useCallback, useImperativeHandle, useMemo, useRef } from 'react' +import { useAppStore } from '@/store' import { hasAskAnswer } from '../../../../../../shared/native-chat/input/native-chat-ask-answer' +import { nativeChatScrollsToLatestOnSend } from '../../../../../../shared/native-chat/native-chat-appearance-settings' import { nativeChatSlotCopyText } from './native-chat-message-copy-text' import type { NativeChatTranscriptSlot } from '../../conversation/slots/native-chat-transcript-slots' import type { NativeChatInteractiveSend } from '../../session/terminal/send/use-native-chat-interactive-send' @@ -86,22 +88,36 @@ export function useNativeChatRevealLatest(): { return { messageListRef, revealLatest, captureRevealLatest } } -function ignoreFindMatch(): void {} - -function alwaysAtEnd(): boolean { - return true -} - -function ignoreSubagent(): void {} - +/** Own sends follow the latest; with that setting off, only a reader who was at the end does. */ export function useNativeChatMessageListHandle( ref: React.Ref | undefined, - revealLatest: NativeChatMessageListHandle['revealLatest'], - revealFindMatch: NativeChatMessageListHandle['revealFindMatch'] = ignoreFindMatch, - slots: readonly NativeChatTranscriptSlot[] = [], - readerAtEnd: NativeChatMessageListHandle['readerAtEnd'] = alwaysAtEnd, - revealSubagent: NativeChatMessageListHandle['revealSubagent'] = ignoreSubagent + { + readerAtEnd, + beginNavigation, + scrollToBottom, + onSent, + revealFindMatch, + slots, + revealSubagent + }: Pick & { + beginNavigation: () => void + scrollToBottom: (reason: 'send') => void + /** The reader answered, whether or not the view moves. */ + onSent: () => void + slots: readonly NativeChatTranscriptSlot[] + } ): void { + const revealLatest = useCallback( + (readerWasAtEnd = readerAtEnd()) => { + onSent() + if (!nativeChatScrollsToLatestOnSend(useAppStore.getState().settings) && !readerWasAtEnd) { + return + } + beginNavigation() + scrollToBottom('send') + }, + [beginNavigation, onSent, readerAtEnd, scrollToBottom] + ) useImperativeHandle( ref, () => ({ diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx index 2a2d3f5090e..3bfadce54b5 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx @@ -20,6 +20,8 @@ import { nativeChatRowOffersRewind } from '../../../../../../shared/native-chat/ import { NativeChatForkContext } from '../actions/native-chat-fork-context' import { nativeChatSlotOffersFork } from '../actions/native-chat-side-chat-fork-point' import { isActionableStructuredAgentSessionPrompt } from '../../../../../../shared/agent-session/view/structured-agent-session-live-turn' +import { NativeChatNewRowsMarker } from '../../viewport/new-rows/NativeChatNewRowsMarker' +import type { NativeChatNewRowsMarkerState } from '../../viewport/new-rows/native-chat-new-rows-marker' /** Memoize shared context so unchanged rows keep their props during transcript updates. */ export type NativeChatTranscriptRowContext = { @@ -45,10 +47,13 @@ export type NativeChatTranscriptRowContext = { /** Wrap message, status and rollup for one virtualized measurement; internal spacing is the row’s, inter-row gaps the window’s. */ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ slot, - context + context, + newRowsMarker }: { slot: NativeChatTranscriptSlot context: NativeChatTranscriptRowContext + /** The "New" marker, when it draws in this row. */ + newRowsMarker?: NativeChatNewRowsMarkerState }): React.JSX.Element { // Offered only on the conversation's own turn-opening prompts (`nativeChatRowOffersRewind`). const rewind = useContext(NativeChatRewindContext) @@ -84,6 +89,9 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ const deliveryNotice = context.deliveryNotices?.get(message.id) const predecessors = context.taskListPredecessors.get(message.id) const expanded = turnKey ? context.expandedTurnIds.has(turnKey) : undefined + const marker = newRowsMarker ? ( + + ) : null const statusRow = status ? ( + {newRowsMarker?.place === 'above-row' ? marker : null} {/* A turn with no user bubble carries its bar above its first row. */} {slot.statusAbove ? statusRow : null} {!slot.drawsMessage ? null : receipt ? ( @@ -154,6 +163,7 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ workRun={workRun} /> )} + {newRowsMarker?.place === 'above-turn-bar' ? marker : null} {slot.statusAbove ? null : statusRow} {turnDiff ? : null} {openedPullRequests ? ( diff --git a/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatMessageList.new-rows-marker.test.tsx b/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatMessageList.new-rows-marker.test.tsx new file mode 100644 index 00000000000..ca44f3e5740 --- /dev/null +++ b/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatMessageList.new-rows-marker.test.tsx @@ -0,0 +1,172 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' + +import { act, cleanup, screen } from '@testing-library/react' +import { render } from '../../messages/actions/native-chat-tooltip-test-harness' +import { createRef } from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import { getDefaultSettings } from '../../../../../../shared/constants' +import { useAppStore } from '@/store' +import { NativeChatMessageList } from '../../NativeChatMessageList' +import type { NativeChatMessageListHandle } from '../../messages/actions/use-native-chat-reveal-latest' +import { + deliverResizes, + layout, + marker, + ROW_PITCH_PX, + scrollTranscript, + session, + stubLayout, + stubResizeObserver, + TRANSCRIPT_LENGTH +} from '../virtualization/native-chat-windowing-test-harness' + +// Pacing is not this test's subject. +vi.mock('../../markdown/use-native-chat-paced-text', async (importOriginal) => + (await import('../../markdown/native-chat-unpaced-text-fixture')).unpacedTextModule( + importOriginal + ) +) + +afterEach(cleanup) + +function chat( + length: number, + isVisible: boolean, + { + ref, + readCurrent = true + }: { ref?: React.Ref; readCurrent?: boolean } = {} +): React.JSX.Element { + const messages: NativeChatMessage[] = Array.from({ length }, (_, index) => ({ + ...marker(index), + journalPosition: { sequence: index + 1, index: 0 } + })) + return ( + + ) +} + +describe('the "New" marker in the transcript', () => { + let paneShown = true + let restore: (() => void)[] = [] + beforeEach(() => { + paneShown = true + vi.spyOn(document, 'hasFocus').mockReturnValue(true) + restore = [ + stubLayout({ scrollGeometry: true, offsetChain: true, isVisible: () => paneShown }), + stubResizeObserver() + ] + }) + afterEach(() => { + for (const undo of restore.toReversed()) { + undo() + } + layout.measuredRowHeights = [] + vi.restoreAllMocks() + }) + + // The window mounts only rows near the view; the marker's row is far from the end it opens at. + it('is drawn above the first row that came while the chat was hidden, however far back', () => { + const { rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + rerender(chat(TRANSCRIPT_LENGTH, false)) + rerender(chat(TRANSCRIPT_LENGTH + 60, true)) + + const row = screen.getByRole('separator', { name: 'New' }).closest('[data-index]') + expect(row?.dataset.index).toBe(String(TRANSCRIPT_LENGTH)) + }) + + it('tells a screen reader that new messages came, in a region that was already there', () => { + const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + const region = container.querySelector('[data-native-chat-scroll] ~ [aria-live="polite"]') + expect(region).toBeEmptyDOMElement() + + rerender(chat(TRANSCRIPT_LENGTH, false)) + rerender(chat(TRANSCRIPT_LENGTH + 60, true)) + expect(region).toHaveTextContent('New messages arrived while you were away') + }) + + it('is neither drawn nor announced when the reader turned it off', () => { + const settings = useAppStore.getState().settings + useAppStore.setState({ + settings: { ...getDefaultSettings('/tmp'), nativeChatMarkNewMessages: false } + }) + try { + const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + rerender(chat(TRANSCRIPT_LENGTH, false)) + rerender(chat(TRANSCRIPT_LENGTH + 60, true)) + + expect(screen.queryByRole('separator', { name: 'New' })).toBeNull() + expect( + container.querySelector('[data-native-chat-scroll] ~ [aria-live="polite"]') + ).toBeEmptyDOMElement() + } finally { + useAppStore.setState({ settings }) + } + }) + + it('goes once the reader sends something', () => { + const ref = createRef() + const { rerender } = render(chat(TRANSCRIPT_LENGTH, true, { ref })) + rerender(chat(TRANSCRIPT_LENGTH, false, { ref })) + rerender(chat(TRANSCRIPT_LENGTH + 60, true, { ref })) + expect(screen.getByRole('separator', { name: 'New' })).toBeInTheDocument() + + act(() => ref.current?.revealLatest()) + + expect(screen.queryByRole('separator', { name: 'New' })).toBeNull() + }) + + describe('when the reader comes back to new rows', () => { + /** Catch up after restoring the hidden pane’s scroll position. */ + function returnToNewRows(rerender: (ui: React.JSX.Element) => void, count = 60): void { + paneShown = false + rerender(chat(TRANSCRIPT_LENGTH, false, { readCurrent: false })) + paneShown = true + rerender(chat(TRANSCRIPT_LENGTH, true, { readCurrent: false })) + rerender(chat(TRANSCRIPT_LENGTH + count, true)) + } + const scrollTop = (container: HTMLElement): number | undefined => + container.querySelector('[data-native-chat-scroll]')?.scrollTop + + it('brings a reader who was at the end to where the new rows begin', () => { + const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + returnToNewRows(rerender) + + expect(scrollTop(container)).toBe(TRANSCRIPT_LENGTH * ROW_PITCH_PX) + }) + + it('keeps the reader where the new rows begin while a reply is still being drawn', async () => { + const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + returnToNewRows(rerender, 1) + + const drawn: number[] = [] + drawn[TRANSCRIPT_LENGTH] = 2_000 + layout.measuredRowHeights = drawn + act(() => void deliverResizes()) + await act(async () => { + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + }) + + expect(scrollTop(container)).toBe(TRANSCRIPT_LENGTH * ROW_PITCH_PX) + }) + + it('leaves a reader who was parked further up where they were', () => { + const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + const readingAt = 2_000 + scrollTranscript(container, readingAt) + returnToNewRows(rerender) + + expect(screen.getByRole('separator', { name: 'New' })).toBeInTheDocument() + expect(scrollTop(container)).toBe(readingAt) + }) + }) +}) diff --git a/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatNewRowsMarker.test.tsx b/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatNewRowsMarker.test.tsx new file mode 100644 index 00000000000..b90a1ddb8af --- /dev/null +++ b/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatNewRowsMarker.test.tsx @@ -0,0 +1,92 @@ +// @vitest-environment happy-dom + +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { NativeChatNewRowsMarker } from './NativeChatNewRowsMarker' +import type { NativeChatNewRowsMarkerState as Marker } from './native-chat-new-rows-marker' +import { overrideLayoutProperty } from '../virtualization/native-chat-windowing-test-harness' + +afterEach(cleanup) + +function marker(overrides: Partial = {}): Marker { + return { + key: 'answer', + place: 'above-row', + arriving: true, + onArrived: vi.fn(), + onDismiss: vi.fn(), + ...overrides + } +} + +const VIEWPORT_PX = 600 +const ROW_TOP_PX = 1_000 + +let restoreLayout: (() => void)[] = [] + +/** Place the view bottom aboveMarkerPx short of a marker positioned intoRowPx within its row. */ +function pane( + value: Marker, + { intoRowPx = 0, aboveMarkerPx = 0 }: { intoRowPx?: number; aboveMarkerPx?: number } = {} +) { + const isRow = (element: HTMLElement): boolean => element.hasAttribute('data-index') + const isMarker = (element: HTMLElement): boolean => element.getAttribute('role') === 'separator' + const layout = (name: string, get: (this: HTMLElement) => unknown) => + overrideLayoutProperty(name, { get }) + restoreLayout = [ + layout('clientHeight', () => VIEWPORT_PX), + layout('scrollTop', () => ROW_TOP_PX + intoRowPx - VIEWPORT_PX - aboveMarkerPx), + layout('offsetTop', function () { + return isRow(this) ? ROW_TOP_PX : isMarker(this) ? intoRowPx : 0 + }), + layout('offsetParent', function () { + return isRow(this) || isMarker(this) ? this.parentElement : null + }) + ] + const onReveal = vi.fn() + const view = render( +
+
+ +
+
+
+ +
+
+