* feat(web): show exact per-turn token usage * test(runtime): refresh exact token usage snapshots * refactor(token-meter): own per-turn usage folding * perf(ui-chat): bound paging anchor layout reads * test(web): align usage golden with system prompt row * fix(test): resolve token-meter client from source * test(token-meter): cover retry without usage --------- Co-authored-by: ZiyaZhang <199893125+ZiyaZhang@users.noreply.github.com>
512 lines
20 KiB
TypeScript
512 lines
20 KiB
TypeScript
// An enclosing `[data-conversation-scroll]` owns scrolling when present;
|
|
// otherwise this view owns it. Each row subscribes to one stable node key.
|
|
|
|
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
|
import type {
|
|
ConversationTimelineSnapshot, RenderMessageImages,
|
|
} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
|
import { Button, IconChevronDownOutline14, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
|
|
import type { ChatViewSlotProps } from '../contract/slots.ts'
|
|
import { PendingSteeringBubble } from './MessageItem.tsx'
|
|
import { ChatNodeSeat } from './ChatNodeSeat.tsx'
|
|
import { formatRunDuration } from './message-chrome.ts'
|
|
import css from './ChatView.module.css'
|
|
|
|
const FOLLOW_THRESHOLD = 24
|
|
|
|
/** Active column host when present; otherwise the view-local scroller. */
|
|
function scrollerOf(from: HTMLElement): HTMLElement {
|
|
return (from.closest('[data-conversation-scroll]')) ?? from
|
|
}
|
|
|
|
interface PagingAnchor {
|
|
/** Stable node/call identity, independent of boundary-spanning group keys. */
|
|
key: string
|
|
/** Row top relative to the scrollport after the latest user scroll. */
|
|
top: number
|
|
}
|
|
|
|
/** Find an already-rendered row without interpolating a selector. */
|
|
function anchorElement(list: HTMLElement, key: string): HTMLElement | null {
|
|
for (const row of list.querySelectorAll<HTMLElement>('[data-chat-anchor-key]')) {
|
|
if (row.dataset.chatAnchorKey === key) return row
|
|
}
|
|
return null
|
|
}
|
|
|
|
/** Row position in scrollport coordinates (viewport-independent). */
|
|
function flowTop(row: HTMLElement, scrollport: HTMLElement): number {
|
|
return row.getBoundingClientRect().top - scrollport.getBoundingClientRect().top
|
|
}
|
|
|
|
/** Select a visible stable node/call identity, falling back only when layout
|
|
* has not exposed a visible box yet. */
|
|
function pagingAnchor(list: HTMLElement, scrollport: HTMLElement): HTMLElement | null {
|
|
const viewport = scrollport.getBoundingClientRect()
|
|
const composer = scrollport.querySelector<HTMLElement>('[data-composer-seat]')
|
|
const visibleBottom = composer?.getBoundingClientRect().top ?? viewport.bottom
|
|
// The leading edge preserves nested call identity when it hits a row.
|
|
// Chrome/gap misses use logarithmic layout reads over the ordered flex rows.
|
|
if (typeof document.elementsFromPoint === 'function' && visibleBottom > viewport.top) {
|
|
const content = list.getBoundingClientRect()
|
|
const left = Math.max(viewport.left, content.left)
|
|
const right = Math.min(viewport.right, content.right)
|
|
const x = left + Math.max(0, right - left) / 2
|
|
for (const element of document.elementsFromPoint(x, viewport.top + 1)) {
|
|
const row = element instanceof HTMLElement
|
|
? element.closest<HTMLElement>('[data-chat-anchor-key]')
|
|
: null
|
|
if (row !== null && list.contains(row)) return row
|
|
}
|
|
}
|
|
const rows = list.querySelectorAll<HTMLElement>('[data-chat-flow] > [data-chat-flow-key]:not(:empty)')
|
|
let low = 0
|
|
let high = rows.length
|
|
while (low < high) {
|
|
const middle = (low + high) >>> 1
|
|
if (rows.item(middle).getBoundingClientRect().bottom > viewport.top) high = middle
|
|
else low = middle + 1
|
|
}
|
|
const row = rows[low]
|
|
return row !== undefined && row.getBoundingClientRect().top < visibleBottom ? row : rows[0] ?? null
|
|
}
|
|
|
|
type ChatScrollPosition = NonNullable<ReturnType<ChatViewSlotProps['chatScroll']['read']>>
|
|
|
|
/** Capture a reflow-resistant reader position from the current rendered window. */
|
|
function scrollPosition(list: HTMLElement, scrollport: HTMLElement): ChatScrollPosition | null {
|
|
const row = pagingAnchor(list, scrollport)
|
|
const anchorKey = row?.dataset.chatAnchorKey
|
|
if (row === null || anchorKey === undefined) return null
|
|
return {
|
|
anchorKey,
|
|
anchorTop: flowTop(row, scrollport),
|
|
scrollTop: scrollport.scrollTop,
|
|
}
|
|
}
|
|
|
|
/** Host/OS refusal text for the file-open dialog; empty throws keep a locale fallback. */
|
|
function openFailureMessage(error: unknown, fallback: string): string {
|
|
const message = error instanceof Error ? error.message : String(error)
|
|
return message === '' ? fallback : message
|
|
}
|
|
|
|
/** ProducedFiles opens the session workspace as `.`. */
|
|
function isFolderOpenPath(path: string): boolean {
|
|
return path === '.'
|
|
}
|
|
|
|
function runningTurnStartTime(timeline: ConversationTimelineSnapshot): number | null {
|
|
let latest: number | null = null
|
|
for (const turn of timeline.turns.values()) {
|
|
if (turn.status === 'open' && turn.start !== undefined) latest = turn.start.time
|
|
}
|
|
return latest
|
|
}
|
|
|
|
/** Turn-level model activity label retained across first-token, tool, and streaming phases. */
|
|
function TurnStatus({ startTime, t }: {
|
|
/** The running turn's logged `turn/start` time; null falls back to mount
|
|
* time when that boundary is outside the window. */
|
|
startTime: number | null
|
|
/** The owning view's locale seat. */
|
|
t: ChatViewSlotProps['t']
|
|
}) {
|
|
const [mountedAt] = useState(() => Date.now())
|
|
// Anchored to turn/start so a mid-turn reload keeps the real
|
|
// elapsed time and the final footer's Ran-for label matches this clock.
|
|
const anchor = startTime ?? mountedAt
|
|
const [elapsedMs, setElapsedMs] = useState(() => Math.max(0, Date.now() - anchor))
|
|
useEffect(() => {
|
|
const tick = (): void => {
|
|
setElapsedMs(Math.max(0, Date.now() - anchor))
|
|
}
|
|
tick()
|
|
const id = setInterval(tick, 1000)
|
|
return () => { clearInterval(id) }
|
|
}, [anchor])
|
|
// Short turns keep the plain label; the clock only appears once the turn
|
|
// has clearly been running for a while.
|
|
const showClock = elapsedMs >= 15_000
|
|
return (
|
|
<div className={css.turnStatus} role="status" aria-live="polite">
|
|
{t('chat.deepDiving')}
|
|
{showClock && (
|
|
<span className={css.turnStatusClock} aria-hidden>
|
|
{formatRunDuration(elapsedMs, t)}
|
|
</span>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
/**
|
|
* The chat view slot entry: pure component over the composed props; each
|
|
* ordered business Node crosses the keyed renderer seat.
|
|
*/
|
|
export function ChatView({
|
|
useSession, useChat, useSessions, useStore, renderSlot, sessionId, openFile, loadOlder, loadImage, openView, chatScroll, forkAt,
|
|
fileMentions, t,
|
|
}: ChatViewSlotProps) {
|
|
const order = useChat(s => s.order)
|
|
const nodeStore = useChat(s => s.nodes)
|
|
const timeline = useChat(s => s.timeline)
|
|
const inbox = useSession(s => s.queue)
|
|
// Workspace root off the session list row: path summaries display relative to it.
|
|
const cwd = useSessions(s => s.byId[sessionId]?.cwd)
|
|
const running = useSession(s => s.running)
|
|
const openState = useSession(s => s.openState)
|
|
const openError = useSession(s => s.openError)
|
|
const hasMore = useSession(s => s.hasMore)
|
|
const loadingOlder = useSession(s => s.loadingOlder)
|
|
const selectedCallId = useStore(s => s.selection?.callId)
|
|
const inspectCall = useCallback((callId: string) => {
|
|
openView('trajectory', callId)
|
|
}, [openView])
|
|
const [fileOpenError, setFileOpenError] = useState<{ path: string; message: string } | null>(null)
|
|
const [fileOpenBusy, setFileOpenBusy] = useState(false)
|
|
// Close/retry must ignore a settlement that started before the latest
|
|
// gesture; otherwise a cancelled in-flight refusal reopens the dialog.
|
|
const fileOpenRequest = useRef(0)
|
|
|
|
const requestOpenFile = useCallback((path: string) => {
|
|
const id = ++fileOpenRequest.current
|
|
setFileOpenBusy(true)
|
|
void openFile(path).then(
|
|
() => {
|
|
if (id !== fileOpenRequest.current) return
|
|
setFileOpenError(null)
|
|
setFileOpenBusy(false)
|
|
},
|
|
(error: unknown) => {
|
|
if (id !== fileOpenRequest.current) return
|
|
setFileOpenError({
|
|
path,
|
|
message: openFailureMessage(
|
|
error,
|
|
t(isFolderOpenPath(path) ? 'fileOpen.folderUnknown' : 'fileOpen.unknown'),
|
|
),
|
|
})
|
|
setFileOpenBusy(false)
|
|
},
|
|
)
|
|
}, [openFile, t])
|
|
|
|
const closeFileOpenError = useCallback(() => {
|
|
fileOpenRequest.current += 1
|
|
setFileOpenError(null)
|
|
setFileOpenBusy(false)
|
|
}, [])
|
|
|
|
const pendingSteering = useMemo(
|
|
() => inbox.filter(item => item.placement === 'steering'),
|
|
[inbox],
|
|
)
|
|
const renderMessageImages = useCallback<RenderMessageImages>(
|
|
owner => renderSlot('conversation.message.images', { ...owner, loadImage }),
|
|
[loadImage, renderSlot],
|
|
)
|
|
const runningTurnStart = useMemo(() => runningTurnStartTime(timeline), [timeline])
|
|
|
|
const listRef = useRef<HTMLDivElement | null>(null)
|
|
const columnRef = useRef<HTMLDivElement | null>(null)
|
|
const atBottomRef = useRef(true)
|
|
const [atBottom, setAtBottom] = useState(true)
|
|
/** Last position delivered or written on the main thread. */
|
|
const observedTopRef = useRef(0)
|
|
/** Paging anchor: semantic row/position at click, updated by reader scrolls
|
|
* while the request is pending and restored after the prepend lands. */
|
|
const anchorRef = useRef<PagingAnchor | null>(null)
|
|
const firstSeqRef = useRef<number | null>(null)
|
|
const openedRef = useRef(false)
|
|
const lastKeyRef = useRef<string | null>(null)
|
|
const lastSteeringIdRef = useRef<string | null>(null)
|
|
/** Flow tip signature — follow-scroll only when this moves, never on a
|
|
* scroll-driven at-bottom chrome re-render (which would snap inertial
|
|
* scrolls the rest of the way to the floor). */
|
|
const followSigRef = useRef<string | null>(null)
|
|
|
|
const firstKey = order[0]
|
|
const firstSeq = firstKey === undefined ? null : nodeStore.get(firstKey)?.anchorSeq ?? null
|
|
const lastKey = order.at(-1) ?? null
|
|
const lastNode = lastKey === null ? undefined : nodeStore.get(lastKey)
|
|
const lastSteeringId = pendingSteering[pendingSteering.length - 1]?.id ?? null
|
|
const followSig = `${openState}:${firstSeq}:${lastKey}:${order.length}:${running ? 1 : 0}:${lastSteeringId ?? ''}`
|
|
|
|
const toBottom = (el: HTMLElement): void => {
|
|
anchorRef.current = null
|
|
el.scrollTop = el.scrollHeight
|
|
observedTopRef.current = el.scrollTop
|
|
atBottomRef.current = true
|
|
setAtBottom(true)
|
|
chatScroll.save(null)
|
|
}
|
|
|
|
useLayoutEffect(() => {
|
|
const local = listRef.current
|
|
/* v8 ignore next -- ref-null guard: React attaches the ref before layout effects run. */
|
|
if (local === null) return
|
|
const el = scrollerOf(local)
|
|
// Open completed: jump to the bottom once — unless a scroll position
|
|
// survives from a previous mount (view-tab switch away and back), which
|
|
// is restored instead of snapping the reader back to the floor.
|
|
if (openState === 'open' && !openedRef.current) {
|
|
openedRef.current = true
|
|
const saved = chatScroll.read()
|
|
if (saved === null) {
|
|
toBottom(el)
|
|
} else {
|
|
el.scrollTop = saved.scrollTop
|
|
const row = anchorElement(local, saved.anchorKey)
|
|
if (row !== null) el.scrollTop += flowTop(row, el) - saved.anchorTop
|
|
observedTopRef.current = el.scrollTop
|
|
const isAtBottom = el.scrollHeight - el.scrollTop - el.clientHeight <= FOLLOW_THRESHOLD + 1
|
|
atBottomRef.current = isAtBottom
|
|
setAtBottom(isAtBottom)
|
|
const normalized = isAtBottom ? null : scrollPosition(local, el)
|
|
if (isAtBottom) chatScroll.save(null)
|
|
else if (normalized !== null) chatScroll.save(normalized)
|
|
}
|
|
firstSeqRef.current = firstSeq
|
|
lastKeyRef.current = lastKey
|
|
lastSteeringIdRef.current = lastSteeringId
|
|
followSigRef.current = followSig
|
|
return
|
|
}
|
|
// Prepend (head seq decreased): preserve the same settled row at the
|
|
// position established by the reader's latest scroll. This excludes
|
|
// unrelated tail/composer growth while the request was in flight.
|
|
if (anchorRef.current !== null && firstSeq !== null && firstSeqRef.current !== null && firstSeq < firstSeqRef.current) {
|
|
const anchor = anchorRef.current
|
|
anchorRef.current = null
|
|
const row = anchorElement(local, anchor.key)
|
|
if (row !== null) el.scrollTop += flowTop(row, el) - anchor.top
|
|
observedTopRef.current = el.scrollTop
|
|
firstSeqRef.current = firstSeq
|
|
/* v8 ignore next -- ?? arm: a prepend adds nodes, so the flow list here is never empty. */
|
|
lastKeyRef.current = lastKey
|
|
lastSteeringIdRef.current = lastSteeringId
|
|
followSigRef.current = followSig
|
|
return
|
|
}
|
|
firstSeqRef.current = firstSeq
|
|
// Own words must be visible: a new trailing user node force-scrolls
|
|
// (send lives in the composer, so arrival is detected here, not armed there).
|
|
const appendedUser = lastKey !== lastKeyRef.current && lastNode?.kind === 'user'
|
|
const appendedSteering = lastSteeringId !== null && lastSteeringId !== lastSteeringIdRef.current
|
|
const tipMoved = followSigRef.current !== followSig
|
|
lastKeyRef.current = lastKey
|
|
lastSteeringIdRef.current = lastSteeringId
|
|
followSigRef.current = followSig
|
|
// Follow new flow content while pinned; do NOT re-pin on every render
|
|
// merely because atBottomRef is true (scroll threshold → setState → snap).
|
|
if (appendedUser || appendedSteering || (tipMoved && atBottomRef.current)) toBottom(el)
|
|
})
|
|
|
|
const onScrollRef = useRef(() => {})
|
|
onScrollRef.current = () => {
|
|
const local = listRef.current
|
|
/* v8 ignore next -- ref-null guard: the handler only fires while mounted. */
|
|
if (local === null) return
|
|
const el = scrollerOf(local)
|
|
// Only reader input may make raw scroll geometry change follow ownership:
|
|
// a delivered position that deviates from the observed-top ledger (every
|
|
// programmatic write records itself there synchronously). This covers
|
|
// wheel, touch, scrollbar, and keyboard alike without naming devices.
|
|
// Browser shrink-clamps land exactly on the floor min and delayed
|
|
// programmatic deliveries land on the ledger itself, so both preserve
|
|
// the current ownership state.
|
|
const floor = Math.max(0, el.scrollHeight - el.clientHeight)
|
|
const movedByReader = Math.abs(el.scrollTop - Math.min(observedTopRef.current, floor)) > 0.5
|
|
const isAtBottom = movedByReader
|
|
? floor - el.scrollTop <= FOLLOW_THRESHOLD + 1
|
|
: atBottomRef.current
|
|
if (!movedByReader && isAtBottom) {
|
|
toBottom(el)
|
|
return
|
|
}
|
|
atBottomRef.current = isAtBottom
|
|
setAtBottom(isAtBottom)
|
|
const position = isAtBottom ? null : scrollPosition(local, el)
|
|
if (isAtBottom) {
|
|
anchorRef.current = null
|
|
} else if (anchorRef.current !== null && position !== null) {
|
|
anchorRef.current = { key: position.anchorKey, top: position.anchorTop }
|
|
}
|
|
// Continuous save (unmount happens after ref detach, so saving there is
|
|
// too late); pinned-to-bottom clears so a remount keeps following.
|
|
if (isAtBottom) chatScroll.save(null)
|
|
else if (position !== null) chatScroll.save(position)
|
|
observedTopRef.current = el.scrollTop
|
|
}
|
|
|
|
// Bind the scroll listener on the resolved scrollport once per mount;
|
|
// reader-input attribution rides the observed-top ledger, not per-device
|
|
// input listeners.
|
|
useEffect(() => {
|
|
const local = listRef.current
|
|
/* v8 ignore next -- ref-null guard: effect runs after the list node commits. */
|
|
if (local === null) return
|
|
const el = scrollerOf(local)
|
|
const onScroll = (): void => { onScrollRef.current() }
|
|
el.addEventListener('scroll', onScroll, { passive: true })
|
|
return () => {
|
|
el.removeEventListener('scroll', onScroll)
|
|
}
|
|
}, [])
|
|
|
|
// The ref starts null and is assigned every render, so the placeholder
|
|
// initializer a function initial value would need never exists.
|
|
const followRef = useRef<(() => void) | null>(null)
|
|
followRef.current = () => {
|
|
const local = listRef.current
|
|
if (local !== null && atBottomRef.current) {
|
|
const el = scrollerOf(local)
|
|
el.scrollTop = el.scrollHeight
|
|
observedTopRef.current = el.scrollTop
|
|
chatScroll.save(null)
|
|
}
|
|
}
|
|
// Streaming, tool disclosures, and other flow changes resize the column;
|
|
// the sticky composer resizes outside it. This observer owns ChatView's
|
|
// dynamic-height follow decisions and writes only while the reader is pinned.
|
|
useEffect(() => {
|
|
const column = columnRef.current
|
|
const local = listRef.current
|
|
if (column === null || local === null || typeof ResizeObserver === 'undefined') return
|
|
const scrollport = scrollerOf(local)
|
|
const composer = scrollport.querySelector<HTMLElement>('[data-composer-seat]')
|
|
const observer = new ResizeObserver(() => { followRef.current?.() })
|
|
observer.observe(column)
|
|
if (composer !== null) observer.observe(composer)
|
|
return () => { observer.disconnect() }
|
|
}, [])
|
|
|
|
// A failed/empty page leaves the head unchanged. Once the request leaves
|
|
// its busy state there is no future prepend for the saved anchor to own.
|
|
useEffect(() => {
|
|
if (!loadingOlder) anchorRef.current = null
|
|
}, [loadingOlder])
|
|
|
|
const loadOlderAnchored = (): void => {
|
|
const local = listRef.current
|
|
/* v8 ignore next -- ref-null guard: the paging button renders inside the list tree. */
|
|
if (local !== null) {
|
|
const el = scrollerOf(local)
|
|
const row = pagingAnchor(local, el)
|
|
if (row !== null && row.dataset.chatAnchorKey !== undefined) {
|
|
anchorRef.current = {
|
|
key: row.dataset.chatAnchorKey,
|
|
top: flowTop(row, el),
|
|
}
|
|
}
|
|
}
|
|
loadOlder()
|
|
}
|
|
|
|
return (
|
|
<div className={css.root}>
|
|
<div ref={listRef} className={css.scroll}>
|
|
<div ref={columnRef} className={css.column} data-chat-flow="">
|
|
{openState === 'loading' && <div className={css.hint}>{t('chat.loadingHistory')}</div>}
|
|
{openState === 'error' && openError !== null && (
|
|
<div className={css.openError}>
|
|
{t('chat.loadError', { message: openError.message, code: openError.code })}
|
|
</div>
|
|
)}
|
|
{hasMore && (
|
|
<div className={css.older}>
|
|
<button type="button" disabled={loadingOlder} onClick={loadOlderAnchored}>
|
|
{loadingOlder ? t('loading') : t('chat.loadOlder')}
|
|
</button>
|
|
</div>
|
|
)}
|
|
{order.map(nodeKey => (
|
|
<ChatNodeSeat
|
|
key={nodeKey}
|
|
nodeKey={nodeKey}
|
|
useChat={useChat}
|
|
selectedCallId={selectedCallId}
|
|
cwd={cwd}
|
|
openFile={requestOpenFile}
|
|
inspectCall={inspectCall}
|
|
forkAt={forkAt}
|
|
renderMessageImages={renderMessageImages}
|
|
fileMentions={fileMentions}
|
|
renderSlot={renderSlot}
|
|
t={t}
|
|
/>
|
|
))}
|
|
{/* No pending placeholders: questions (ui-user-questions) and approvals
|
|
(ApprovalPanel) both take over the composer, so a flow card would
|
|
double-render the same wait. */}
|
|
{/* Turn-level loading signal: rides the whole running turn (first-token
|
|
wait, tool execution, streaming) so it never flickers per step. */}
|
|
{running && <TurnStatus startTime={runningTurnStart} t={t} />}
|
|
{pendingSteering.map(item => (
|
|
<PendingSteeringBubble
|
|
key={item.id}
|
|
content={item.content}
|
|
renderMessageImages={renderMessageImages}
|
|
t={t}
|
|
/>
|
|
))}
|
|
</div>
|
|
{!atBottom && (
|
|
<div className={css.toBottomSlot}>
|
|
<button
|
|
type="button"
|
|
className={css.toBottom}
|
|
aria-label={t('chat.toBottom')}
|
|
onClick={() => {
|
|
const local = listRef.current
|
|
/* v8 ignore next -- ref-null guard: the button only renders alongside the mounted list. */
|
|
if (local !== null) toBottom(scrollerOf(local))
|
|
}}
|
|
>
|
|
<IconChevronDownOutline14 />
|
|
</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
{fileOpenError !== null && (
|
|
<FileOpenErrorDialog
|
|
path={fileOpenError.path}
|
|
message={fileOpenError.message}
|
|
busy={fileOpenBusy}
|
|
onClose={closeFileOpenError}
|
|
onRetry={() => { requestOpenFile(fileOpenError.path) }}
|
|
t={t}
|
|
/>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
/** In-page Host open-path refusal: the wire reason plus a retry of the same path. */
|
|
function FileOpenErrorDialog({
|
|
path, message, busy, onClose, onRetry, t,
|
|
}: {
|
|
path: string
|
|
message: string
|
|
busy: boolean
|
|
onClose: () => void
|
|
onRetry: () => void
|
|
t: ChatViewSlotProps['t']
|
|
}) {
|
|
return (
|
|
<Modal
|
|
open
|
|
onClose={onClose}
|
|
closeLabel={t('close')}
|
|
title={t(isFolderOpenPath(path) ? 'fileOpen.folderTitle' : 'fileOpen.title')}
|
|
description={message}
|
|
footer={(
|
|
<>
|
|
<Button variant="outline" className={css.modalAction} onClick={onClose}>{t('cancel')}</Button>
|
|
<Button variant="primary" className={css.modalAction} disabled={busy} onClick={onRetry}>{t('retry')}</Button>
|
|
</>
|
|
)}
|
|
/>
|
|
)
|
|
}
|