fix(web): use exact turn boundaries for run time

This commit is contained in:
imccyu
2026-08-04 15:55:07 +08:00
parent 2a828f09da
commit cc435a9c0c
26 changed files with 146 additions and 116 deletions

View File

@@ -30,11 +30,12 @@ import type {
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
import { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives'
import type { ChatViewSlotProps } from '../contract/slots.ts'
import { assistantActionsSeqs, deriveChatFlow, lastInputTime, messageBranchSeqs, turnStartTimes, type ChatFlowItem } from './chat-flow.ts'
import { assistantActionsSeqs, deriveChatFlow, messageBranchSeqs, runningTurnStartTime, type ChatFlowItem } from './chat-flow.ts'
import { AssistantMarkdown } from './AssistantMarkdown.tsx'
import { GenericCommandCard } from './GenericCommandCard.tsx'
import { GenericToolCard } from './GenericToolCard.tsx'
import { MessageItem, PendingSteeringBubble } from './MessageItem.tsx'
import { formatRunDuration } from './message-chrome.ts'
import css from './ChatView.module.css'
const FOLLOW_THRESHOLD = 24
@@ -282,34 +283,37 @@ const CommandRow = memo(function CommandRow({ renderSlot, node, t }: {
})
/** Turn-level model activity label retained across first-token, tool, and streaming phases. */
function TurnStatus({ startTime }: {
/** The running turn's logged trigger time; null falls back to mount time
* (input node outside the window), which restarts the clock on reload. */
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 the logged trigger so a mid-turn reload keeps the real
// 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 [elapsedSeconds, setElapsedSeconds] = useState(() => Math.max(0, Math.floor((Date.now() - anchor) / 1000)))
const [elapsedMs, setElapsedMs] = useState(() => Math.max(0, Date.now() - anchor))
useEffect(() => {
const tick = (): void => {
setElapsedSeconds(Math.max(0, Math.floor((Date.now() - anchor) / 1000)))
setElapsedMs(Math.max(0, Date.now() - anchor))
}
tick()
const id = setInterval(tick, 1000)
return () => { clearInterval(id) }
}, [anchor])
const minutes = Math.floor(elapsedSeconds / 60)
const seconds = elapsedSeconds % 60
const clock = minutes > 0 ? `${minutes}m ${String(seconds).padStart(2, '0')}s` : `${seconds}s`
// Short turns keep the plain label; the clock only appears once the turn
// has clearly been running for a while.
const showClock = elapsedSeconds >= 15
const showClock = elapsedMs >= 15_000
return (
<div className={css.turnStatus} role="status" aria-live="polite">
Deep diving...
{showClock && <span className={css.turnStatusClock}>{clock}</span>}
{showClock && (
<span className={css.turnStatusClock} aria-hidden>
{formatRunDuration(elapsedMs, t)}
</span>
)}
</div>
)
}
@@ -333,6 +337,7 @@ export function ChatView({
useSession, useSessions, useStore, renderSlot, sessionId, openFile, loadOlder, inspectCall, chatScroll, forkAt, t,
}: ChatViewSlotProps) {
const nodes = useSession(s => s.nodes)
const turnTimings = useSession(s => s.turnTimings)
const turnEnds = useSession(s => s.turnEnds)
const inbox = useSession(s => s.queue)
// Workspace root off the session list row: path summaries display relative to it.
@@ -356,8 +361,7 @@ export function ChatView({
// text (before tools) omits `time` so AssistantMarkdown stays chrome-free.
const actionSeqs = useMemo(() => assistantActionsSeqs(nodes), [nodes])
const branchSeqs = useMemo(() => messageBranchSeqs(nodes, turnEnds), [nodes, turnEnds])
const turnStarts = useMemo(() => turnStartTimes(nodes), [nodes])
const runningTurnStart = useMemo(() => lastInputTime(nodes), [nodes])
const runningTurnStart = useMemo(() => runningTurnStartTime(turnTimings), [turnTimings])
const listRef = useRef<HTMLDivElement | null>(null)
const columnRef = useRef<HTMLDivElement | null>(null)
@@ -594,14 +598,16 @@ export function ChatView({
}
const node: ConversationNode = item.node
if (node.kind === 'assistant') {
const turnStart = actionSeqs.has(node.seq) ? turnStarts.get(node.turn) : undefined
const timing = actionSeqs.has(node.seq) ? turnTimings.get(node.turn) : undefined
return (
<AssistantMarkdown
blocks={node.blocks}
streaming={false}
interrupted={node.interrupted}
time={actionSeqs.has(node.seq) ? node.time : undefined}
runMs={turnStart === undefined ? undefined : Math.max(0, node.time - turnStart)}
runMs={timing?.endTime === undefined
? undefined
: Math.max(0, timing.endTime - timing.startTime)}
seq={node.seq}
onFork={forkAt}
forkUnavailable={!branchSeqs.has(node.seq)}
@@ -679,7 +685,7 @@ export function ChatView({
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} />}
{running && <TurnStatus startTime={runningTurnStart} t={t} />}
{pendingSteering.map(item => (
<PendingSteeringBubble key={item.id} content={item.content} t={t} />
))}

View File

@@ -50,7 +50,7 @@ export function MessageIconActions({
{runMs !== undefined && (
<>
<span className={css.runTimeDot} aria-hidden>·</span>
{t('message.ranFor', { duration: formatRunDuration(runMs) })}
{t('message.ranFor', { duration: formatRunDuration(runMs, t) })}
</>
)}
</span>

View File

@@ -9,7 +9,7 @@
* flow share their gates.
*/
import type {
AssistantBlock, ConversationNode, ToolResultNode,
AssistantBlock, ConversationNode, ConversationSnapshot, ToolResultNode,
} from '@deepseek-ai/dsh-client-runtime/client'
/** One renderable flow item; key is the React key and the parent's identity unit. */
@@ -48,40 +48,18 @@ export function assistantActionsSeqs(nodes: readonly ConversationNode[]): Readon
}
/**
* Approximate turn start times: turn number -> the time of the nearest
* user/steering node preceding the turn's first assistant node. Same
* derivation family as the trajectory fold (adjacent logged timestamps, no
* dedicated turn/start state); a turn whose triggering input is outside the
* loaded window is simply absent.
* @param nodes - snapshot nodes in event order.
* @returns Unix epoch ms per in-window turn with a visible trigger.
* Exact start time of the latest in-window turn without a matching end time.
* @param turnTimings - In-window turn timings in event order.
* @returns Unix epoch ms, or null when the running turn started outside the window.
*/
export function turnStartTimes(nodes: readonly ConversationNode[]): ReadonlyMap<number, number> {
const starts = new Map<number, number>()
let lastInputTime: number | null = null
for (const node of nodes) {
if (node.kind === 'user' || node.kind === 'steering') {
lastInputTime = node.time
} else if (node.kind === 'assistant' && lastInputTime !== null && !starts.has(node.turn)) {
starts.set(node.turn, lastInputTime)
}
export function runningTurnStartTime(
turnTimings: ConversationSnapshot['turnTimings'],
): number | null {
let latest: number | null = null
for (const timing of turnTimings.values()) {
if (timing.endTime === undefined) latest = timing.startTime
}
return starts
}
/**
* Time of the last user/steering node in the window: the running turn's
* trigger, anchoring the live TurnStatus clock to the same logged instant the
* finalized footer's run time is measured from.
* @param nodes - snapshot nodes in event order.
* @returns Unix epoch ms, or null when no input node is in-window.
*/
export function lastInputTime(nodes: readonly ConversationNode[]): number | null {
for (let i = nodes.length - 1; i >= 0; i--) {
const node = nodes[i]
if (node?.kind === 'user' || node?.kind === 'steering') return node.time
}
return null
return latest
}
/**

View File

@@ -6,6 +6,9 @@ import type { Translate } from '@deepseek-ai/dsh-client-ui-slots'
/** The date-template share of the conversation dictionary the clock consumes. */
export type ClockTranslate = Translate<'clock.md' | 'clock.ymd'>
/** The elapsed-duration share of the conversation dictionary. */
export type RunDurationTranslate = Translate<'duration.seconds' | 'duration.minutes'>
/**
* Best-effort clipboard write; rejections stay swallowed (no success chrome).
* @param text - Plain text to place on the clipboard.
@@ -72,16 +75,18 @@ export function msUntilNextLocalMidnight(ms: number): number {
}
/**
* Compact elapsed-time label for the turn run-time chrome, matching the
* running TurnStatus clock format: `15s` under a minute, `2m 05s` from there.
* Localized elapsed-time label shared by running and settled turn chrome.
* @param ms - Elapsed duration in milliseconds (negatives clamp to zero).
* @param t - Translate seat supplying the duration templates.
* @returns Display string in whole seconds.
*/
export function formatRunDuration(ms: number): string {
const total = Math.max(0, Math.round(ms / 1000))
export function formatRunDuration(ms: number, t: RunDurationTranslate): string {
const total = Math.max(0, Math.floor(ms / 1000))
const minutes = Math.floor(total / 60)
const seconds = total % 60
return minutes > 0 ? `${minutes}m ${String(seconds).padStart(2, '0')}s` : `${seconds}s`
return minutes > 0
? t('duration.minutes', { minutes, seconds: String(seconds).padStart(2, '0') })
: t('duration.seconds', { seconds })
}
/**

View File

@@ -69,6 +69,8 @@ export const zh = {
'message.retry.failure': '失败原因:',
'message.turnError': '本轮运行失败',
'message.ranFor': '用时 {duration}',
'duration.seconds': '{seconds}秒',
'duration.minutes': '{minutes}分{seconds}秒',
'command.running': '执行中…',
'command.failed': '命令失败',
'command.done': '已完成',
@@ -178,6 +180,8 @@ export const en = {
'message.retry.failure': 'Failure reason: ',
'message.turnError': 'This turn failed',
'message.ranFor': 'Ran for {duration}',
'duration.seconds': '{seconds}s',
'duration.minutes': '{minutes}m {seconds}s',
'command.running': 'Running…',
'command.failed': 'Command failed',
'command.done': 'Completed',