Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.
Rust ai-agentsai-gatewayclaude-codecodexcoding-agentcost-optimizationdeepseekllm-gatewayllm-routerlocal-firstmodel-routingrusttask-routingtauri
fix: keep live session timelines consistent and recoverable (#212)
澄潭138cd26e568a
diff --git a/apps/desktop/src/features/RoutingTimeline.tsx b/apps/desktop/src/features/RoutingTimeline.tsxindex ae125659..c05876fa 100644--- a/apps/desktop/src/features/RoutingTimeline.tsx+++ b/apps/desktop/src/features/RoutingTimeline.tsx@@ -21,9 +21,9 @@ export type TimelineTurn = {branch_id: string | null; model_configuration_id: string | null; reasoning_profile_id: string | null; group: string | null;selection: { simple_probability: number | null; simple_threshold_millis: number | null; selection_reason: string; competence_trigger?: { score: number; floor_millis: number } | null; historical_protection?: TimelineProtection | null } | null;tool_continuations: number; relays: { request_id: string; from_model: string | null; to_model: string | null }[];- assessment_state: string; assessment: { score: number; partial: boolean; target_from_ordinal: number; target_through_ordinal: number } | null;+ assessment_state: string; assessment: { score: number; partial: boolean; target_from_turn_id?: string; target_through_turn_id?: string; target_from_ordinal: number; target_through_ordinal: number } | null;competence_floor_millis: number | null; protected_turn_ids: string[]; status: string; requests: TimelineRequest[];- transitions?: { kind: string; request_id: string; model: { native_model: string | null }; previous_model: { native_model: string | null } | null; completeness: string }[];+ transitions?: { kind: string; request_id: string; previous_request_id?: string | null; model_changed?: boolean | null; reasoning_changed?: boolean | null; model: { native_model: string | null }; previous_model: { native_model: string | null } | null; completeness: string }[];cost_by_model: Cost[]; evidence_partial: boolean; content_digest: string;};type TimelinePage = { turns: TimelineTurn[]; watermark: string; complete: boolean };@@ -38,8 +38,8 @@ const TICKS = 18;const REQUESTS = 6;/** `active` allows reads at all; `displayed` adds continuing polling. Otherwise one probe settles availability. */-export function RoutingTimeline({ session, language, active, displayed, refreshVersion, requestId, onSelectRequest, onOpenPerformance, onViewConversation, onAvailability }: {- session: string; language: 'zh' | 'en'; active: boolean; displayed: boolean; refreshVersion: number; requestId: string | null;+export function RoutingTimeline({ session, language, active, displayed, refreshVersion, requestId, contentCleared = false, clearedRequestIds = [], onSelectRequest, onOpenPerformance, onViewConversation, onAvailability }: {+ session: string; language: 'zh' | 'en'; active: boolean; displayed: boolean; refreshVersion: number; requestId: string | null; contentCleared?: boolean; clearedRequestIds?: readonly string[];onSelectRequest(request: TimelineRequest): void; onOpenPerformance(plan: string): void;onViewConversation?(request: TimelineRequest): void; onAvailability?(availability: TimelineAvailability): void;}) {@@ -58,12 +58,13 @@ export function RoutingTimeline({ session, language, active, displayed, refreshVconst blockedScope = useRef(false);const probed = useRef(false);const lastRead = useRef(-Infinity);+ const failures = useRef(0);const stored = useRef(new Map<string, TimelineTurn>());const scroller = useRef<HTMLDivElement>(null);const timeline = useRef<HTMLElement>(null);const pendingFocus = useRef<{ from: Element; owner: string; attribute: 'data-overview-turn' | 'data-turn-id' } | null>(null);useEffect(() => { blockedScope.current = false; setError(''); }, [session]);- useEffect(() => { watermark.current = null; probed.current = false; lastRead.current = -Infinity; stored.current.clear(); setTurns([]); setSelected(null); setOverviewFocus(null); setLoaded(false); setArrivals(new Set()); setUnseen([]); }, [session, refreshVersion]);+ useEffect(() => { watermark.current = null; probed.current = false; lastRead.current = -Infinity; failures.current = 0; stored.current.clear(); setTurns([]); setSelected(null); setOverviewFocus(null); setLoaded(false); setArrivals(new Set()); setUnseen([]); }, [session, refreshVersion]);useEffect(() => {if (!arrivals.size) return;const timer = window.setTimeout(() => setArrivals(new Set()), 600);@@ -104,7 +105,7 @@ export function RoutingTimeline({ session, language, active, displayed, refreshVfor (const turn of page.turns) { if (stored.current.get(turn.turn_id)?.content_digest !== turn.content_digest) { stored.current.set(turn.turn_id, turn); changed = true; } }if (fresh.length) { setArrivals(previous => new Set([...previous, ...fresh])); setUnseen(previous => [...new Set([...previous, ...fresh])]); }if (changed) setTurns([...stored.current.values()].sort((a, b) => a.started_at_ms - b.started_at_ms || a.turn_id.localeCompare(b.turn_id)));- watermark.current = page.watermark; setError(''); setLoaded(true);+ watermark.current = page.watermark; failures.current = 0; setError(''); setLoaded(true);if (!page.complete) schedule(0);else { probed.current = true; if (displayed) schedule(2000); }} catch (e) {@@ -117,7 +118,13 @@ export function RoutingTimeline({ session, language, active, displayed, refreshVif (stale) { watermark.current = null; stored.current.clear(); setTurns([]); setLoaded(false); setArrivals(new Set()); setUnseen([]); }setError(code);if (stale) schedule(0);- else { probed.current = true; if (displayed && !blockedScope.current) schedule(2000); }+ else {+ probed.current = true;+ // Keep one visible read in flight; repeated transient failures back off,+ // while actual capacity limits require an explicit retry.+ const delay = Math.min(30_000, 2000 * 2 ** Math.min(failures.current++, 4));+ if (displayed && !blockedScope.current) schedule(delay);+ }} finally { inFlight = false; lastRead.current = performance.now(); }}const visible = () => { if (document.visibilityState === 'visible') void load(); else window.clearTimeout(timer); };@@ -175,7 +182,14 @@ export function RoutingTimeline({ session, language, active, displayed, refreshVconst selectedTurn = turns.find(t => t.turn_id === selected) ?? turns[turns.length - 1];const overviewTabStop = turns.some(turn => turn.turn_id === overviewFocus) ? overviewFocus : selectedTurn?.turn_id;- const index = (turn: TimelineTurn) => turns.indexOf(turn) + 1;+ const coordinates = new Map(turns.map((turn, i) => [turn.turn_id, i + 1]));+ const index = (turn: TimelineTurn) => coordinates.get(turn.turn_id)!;+ const assessmentCoordinates = new Map<string, number | null>();+ for (const turn of turns) {+ // Assessments refer to authoritative AgentTurnId, while timeline selection+ // uses the opening RequestId. Ambiguous retained identities cannot locate a score.+ if (turn.agent_turn_id) assessmentCoordinates.set(turn.agent_turn_id, assessmentCoordinates.has(turn.agent_turn_id) ? null : index(turn));+ }const boundary = (turn: TimelineTurn) => turn.boundary === 'new_user_message' ? text('新消息', 'New message') : turn.boundary === 'context_rebuilt' ? text('上下文重建', 'Context rebuilt') : text('边界未确认', 'Boundary unknown');const laneName = (lane: Lane) => lane === 'primary' ? text('主力', 'Primary') : lane === 'regular' ? text('常规', 'Regular') : text('分组未记录', 'Group unknown');const tone = (lane: Lane) => lane === 'regular' ? 'cyan' : lane === 'primary' ? 'purple' : '';@@ -266,7 +280,13 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV}function scoreExplanation(turn: TimelineTurn) {if (turn.assessment) {- const covered = text(`覆盖轮次 ${turn.assessment.target_from_ordinal}–${turn.assessment.target_through_ordinal}`, `covers turns ${turn.assessment.target_from_ordinal}–${turn.assessment.target_through_ordinal}`);+ const from = assessmentCoordinates.get(turn.assessment.target_from_turn_id ?? '');+ const through = assessmentCoordinates.get(turn.assessment.target_through_turn_id ?? '');+ // Producer ordinals can restart across epochs; only exact identities share+ // the same coordinates as the overview, lane headings and selected detail.+ const covered = typeof from === 'number' && typeof through === 'number' && from <= through+ ? from === through ? text(`覆盖轮次 T${from}`, `covers turn T${from}`) : text(`覆盖轮次 T${from}–T${through}`, `covers turns T${from}–T${through}`)+ : text('覆盖范围包含当前已加载范围外或身份未确认的轮次', 'covers turns outside the loaded range or without a confirmed identity');const floor = turn.competence_floor_millis != null ? text(`,下限 ${fixed(turn.competence_floor_millis)}`, `, floor ${fixed(turn.competence_floor_millis)}`) : '';const protectedNext = turn.protected_turn_ids.length ? text('低于下限,下一轮交给主力。', ' Below the floor, so the next agent turn went to Primary.') : '';return text(`阶段评分${covered}${floor}。${turn.assessment.partial ? '证据不完整。' : ''}${protectedNext}`, `This stage score ${covered}${floor}.${turn.assessment.partial ? ' Evidence is incomplete.' : ''}${protectedNext}`);@@ -285,7 +305,7 @@ export function RoutingTimeline({ session, language, active, displayed, refreshVreturn <div className="routing-turn-detail"><div className="routing-detail-main"><div className="routing-detail-head">- <strong>T{index(selectedTurn)}</strong><span className="badge no-dot">{boundary(selectedTurn)}</span><span className={`badge no-dot ${tone(lane)}`}>{modelOf(selectedTurn) ?? text('模型未记录', 'Model unknown')}</span>+ <strong>T{index(selectedTurn)}</strong><span className="badge no-dot">{boundary(selectedTurn)}</span><span className={`badge no-dot ${tone(lane)}`}>{text('模型:', 'Model: ')}{modelOf(selectedTurn) ?? text('未记录', 'unknown')}</span><span className="routing-detail-actions">{onViewConversation && selectedTurn.requests[0] && <button type="button" className="btn btn-quiet" onClick={() => onViewConversation(selectedTurn.requests[0])}>{text('查看对话', 'View conversation')}</button>}{selectedTurn.plan_id && <button type="button" className="btn btn-quiet" onClick={() => onOpenPerformance(selectedTurn.plan_id!)}>{text('查看模型表现', 'View model performance')}</button>}@@ -295,7 +315,7 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV? text('依据:会话第一轮,或网关确认对话延续并重新判断。客户端自动追加的后台消息也可能满足此规则。', 'Basis: the first session turn, or a fresh decision on gateway-confirmed continuing history. Client-generated background messages can also meet this rule.'): selectedTurn.boundary === 'context_rebuilt' ? text('上下文中的消息步骤比上一份可比较记录少,按压缩归因;已重新判断。回退或共享会话的后台、子代理请求也可能满足此条件。', 'The context has fewer message steps than the prior comparable checkpoint, so this is attributed to compaction and judged again. Rewinds or background and subagent requests sharing a session can also meet this condition.'): text('没有足够记录确认这一轮的起因。', 'The retained records do not establish what started this turn.')}</p>- {selectedTurn.requests[0] && <blockquote className="routing-quote"><ContentExcerpt request={selectedTurn.requests[0].request_id} language={language} fallback={text('这一轮的消息未记录或已清理', 'This turn’s message is unrecorded or cleared')} limit={140} revision={selectedTurn.content_digest} /></blockquote>}+ {selectedTurn.requests[0] && <blockquote className="routing-quote"><ContentExcerpt active={active && displayed} contentCleared={contentCleared || clearedRequestIds.includes(selectedTurn.requests[0].request_id)} request={selectedTurn.requests[0].request_id} language={language} fallback={text('这一轮的消息未记录或已清理', 'This turn’s message is unrecorded or cleared')} limit={140} revision={selectedTurn.content_digest} /></blockquote>}<div className="routing-detail-block"><span>{text('阶段开始时的模型选择', 'Model selection at the start of this stage')}</span>{historicalExplanation(selectedTurn)}</div><div className="routing-detail-block"><span>{text('胜任评分', 'Competence score')}</span><div><span className={`routing-score ${scoreTone(selectedTurn)}`}>{score(selectedTurn)}</span></div><p>{scoreExplanation(selectedTurn)}</p></div><p className="routing-detail-facts">{[@@ -305,7 +325,15 @@ export function RoutingTimeline({ session, language, active, displayed, refreshVselectedTurn.reasoning_profile_id ? text(`思考 ${selectedTurn.reasoning_profile_id}`, `reasoning ${selectedTurn.reasoning_profile_id}`) : '',selectedTurn.evidence_partial ? text('证据不完整', 'Incomplete evidence') : '',].filter(Boolean).join(' · ')}</p>- {changes.map((change, i) => <p key={`transition-${i}`} className="routing-detail-facts">{transition(change.kind)}{change.previous_model?.native_model && ` · ${change.previous_model.native_model} → ${change.model.native_model ?? '?'}`}</p>)}+ {changes.map((change, i) => {+ const withinTurn = Boolean(change.previous_request_id && selectedTurn.requests.some(request => request.request_id === change.previous_request_id));+ const label = change.kind !== 'unknown' || !withinTurn ? transition(change.kind)+ : change.completeness !== 'complete' ? text('请求间切换证据尚不完整', 'Request transition evidence incomplete')+ : change.model_changed ? text('本轮请求间模型变化', 'Model change between requests in this turn')+ : change.reasoning_changed ? text('本轮请求间推理设置变化', 'Reasoning change between requests in this turn')+ : text('本轮请求间变化未分类', 'Unclassified transition between requests in this turn');+ return <p key={`transition-${i}`} className="routing-detail-facts">{label}{change.previous_model?.native_model && ` · ${change.previous_model.native_model} → ${change.model.native_model ?? '?'}`}</p>;+ })}{selectedTurn.relays.map((relay, i) => <p key={`relay-${i}`} className="routing-detail-facts">{text('接力', 'Relay')} · {relay.from_model ?? '?'} → {relay.to_model ?? '?'}</p>)}</div><div className="routing-detail-requests">@@ -322,8 +350,8 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV})();return <section className="routing-timeline" ref={timeline} aria-label={text('路由时间线', 'Routing timeline')}>- <div className="routing-live" role="status"><span className={`routing-live-dot${running ? ' running' : ''}`} />{running ? text(`实时 · 第 ${turns.length} 轮正在执行`, `Live · agent turn ${turns.length} is running`) : text('实时', 'Live')}<span className="muted">{text('可见时每 2 秒更新', 'Updates every 2 s while visible')}</span></div>- {error && <div className="callout warn" role="alert" data-error-code={error}><span>{blocked ? text('这条会话超出完整读取范围,暂时无法显示时间线。', 'This session exceeds the complete-read limit; its timeline is unavailable.') : text('更新暂时不可用,已读取内容保留。', 'Updates are temporarily unavailable. Loaded records are retained.')}</span><button className="btn" onClick={() => { blockedScope.current = false; lastRead.current = -Infinity; setRetry(n => n + 1); }}>{text('重试', 'Retry')}</button></div>}+ <div className="routing-live" role="status"><span className={`routing-live-dot${running && !error ? ' running' : ''}`} />{error ? text('更新延迟', 'Update delayed') : running ? text(`实时 · 第 ${turns.length} 轮正在执行`, `Live · agent turn ${turns.length} is running`) : text('实时', 'Live')}<span className="muted">{error ? blocked ? text('等待手动重试', 'Waiting for Retry') : text('可见时自动重试', 'Retries automatically while visible') : text('可见时每 2 秒更新', 'Updates every 2 s while visible')}</span></div>+ {error && <div className="callout warn" role="alert" data-error-code={error}><span>{blocked ? text('这条会话超出完整读取范围,暂时无法显示时间线。', 'This session exceeds the complete-read limit; its timeline is unavailable.') : turns.length ? text('更新暂时不可用,显示上次读取的内容。', 'Updates are temporarily unavailable. Showing the last successful read.') : text('暂时无法读取,正在自动重试。', 'The read is temporarily unavailable. Retrying automatically.')}</span><button className="btn" onClick={() => { blockedScope.current = false; failures.current = 0; lastRead.current = -Infinity; setRetry(n => n + 1); }}>{text('重试', 'Retry')}</button></div>}{!loaded && !error && <p className="muted" role="status">{text('正在读取轮次…', 'Reading turns…')}</p>}{loaded && !turns.length && <p className="muted">{text('还没有可显示的轮次。', 'No recorded turns yet.')}</p>}{turns.length > 0 && <div className="routing-tiles">@@ -365,7 +393,7 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV<div className="routing-lanes-scroll" ref={scroller} onScroll={markVisible}><div className="routing-lanes" role="group" aria-label={text('Agent 轮次', 'Agent turns')} data-lanes={lanes.length}><div className="routing-lane-corner" />- {lanes.map(lane => <div key={lane} className={`routing-lane-label ${tone(lane)}`}><strong>{laneName(lane)}</strong>{laneModel(lane) && <span>{laneModel(lane)}</span>}</div>)}+ {lanes.map(lane => <div key={lane} className={`routing-lane-label ${tone(lane)}`}><strong>{laneName(lane)}</strong>{laneModel(lane) && <span>{text('模型:', 'Model: ')}{laneModel(lane)}</span>}</div>)}{/* One column per agent turn; the grid flows by column, so focus and reading order follow time. */}{turns.map(turn => <Fragment key={turn.turn_id}><div className="routing-turn-head" title={new Date(turn.started_at_ms).toLocaleString(language === 'zh' ? 'zh-CN' : 'en')}><strong>T{index(turn)}</strong>{turn.boundary !== 'unknown' && <span className="badge no-dot">{boundary(turn)}</span>}</div>diff --git a/apps/desktop/src/features/Sessions.tsx b/apps/desktop/src/features/Sessions.tsxindex 21bfe4bc..da22330c 100644--- a/apps/desktop/src/features/Sessions.tsx+++ b/apps/desktop/src/features/Sessions.tsx@@ -19,6 +19,7 @@ type Content = { content_id: string; role: string; kind: string; state: string;type Hit = { session_id: string; request_id: string; content_id: string; original_text_offset: number };type Ancestry = { roots: { state: string }[]; gap: string | null };type ContentState = 'recorded' | 'partial' | 'cleared';+const isCleared = (completeness?: string) => completeness === 'deleted' || completeness === 'expired';const errorCode = (error: unknown) => safeDiagnosticCode(error, 'LOCAL_SERVICE_UNAVAILABLE');function sessionTimeLabel(value: number, language: 'zh' | 'en') {const date = new Date(value);@@ -89,6 +90,16 @@ export function Sessions({ initialSession = null, initialRequest = null, languagconst keywordTimer = useRef<number | null>(null);const initialTarget = useRef(initialSession);const initialRequestTarget = useRef(initialRequest);+ function acceptSummaryVisibility(summaries: Summary[]) {+ // Called only after the read's generation guard. Current metadata supersedes+ // a local cleanup-success hint, including a session revived by new traffic.+ setSessionContentStates(current => {+ if (!summaries.some(item => item.session_id in current)) return current;+ const next = { ...current };+ for (const item of summaries) delete next[item.session_id];+ return next;+ });+ }function clearTimelineSelection() {timelineGeneration.current++;setBusy(false); setTimelineError('');@@ -120,6 +131,7 @@ export function Sessions({ initialSession = null, initialRequest = null, languag} else {const page = await read<Page<{ sessions: Summary[] }>>('sessions', { ...queryWindow, session_id: null, limit: 50, cursor, agent_id: null, plan_id: null, native_model: null, outcome: null, only_model_switch: effectiveOnlySwitch });if (epoch !== generation.current) return;+ acceptSummaryVisibility(page.sessions);setListLoaded(true); setSessions(current => cursor ? [...current, ...page.sessions] : page.sessions); setSessionCursor(page.next_cursor); setHits([]); setPartial(false);}} catch (e) {@@ -136,6 +148,42 @@ export function Sessions({ initialSession = null, initialRequest = null, languagvoid load();return () => { generation.current++; };}, [reload, refreshVersion, active]);+ // Refresh just the selected summary. List pagination keeps its original window+ // and order; a newer selected row must not restart that query or its selection.+ useEffect(() => {+ if (!active || !session || cleanupOpen) return;+ let stopped = false, inFlight = false;+ let timer: number | undefined;+ const controller = new AbortController();+ const schedule = () => {+ window.clearTimeout(timer);+ if (!stopped && document.visibilityState !== 'hidden') timer = window.setTimeout(() => void refreshSummary(), 2000);+ };+ async function refreshSummary() {+ if (stopped || inFlight || document.visibilityState === 'hidden') return;+ inFlight = true;+ const listGeneration = generation.current;+ const detailGeneration = timelineGeneration.current;+ try {+ const page = await read<Page<{ sessions: Summary[] }>>('sessions', {+ session_id: session, from_ms: 0, to_ms: Date.now() + 1, limit: 1, cursor: null,+ agent_id: null, plan_id: null, native_model: null, outcome: null, only_model_switch: false,+ }, controller.signal);+ if (stopped || document.hidden || listGeneration !== generation.current || detailGeneration !== timelineGeneration.current) return;+ const updated = page.sessions.find(item => item.session_id === session);+ if (updated) {+ acceptSummaryVisibility([updated]);+ setFocusedSummary(updated);+ setSessions(current => current.map(item => item.session_id === session ? updated : item));+ }+ } catch { /* Retain the last summary; the next visible read can recover. */ }+ finally { inFlight = false; schedule(); }+ }+ const visibility = () => { window.clearTimeout(timer); if (document.visibilityState !== 'hidden') void refreshSummary(); };+ document.addEventListener('visibilitychange', visibility);+ schedule();+ return () => { stopped = true; controller.abort(); window.clearTimeout(timer); document.removeEventListener('visibilitychange', visibility); };+ }, [session, active, cleanupOpen, reload, refreshVersion]);useEffect(() => {if (!searchMounted.current) { searchMounted.current = true; return; }const timer = window.setTimeout(() => { keywordTimer.current = null; void load(null, { keyword }); }, 260);@@ -168,7 +216,7 @@ export function Sessions({ initialSession = null, initialRequest = null, languag]);if (epoch !== timelineGeneration.current) return;if (exactRequest && !page.requests.some(item => item.request_id === exactRequest)) setTimelineError('OBSERVATION_REQUEST_UNAVAILABLE');- if (!cursor && summaryPage?.sessions[0]) setFocusedSummary(summaryPage.sessions[0]);+ if (!cursor && summaryPage?.sessions[0]) { acceptSummaryVisibility(summaryPage.sessions); setFocusedSummary(summaryPage.sessions[0]); }setRequests(current => cursor ? [...current, ...page.requests] : page.requests); setRequestCursor(page.next_cursor);if (!cursor && !hit && !exactRequest) {const first = page.requests[0]?.request_id ?? null;@@ -239,6 +287,7 @@ export function Sessions({ initialSession = null, initialRequest = null, languag}const selectedSummary = sessions.find(item => item.session_id === session)?? (focusedSummary?.session_id === session ? focusedSummary : undefined);+ const selectedContentCleared = Boolean(session && sessionContentStates[session] === 'cleared') || isCleared(selectedSummary?.content_completeness);const agentName = (id?: string) => !id? text('未关联 Agent', 'Unlinked Agent'): id.toLowerCase().includes('codex') ? 'Codex'@@ -307,28 +356,28 @@ export function Sessions({ initialSession = null, initialRequest = null, languagconst context = sessions.find(item => item.session_id === hit.session_id);return <button className={`session-item${session === hit.session_id ? ' active' : ''}`} key={hit.session_id} aria-current={session === hit.session_id ? 'page' : undefined} onClick={() => void timeline(hit.session_id, null, hit)}><div className="session-item-top"><span className="muted session-item-time">{context ? sessionTimeLabel(context.last_request_at_ms, language) : text('搜索命中', 'Match')}</span></div>- <div className="session-item-title"><ContentExcerpt hit={hit} language={language} fallback={text('查看命中正文', 'Open matching content')} revision={refreshVersion + reload} /></div>- <div className="session-item-meta">{context ? <><span>{agentName(context.agent_id)}</span>{sessionRoutes[context.session_id] && <><span>·</span><span>{sessionRoutes[context.session_id]}</span></>}{sessionModels[context.session_id] && <><span>·</span><span>{sessionModels[context.session_id]}</span></>}</> : text('点击读取所在会话', 'Open the matching session')}</div>+ <div className="session-item-title"><ContentExcerpt active={active} contentCleared={sessionContentStates[hit.session_id] === 'cleared' || isCleared(context?.content_completeness)} hit={hit} language={language} fallback={text('查看命中正文', 'Open matching content')} revision={refreshVersion + reload} /></div>+ <div className="session-item-meta">{context ? <><span>{agentName(context.agent_id)}</span>{sessionRoutes[context.session_id] && <><span>·</span><span>Plan: {sessionRoutes[context.session_id]}</span></>}{sessionModels[context.session_id] && <><span>·</span><span>{sessionModels[context.session_id]}</span></>}</> : text('点击读取所在会话', 'Open the matching session')}</div></button>;})}{searchCursor && !listError && <button className="btn session-more" disabled={listBusy} onClick={() => void load(searchCursor)}>{text('加载更多结果', 'Load more results')}</button>}{!listBusy && !listError && !hits.length && <div className="empty-state session-list-empty"><div><span className="empty-icon"><UiIcon name="search" /></span><h3>{partial ? text('尚未找到匹配', 'No match found yet') : text('没有匹配的会话', 'No matching sessions')}</h3><p>{partial ? text('部分正文暂不可搜索,可稍后刷新。', 'Some content is not searchable yet. Refresh later.') : text('试试其他关键词。', 'Try another keyword.')}</p></div></div>}- </> : <>{sessions.map(item => { const contentState = sessionContentStates[item.session_id] ?? (['deleted', 'expired'].includes(item.content_completeness) ? 'cleared' : item.content_completeness === 'complete' ? 'recorded' : 'partial'); return <button className={`session-item${session === item.session_id ? ' active' : ''}`} key={item.session_id} aria-current={session === item.session_id ? 'page' : undefined} onClick={() => void timeline(item.session_id)}><div className="session-item-top"><span className="muted session-item-time">{sessionTimeLabel(item.last_request_at_ms, language)}</span>{contentState === 'cleared' ? <span className="badge warn no-dot">{text('正文已清理', 'Content cleared')}</span> : contentState === 'partial' ? <span className="badge warn no-dot">{text('记录不完整', 'Incomplete record')}</span> : item.fallback_request_count > 0 && <span className="badge warn no-dot">{text('请求内回退', 'Request fallback')}</span>}</div><div className="session-item-title"><ContentExcerpt session={item.session_id} language={language} fallback={text('会话记录', 'Session')} limit={48} revision={`${refreshVersion + reload}:${item.last_request_at_ms}:${item.request_count}`} onModel={model => setSessionModels(current => current[item.session_id] === model ? current : { ...current, [item.session_id]: model })} onRoute={route => setSessionRoutes(current => current[item.session_id] === route ? current : { ...current, [item.session_id]: route })} /></div><div className="session-item-meta"><span>{agentName(item.agent_id)}</span>{sessionRoutes[item.session_id] && <><span>·</span><span>{sessionRoutes[item.session_id]}</span></>}{sessionModels[item.session_id] && <><span>·</span><span>{sessionModels[item.session_id]}</span></>}{!sessionRoutes[item.session_id] && !sessionModels[item.session_id] && <><span>·</span><span>{item.request_count} {text('个请求', 'requests')}</span></>}</div></button>; })}{sessionCursor && !listError && <button className="btn session-more" disabled={listBusy} onClick={() => void load(sessionCursor)}>{text('加载更多会话', 'Load more sessions')}</button>}{!busy && !listError && listLoaded && !sessions.length && <div className="empty-state session-list-empty"><div><h3>{text('当前筛选没有会话', 'No sessions match this filter')}</h3><p>{text('切换到全部会话。', 'Show all sessions.')}</p></div></div>}</>}+ </> : <>{sessions.map(item => { const contentState = sessionContentStates[item.session_id] ?? (isCleared(item.content_completeness) ? 'cleared' : item.content_completeness === 'complete' ? 'recorded' : 'partial'); return <button className={`session-item${session === item.session_id ? ' active' : ''}`} key={item.session_id} aria-current={session === item.session_id ? 'page' : undefined} onClick={() => void timeline(item.session_id)}><div className="session-item-top"><span className="muted session-item-time">{sessionTimeLabel(item.last_request_at_ms, language)}</span>{contentState === 'cleared' ? <span className="badge warn no-dot">{text('正文已清理', 'Content cleared')}</span> : contentState === 'partial' ? <span className="badge warn no-dot">{text('记录不完整', 'Incomplete record')}</span> : item.fallback_request_count > 0 && <span className="badge warn no-dot">{text('请求内回退', 'Request fallback')}</span>}</div><div className="session-item-title"><ContentExcerpt active={active} contentCleared={contentState === 'cleared'} session={item.session_id} language={language} fallback={text('会话记录', 'Session')} limit={48} revision={`${refreshVersion + reload}:${item.last_request_at_ms}:${item.request_count}`} onModel={model => setSessionModels(current => current[item.session_id] === model ? current : { ...current, [item.session_id]: model })} onRoute={route => setSessionRoutes(current => current[item.session_id] === route ? current : { ...current, [item.session_id]: route })} /></div><div className="session-item-meta"><span>{agentName(item.agent_id)}</span>{sessionRoutes[item.session_id] && <><span>·</span><span>Plan: {sessionRoutes[item.session_id]}</span></>}{sessionModels[item.session_id] && <><span>·</span><span>{sessionModels[item.session_id]}</span></>}{!sessionRoutes[item.session_id] && !sessionModels[item.session_id] && <><span>·</span><span>{item.request_count} {text('个请求', 'requests')}</span></>}</div></button>; })}{sessionCursor && !listError && <button className="btn session-more" disabled={listBusy} onClick={() => void load(sessionCursor)}>{text('加载更多会话', 'Load more sessions')}</button>}{!busy && !listError && listLoaded && !sessions.length && <div className="empty-state session-list-empty"><div><h3>{text('当前筛选没有会话', 'No sessions match this filter')}</h3><p>{text('切换到全部会话。', 'Show all sessions.')}</p></div></div>}</>}</div></aside><section className="session-transcript">{session ? <article className="session-detail"><div className="oc-model-back"><button className="btn btn-quiet" type="button" onClick={() => { timelineGeneration.current++; factGeneration.current++; setSession(null); setRequest(null); setFactsOpen(false); if (!listLoaded) void load(); }}><UiIcon name="arrowLeft" />{text('返回会话列表', 'Back to sessions')}</button></div>- <header className="transcript-head"><div><h2><ContentExcerpt session={session} language={language} fallback={text('会话正文', 'Conversation')} limit={56} revision={refreshVersion + reload} onModel={model => setSessionModels(current => current[session] === model ? current : { ...current, [session]: model })} onRoute={route => setSessionRoutes(current => current[session] === route ? current : { ...current, [session]: route })} /></h2><p>{[agentName(selectedSummary?.agent_id), sessionRoutes[session], selectedSummary ? sessionTimeLabel(selectedSummary.last_request_at_ms, language) : undefined].filter(Boolean).join(' · ')}</p></div><div className="transcript-actions">{routed && <div className="segmented session-view-tabs" role="group" aria-label={text('会话视图', 'Session view')}>{([['timeline', text('路由时间线', 'Routing timeline')], ['conversation', text('对话', 'Conversation')]] as const).map(([value, label]) => <button key={value} type="button" className={`segment${pane === value ? ' active' : ''}`} aria-pressed={pane === value} onClick={() => setSessionView(value)}>{label}</button>)}</div>}<button className="btn" type="button" disabled={!request} onClick={() => factsOpen ? setFactsOpen(false) : openFacts()}><UiIcon name="activity" />{factsOpen ? text('收起运行记录', 'Hide run record') : text('运行记录', 'Run record')}</button>{!factsOpen && <button className="icon-btn" type="button" aria-label={text('清理此会话', 'Clear this session')} disabled={busy} onClick={() => { setCleanupError(''); setCleanupOpen(true); }}><UiIcon name="trash" /></button>}</div></header>+ <header className="transcript-head"><div><h2><ContentExcerpt active={active} contentCleared={selectedContentCleared} session={session} language={language} fallback={text('会话正文', 'Conversation')} limit={56} revision={`${refreshVersion + reload}:${selectedSummary?.last_request_at_ms}:${selectedSummary?.request_count}`} onModel={model => setSessionModels(current => current[session] === model ? current : { ...current, [session]: model })} onRoute={route => setSessionRoutes(current => current[session] === route ? current : { ...current, [session]: route })} /></h2><p>{[agentName(selectedSummary?.agent_id), sessionRoutes[session] ? `Plan: ${sessionRoutes[session]}` : undefined, selectedSummary ? sessionTimeLabel(selectedSummary.last_request_at_ms, language) : undefined].filter(Boolean).join(' · ')}</p></div><div className="transcript-actions">{routed && <div className="segmented session-view-tabs" role="group" aria-label={text('会话视图', 'Session view')}>{([['timeline', text('路由时间线', 'Routing timeline')], ['conversation', text('对话', 'Conversation')]] as const).map(([value, label]) => <button key={value} type="button" className={`segment${pane === value ? ' active' : ''}`} aria-pressed={pane === value} onClick={() => setSessionView(value)}>{label}</button>)}</div>}<button className="btn" type="button" disabled={!request} onClick={() => factsOpen ? setFactsOpen(false) : openFacts()}><UiIcon name="activity" />{factsOpen ? text('收起运行记录', 'Hide run record') : text('运行记录', 'Run record')}</button>{!factsOpen && <button className="icon-btn" type="button" aria-label={text('清理此会话', 'Clear this session')} disabled={busy} onClick={() => { setCleanupError(''); setCleanupOpen(true); }}><UiIcon name="trash" /></button>}</div></header>{focusedRequest && focusedRequest === request && <div className="callout session-detail-feedback session-request-focus" data-request-id={focusedRequest} role="status"><UiIcon name="activity" /><div><strong>{selectedRequest ? text('已定位所选请求', 'Selected request') : timelineError ? text('所选请求不可用', 'Selected request unavailable') : text('正在定位所选请求…', 'Locating selected request…')}</strong>{selectedRequest && <p>{new Date(selectedRequest.started_at_ms).toLocaleString(language === 'zh' ? 'zh-CN' : 'en')}{selectedRequest.final_native_model && ' · ' + selectedRequest.final_native_model}<br />{text('下方包含本次请求的历史对话和回复。', 'The content below includes this request’s conversation history and response.')}</p>}</div><button className="btn" type="button" onClick={() => void timeline(session)}>{text('查看完整会话', 'View full session')}</button></div>}{timelineError && <div className="callout bad session-detail-feedback" role="alert" data-error-code={timelineError}><UiIcon name="warning" /><div><strong>{text('会话详情没有刷新', 'The session details were not refreshed')}</strong><p>{nativeConnectionReadText(timelineError, language) ?? (requests.length ? text('已加载的请求仍然保留。', 'Previously loaded requests are still available.') : text('暂时无法读取这条会话。', 'This session is temporarily unavailable.'))}</p><button className="btn" type="button" onClick={() => void timeline(session, null, undefined, focusedRequest)}>{text('重试', 'Retry')}</button></div></div>}<div className={`session-routing-and-conversation show-${pane}`}><Disclosure className="native-details session-model-performance" label={text('本会话的模型表现', 'Model performance in this session')} language={language} onOpenChange={setQualityOpen}><PlanQuality key={session} sessionId={session} language={language} compact active={active && qualityOpen} refreshVersion={refreshVersion + reload} onOpenEvidence={(targetSession, targetRequest) => void timeline(targetSession, null, undefined, targetRequest)} /></Disclosure>- <div className="session-pane" hidden={pane !== 'timeline'}><RoutingTimeline key={session} session={session} language={language} active={active} displayed={pane === 'timeline'} refreshVersion={refreshVersion + reload} requestId={routingRequestId} onOpenPerformance={setQualityPlan} onAvailability={setRouting} onSelectRequest={selectTimelineRequest} onViewConversation={item => { selectTimelineRequest(item); setSessionView('conversation'); }} /></div>+ <div className="session-pane" hidden={pane !== 'timeline'}><RoutingTimeline key={session} session={session} contentCleared={selectedContentCleared} clearedRequestIds={Object.keys(requestContentStates).filter(id => requestContentStates[id] === 'cleared')} language={language} active={active} displayed={pane === 'timeline'} refreshVersion={refreshVersion + reload} requestId={routingRequestId} onOpenPerformance={setQualityPlan} onAvailability={setRouting} onSelectRequest={selectTimelineRequest} onViewConversation={item => { selectTimelineRequest(item); setSessionView('conversation'); }} /></div><section className="routing-conversation" hidden={pane !== 'conversation'} aria-label={text('对话', 'Conversation')}>{requests.length > 1 && <Disclosure className="native-details request-timeline" label={text(`请求记录(${requests.length})`, `Requests (${requests.length})`)} language={language}><nav className="native-list" aria-label={text('请求时间线', 'Request timeline')}>{requests.map((item, index) => <button className={`list-row${request === item.request_id ? ' active' : ''}`} key={item.request_id} aria-current={request === item.request_id ? 'true' : undefined} onClick={() => { setRequestPicked(true); setRequest(item.request_id); setReadingRequests([item.request_id]); setAnchor(null); }}><span className="row-main"><span className="row-title">{text('请求', 'Request')} {index + 1}</span><span className="row-meta">{item.routing_context?.state === 'recorded' && item.routing_context.display_name ? item.routing_context.display_name : item.final_native_model ?? text('路由未记录', 'Route not recorded')}{item.within_request_fallback === true ? text(' · 请求内回退', ' · Request fallback') : item.between_turn_model_change === true ? text(' · 跨轮切换', ' · Turn change') : ''}</span></span></button>)}{requestCursor && <button className="btn" disabled={busy} onClick={() => void timeline(session, requestCursor)}>{text('加载更多请求', 'Load more requests')}</button>}</nav></Disclosure>}- {displayedRequestIds.length ? displayedRequestIds.map((id, index) => <div key={id} className="request-chapter">{index > 0 && <h3>{text('后续请求', 'Following request')} {requests.findIndex(item => item.request_id === id) + 1}</h3>}<RequestBody request={id} summary={requests.find(item => item.request_id === id)} attemptModels={id === request ? attemptModels : []} anchor={id === request ? anchor : null} language={language} onOpenFacts={openFacts} onContentState={reportRequestContentState} onNextRequest={index === displayedRequestIds.length - 1 && nextRequestId ? () => { setRequestPicked(true); setReadingRequests(current => [...current, nextRequestId]); setRequest(nextRequestId); setAnchor(null); } : undefined} onMoreRequests={index === displayedRequestIds.length - 1 && !nextRequestId && requestCursor ? () => void timeline(session, requestCursor) : undefined} /></div>) : !busy && <div className="empty-state transcript-empty"><div><p>{text('此会话尚未取得可显示的请求。', 'No displayable request was retrieved for this session.')}</p></div></div>}+ {displayedRequestIds.length ? displayedRequestIds.map((id, index) => <div key={id} className="request-chapter">{index > 0 && <h3>{text('后续请求', 'Following request')} {requests.findIndex(item => item.request_id === id) + 1}</h3>}<RequestBody contentCleared={selectedContentCleared || requestContentStates[id] === 'cleared'} request={id} summary={requests.find(item => item.request_id === id)} attemptModels={id === request ? attemptModels : []} anchor={id === request ? anchor : null} language={language} onOpenFacts={openFacts} onContentState={reportRequestContentState} onNextRequest={index === displayedRequestIds.length - 1 && nextRequestId ? () => { setRequestPicked(true); setReadingRequests(current => [...current, nextRequestId]); setRequest(nextRequestId); setAnchor(null); } : undefined} onMoreRequests={index === displayedRequestIds.length - 1 && !nextRequestId && requestCursor ? () => void timeline(session, requestCursor) : undefined} /></div>) : !busy && <div className="empty-state transcript-empty"><div><p>{text('此会话尚未取得可显示的请求。', 'No displayable request was retrieved for this session.')}</p></div></div>}</section></div></article> : <div className="empty-state session-no-selection"><div><span className="empty-icon"><UiIcon name="sessions" /></span><h3>{text('选择一个会话', 'Select a session')}</h3></div></div>}</section>@@ -347,7 +396,7 @@ export function Sessions({ initialSession = null, initialRequest = null, languag</Dialog></ProductPage>;}-function RequestBody({ request, summary, attemptModels, anchor, language, onOpenFacts, onContentState, onNextRequest, onMoreRequests }: { request: string; summary?: Request; attemptModels: string[]; anchor: Hit | null; language: 'zh' | 'en'; onOpenFacts(): void; onContentState(requestId: string, state: ContentState): void; onNextRequest?: () => void; onMoreRequests?: () => void }) {+function RequestBody({ request, contentCleared, summary, attemptModels, anchor, language, onOpenFacts, onContentState, onNextRequest, onMoreRequests }: { request: string; contentCleared: boolean; summary?: Request; attemptModels: string[]; anchor: Hit | null; language: 'zh' | 'en'; onOpenFacts(): void; onContentState(requestId: string, state: ContentState): void; onNextRequest?: () => void; onMoreRequests?: () => void }) {const text = (cn: string, en: string) => language === 'zh' ? cn : en;const [catalog, setCatalog] = useState<Content[]>([]);const [events, setEvents] = useState<Record<string, ReadableEvent>>({});@@ -396,9 +445,10 @@ function RequestBody({ request, summary, attemptModels, anchor, language, onOpenfinally { if (epoch === generation.current) setBusy(false); }}useEffect(() => {+ if (contentCleared) { setCatalog([]); setEvents({}); setCursor(null); return; }controller.current = new AbortController(); void load();return () => { generation.current++; controller.current.abort(); };- }, [request]);+ }, [request, contentCleared]);async function checkAncestry(roots: string[], partial: boolean, epoch: number) {if (partial) setAncestryIncomplete(true);if (!roots.length) return;@@ -411,8 +461,14 @@ function RequestBody({ request, summary, attemptModels, anchor, language, onOpen? 'cleared': !catalog.length || contentIncomplete ? 'partial' : 'recorded';useEffect(() => {- if (catalogLoaded || error) onContentState(request, contentState);- }, [request, contentState, catalogLoaded, error, onContentState]);+ if (!contentCleared && (catalogLoaded || error)) onContentState(request, contentState);+ }, [request, contentState, contentCleared, catalogLoaded, error, onContentState]);+ // Hide child message caches immediately; preserve navigation to new requests.+ if (contentCleared) return <section className="transcript-body">+ <p className="oc-meta">{text('正文已清理', 'Content cleared')}</p>+ {onNextRequest && <button className="btn" type="button" onClick={onNextRequest}>{text('继续读取下一请求', 'Continue to next request')}</button>}+ {onMoreRequests && <button className="btn" type="button" onClick={onMoreRequests}>{text('加载更多请求', 'Load more requests')}</button>}+ </section>;const occurrences = groupOccurrences(catalog.filter(item => displayableContent(item.kind)));const displayRuns = contentDisplayRuns(occurrences);// Input may replay answers from other models; a request's model and fallback@@ -590,6 +646,7 @@ async function completeTitlePart(requestId: string, contentId: string, signal: Aconst seen = new Set<string>();do {const page: { state: string; chunks: { text: string }[]; next_cursor: string | null } = await read('content', { request_id: requestId, content_id: contentId, cursor, anchor_offset: null }, signal);+ if (signal.aborted || ['deleted', 'expired'].includes(page.state)) return { text: null, incomplete: true };const next = page.chunks.map(chunk => chunk.text).join('');byteCount += new TextEncoder().encode(next).length;if (byteCount > TITLE_CONTENT_LIMIT) return { text: null, incomplete: true };@@ -610,8 +667,8 @@ async function firstRequestTitle(requestId: string, signal: AbortSignal, state:const page: { contents: Content[]; roots_partial?: boolean; next_cursor?: string | null } = await read('catalog', { request_id: requestId, limit: 200, cursor }, signal);contents.push(...page.contents);state.sawContent ||= page.contents.length > 0;- state.allDeleted &&= page.contents.every(item => item.state === 'deleted');- state.incomplete ||= Boolean(page.roots_partial) || page.contents.some(item => !['available', 'complete', 'deleted'].includes(item.state));+ state.allDeleted &&= page.contents.every(item => ['deleted', 'expired'].includes(item.state));+ state.incomplete ||= Boolean(page.roots_partial) || page.contents.some(item => !['available', 'complete', 'deleted', 'expired'].includes(item.state));cursor = page.next_cursor ?? null;if (cursor && seen.has(cursor)) { state.incomplete = true; break; }if (cursor) seen.add(cursor);@@ -645,77 +702,123 @@ async function firstRequestTitle(requestId: string, signal: AbortSignal, state:}/** `request` shows that request's latest user message, e.g. the message that opened an agent turn. */-export function ContentExcerpt({ session, request, hit, language, fallback = '', limit = 160, revision = 0, onCompleteness, onContentState, onModel, onRoute }: { session?: string; request?: string; hit?: Hit; language: 'zh' | 'en'; fallback?: string; limit?: number; revision?: number | string; onCompleteness?: (incomplete: boolean) => void; onContentState?: (state: ContentState) => void; onModel?: (model: string) => void; onRoute?: (route: string) => void }) {+export function ContentExcerpt({ session, request, hit, language, fallback = '', limit = 160, revision = 0, active = true, contentCleared = false, onCompleteness, onContentState, onModel, onRoute }: { session?: string; request?: string; hit?: Hit; language: 'zh' | 'en'; fallback?: string; limit?: number; revision?: number | string; active?: boolean; contentCleared?: boolean; onCompleteness?: (incomplete: boolean) => void; onContentState?: (state: ContentState) => void; onModel?: (model: string) => void; onRoute?: (route: string) => void }) {const node = useRef<HTMLSpanElement>(null);const [value, setValue] = useState('');- const [invalidation, setInvalidation] = useState(0);- useEffect(() => { const invalidate = () => { setValue(''); setInvalidation(v => v + 1); }; window.addEventListener('hiroute-content-invalidated', invalidate); return () => window.removeEventListener('hiroute-content-invalidated', invalidate); }, []);+ const [status, setStatus] = useState<'pending' | 'ready' | 'absent' | 'cleared' | 'error'>('pending');+ const callbacks = useRef({ onCompleteness, onContentState, onModel, onRoute });+ callbacks.current = { onCompleteness, onContentState, onModel, onRoute };+ useEffect(() => { setValue(''); setStatus('pending'); }, [session, request, hit?.request_id, hit?.content_id, hit?.original_text_offset]);useEffect(() => {- const controller = new AbortController(); let started = false;- setValue('');+ if (contentCleared) {+ setValue(''); setStatus('cleared');+ callbacks.current.onCompleteness?.(false);+ callbacks.current.onContentState?.('cleared');+ return;+ }+ let stopped = false, visible = false, inFlight = false, resolved = false;+ let timer: number | undefined, controller: AbortController | undefined;+ let retryMs = 2000;+ const eligible = () => !stopped && active && visible && document.visibilityState !== 'hidden';+ const schedule = () => {+ window.clearTimeout(timer);+ if (eligible() && !resolved) {+ timer = window.setTimeout(() => void load(), retryMs);+ retryMs = Math.min(retryMs * 2, 30000);+ }+ };+ function report(title: string | null, state: TitleScanState) {+ const cleared = state.sawContent && state.allDeleted;+ resolved = cleared || (state.sawContent && !state.incomplete);+ setValue(title === null ? '' : excerpt(title, limit));+ setStatus(cleared ? 'cleared' : !resolved ? 'pending' : title !== null ? 'ready' : 'absent');+ callbacks.current.onCompleteness?.(!resolved);+ callbacks.current.onContentState?.(cleared ? 'cleared' : resolved ? 'recorded' : 'partial');+ }async function load() {+ if (!eligible() || inFlight || resolved) return;+ inFlight = true;+ controller = new AbortController();+ const signal = controller.signal;try {if (hit) {- const page = await read<{ state?: string; chunks: { text: string; original_byte_offset: number }[] }>('content', { request_id: hit.request_id, content_id: hit.content_id, cursor: null, anchor_offset: hit.original_text_offset }, controller.signal);- if (controller.signal.aborted) return;- setValue(excerptAround(page.chunks.map(c => c.text).join(''), Math.max(0, hit.original_text_offset - (page.chunks[0]?.original_byte_offset ?? 0)), limit));- if (typeof page.state === 'string') {- const incomplete = !['available', 'complete'].includes(page.state);- onCompleteness?.(incomplete);- if (page.state === 'deleted') onContentState?.('cleared');- else if (incomplete) onContentState?.('partial');- }+ const page = await read<{ state?: string; chunks: { text: string; original_byte_offset: number }[] }>('content', { request_id: hit.request_id, content_id: hit.content_id, cursor: null, anchor_offset: hit.original_text_offset }, signal);+ if (signal.aborted) return;+ const cleared = ['deleted', 'expired'].includes(page.state ?? '');+ resolved = cleared || ['available', 'complete'].includes(page.state ?? '');+ setValue(cleared ? '' : excerptAround(page.chunks.map(c => c.text).join(''), Math.max(0, hit.original_text_offset - (page.chunks[0]?.original_byte_offset ?? 0)), limit));+ setStatus(cleared ? 'cleared' : resolved ? 'ready' : 'pending');+ callbacks.current.onCompleteness?.(!resolved);+ callbacks.current.onContentState?.(cleared ? 'cleared' : resolved ? 'recorded' : 'partial');return;}+ const state: TitleScanState = { sawContent: false, allDeleted: true, incomplete: false };if (request) {- const title = await firstRequestTitle(request, controller.signal, { sawContent: false, allDeleted: true, incomplete: false }, true);- if (!controller.signal.aborted && title !== null) setValue(excerpt(title, limit));+ const title = await firstRequestTitle(request, signal, state, true);+ if (!signal.aborted) report(title, state);return;}- if (!session) return;- const state: TitleScanState = { sawContent: false, allDeleted: true, incomplete: false };+ if (!session) { resolved = true; return; }let cursor: string | null = null;const toMs = Date.now() + 1;let firstRequest = true;const seen = new Set<string>();do {- const timeline: Page<{ requests: Request[] }> = await read('timeline', { session_id: session, limit: 50, cursor, from_ms: 0, to_ms: toMs, agent_id: null, plan_id: null, native_model: null, outcome: null, only_model_switch: false }, controller.signal);- for (const request of timeline.requests) {+ const timeline: Page<{ requests: Request[] }> = await read('timeline', { session_id: session, limit: 50, cursor, from_ms: 0, to_ms: toMs, agent_id: null, plan_id: null, native_model: null, outcome: null, only_model_switch: false }, signal);+ if (signal.aborted) return;+ for (const item of timeline.requests) {if (firstRequest) {firstRequest = false;- if (request.final_native_model) onModel?.(request.final_native_model);- const routing = request.routing_context;- if (routing?.state === 'recorded' && routing.name_state === 'recorded' && routing.display_name) onRoute?.(routing.display_name);- }- const title = await firstRequestTitle(request.request_id, controller.signal, state);- if (title !== null) {- if (!controller.signal.aborted) setValue(excerpt(title, limit));- onCompleteness?.(state.incomplete);- onContentState?.(state.incomplete ? 'partial' : 'recorded');- return;+ if (item.final_native_model) callbacks.current.onModel?.(item.final_native_model);+ const routing = item.routing_context;+ if (routing?.state === 'recorded' && routing.name_state === 'recorded' && routing.display_name) callbacks.current.onRoute?.(routing.display_name);}+ const title = await firstRequestTitle(item.request_id, signal, state);+ if (signal.aborted) return;+ if (title !== null) { report(title, state); return; }}cursor = timeline.next_cursor;if (cursor && seen.has(cursor)) { state.incomplete = true; break; }if (cursor) seen.add(cursor);- } while (cursor && !controller.signal.aborted);- if (!controller.signal.aborted) {- onCompleteness?.(state.incomplete);- onContentState?.(state.sawContent && state.allDeleted ? 'cleared' : !state.sawContent || state.incomplete ? 'partial' : 'recorded');- }+ } while (cursor && !signal.aborted);+ if (!signal.aborted) report(null, state);} catch {- // Keep the semantic row visible, while making the missing content- // explicit instead of silently leaving it indistinguishable from a- // successfully recorded fallback title.- if (!controller.signal.aborted) {- onCompleteness?.(true);- onContentState?.('partial');+ if (!signal.aborted) {+ setStatus('error');+ callbacks.current.onCompleteness?.(true);+ callbacks.current.onContentState?.('partial');}- }+ } finally { inFlight = false; schedule(); }}- const observer = new IntersectionObserver(entries => { if (!started && entries.some(e => e.isIntersecting)) { started = true; void load(); } });+ const visibility = () => {+ window.clearTimeout(timer);+ if (!eligible()) controller?.abort();+ else if (!resolved) { retryMs = 2000; void load(); }+ };+ // Abort synchronously on privacy invalidation: a pending old response must+ // never repopulate the body while React schedules the next render.+ const invalidate = () => {+ controller?.abort(); window.clearTimeout(timer); resolved = false; retryMs = 2000;+ setValue(''); setStatus('pending');+ if (!inFlight) void load();+ };+ const observer = new IntersectionObserver(entries => {+ visible = entries.some(entry => entry.isIntersecting);+ visibility();+ });if (node.current) observer.observe(node.current);- return () => { controller.abort(); observer.disconnect(); };- }, [session, request, hit?.request_id, hit?.content_id, hit?.original_text_offset, invalidation, limit, revision]);- return <span ref={node}>{value || fallback || (hit ? (language === 'zh' ? '查看命中正文' : 'Open matching content') : '')}</span>;+ document.addEventListener('visibilitychange', visibility);+ window.addEventListener('hiroute-content-invalidated', invalidate);+ return () => {+ stopped = true; controller?.abort(); window.clearTimeout(timer); observer.disconnect();+ document.removeEventListener('visibilitychange', visibility);+ window.removeEventListener('hiroute-content-invalidated', invalidate);+ };+ }, [session, request, hit?.request_id, hit?.content_id, hit?.original_text_offset, limit, revision, active, contentCleared]);+ // Mask cached text in the same render that receives a visibility change.+ const currentStatus = contentCleared ? 'cleared' : status;+ const statusText = currentStatus === 'cleared' ? (language === 'zh' ? '正文已清理' : 'Content cleared')+ : currentStatus === 'error' ? (language === 'zh' ? '正文暂时无法读取' : 'Content is temporarily unavailable')+ : currentStatus === 'pending' ? (language === 'zh' ? '正文尚未就绪' : 'Content is not ready yet') : undefined;+ return <span ref={node} data-content-state={currentStatus} title={statusText}>{(contentCleared ? '' : value) || ((request || hit || currentStatus === 'cleared') && statusText) || fallback || (hit ? (language === 'zh' ? '查看命中正文' : 'Open matching content') : '')}</span>;}diff --git a/apps/desktop/src/features/routing-timeline.css b/apps/desktop/src/features/routing-timeline.cssindex 13483fbc..12726dd1 100644--- a/apps/desktop/src/features/routing-timeline.css+++ b/apps/desktop/src/features/routing-timeline.css@@ -28,7 +28,7 @@.routing-judgments { display: grid; gap: 4px; }.routing-judgments > strong { color: var(--text); font-size: calc(13px * var(--hr-text-scale)); font-weight: 600; }.routing-protection-badge { justify-self: start; max-width: 100%; white-space: normal; }-.routing-lanes-scroll { min-width: 0; overflow-x: auto; padding: 2px 2px 4px; }+.routing-lanes-scroll { min-width: 0; overflow-x: auto; padding: 4px 0; }.routing-lanes { display: grid; width: max-content; min-width: 100%; grid-auto-flow: column; grid-template-columns: var(--routing-label-width); grid-auto-columns: clamp(var(--routing-cell-width), 18vw, 232px); grid-template-rows: auto; gap: 10px; align-items: stretch; }.routing-lanes[data-lanes='1'] { grid-template-rows: repeat(2, auto); }.routing-lanes[data-lanes='2'] { grid-template-rows: repeat(3, auto); }@@ -56,7 +56,9 @@@media (prefers-reduced-motion: reduce) { .routing-turn[data-new=true] { animation: none; } }.routing-turn:hover { border-color: color-mix(in srgb, var(--lane) 60%, transparent); }.routing-turn.selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }-.routing-turn:focus-visible, .routing-request:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+/* Keep focus inside each card so the scroll viewport and sticky labels do not clip it. */+.routing-turn:focus-visible { outline: 2px solid var(--accent); outline-offset: -3px; }+.routing-request:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }.routing-turn-reason { color: var(--lane); font-size: calc(13px * var(--hr-text-scale)); font-weight: 650; }.routing-turn-meta { color: var(--text-soft); font-size: calc(12px * var(--hr-text-scale)); font-variant-numeric: tabular-nums; }.routing-ticks { display: flex; flex-wrap: wrap; align-items: center; gap: 3px; min-height: 14px; }diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.mdindex abb369a2..9f536cda 100644--- a/apps/desktop/tests/README.md+++ b/apps/desktop/tests/README.md@@ -61,6 +61,13 @@ proves native authorization, persistence, process cleanup or real model calls.| Inspect a model or open its documentation | `desktop.models.documentation-retains-input`; [model-to-route scenario](v3/browser/model-to-route-scenarios.mjs) | Local readiness does not claim inference success; browser failure retains form input; web anchors retain their default action; route creation uses the selected model. || Change model grouping or inspect page controls | `desktop.models.view-switch`, `desktop.presentation.control-layout`; [presentation scenarios](v3/browser/presentation-interactions.mjs) | Production styles preserve model/connection counts, selected model and visible selection. Chinese/English and light/dark checks reject browser-default buttons and horizontal overflow from long recent-session titles at the supported small window. || Try a new model, judge its evidence and follow live routing | `timeline.initial-failure-retry-recovers.*`, `timeline.polls-only-while-displayed-and-visible`, `trust.scoring-states.both-groupings.*`, `quickstart.*.inline-connection-guard.model-change-and-back` in [trial scenarios](v3/visual/new-model-trial-active.mjs) | A failed timeline read keeps its tab, error and Retry until recovery, while only a confirmed empty read hides the tab; polling continues only while the timeline is shown and the window is visible, after one availability probe. Per-model and per-executor groupings both show scoring coverage and complete/partial/awaiting/unscored counts. Changing models, going back or leaving the quick start asks before discarding the inline connection form; Cancel keeps the model and input. `HIROUTE_BROWSER_TRANSPORT=console` runs the same scenarios over the console host. Real feed retrieval, saved trials and live sessions require native acceptance. |+| Keep selected sessions and delayed excerpts current | [Live session refresh scenarios](v3/visual/session-live-refresh-active.mjs) | Narrow summary refresh preserves list pages, selection and scroll. Visible unresolved excerpts retry independently of timeline digests; hidden/inactive views pause. Production-shaped empty catalogs after cleanup, late responses, externally deleted/expired summaries, reopening and new-request revival preserve current body visibility. |+| Read exact turn ranges and recover live timeline reads | [Timeline presentation scenarios](v3/visual/timeline-presentation-active.mjs) | Assessment Agent-turn IDs resolve to display coordinates across producer epochs; unavailable or ambiguous identities remain explicit. Transient reads preserve the last view and recover with bounded backoff; real capacity failures require Retry. Fixed labels occlude moving cards without hiding keyboard focus. |++Run the focused production-component cases with+`node tests/v3/visual/new-model-trial.mjs <evidence-directory> --session-live-refresh`+or `--presentation` from the Desktop directory. They use production styles and+controlled IPC; they do not establish native persistence or real model outcomes.The focused timeline pricing checks run with`node tests/v3/visual/new-model-trial.mjs <evidence-directory> --timeline-pricing`.diff --git a/apps/desktop/tests/v3/browser/session-live-refresh.html b/apps/desktop/tests/v3/browser/session-live-refresh.htmlnew file mode 100644index 00000000..24ad2392--- /dev/null+++ b/apps/desktop/tests/v3/browser/session-live-refresh.html@@ -0,0 +1 @@+<!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Session refresh acceptance</title></head><body><div id="root"></div><script type="module" src="./session-live-refresh.tsx"></script></body></html>diff --git a/apps/desktop/tests/v3/browser/session-live-refresh.tsx b/apps/desktop/tests/v3/browser/session-live-refresh.tsxnew file mode 100644index 00000000..331cf8ff--- /dev/null+++ b/apps/desktop/tests/v3/browser/session-live-refresh.tsx@@ -0,0 +1,99 @@+import React, { useState } from 'react';+import { createRoot } from 'react-dom/client';+import { mockIPC } from './host-mock';+import { Sessions, ContentExcerpt } from '../../../src/features/Sessions';+import { PresentationRoot } from '../../../src/ui';+import '../../../src/occami/styles.css';++const params = new URLSearchParams(location.search);+const language = params.get('lang') === 'zh' ? 'zh' : 'en';+const baseTime = Date.now();+let now = baseTime;+Date.now = () => now;+const realSet = window.setTimeout.bind(window), realClear = window.clearTimeout.bind(window);+const timers = new Map<number, { at: number; callback: () => void }>();+let serial = 90000, hidden = false;+window.setTimeout = ((callback: () => void, delay: number) => {+ if (delay < 2000 || delay > 30000) return realSet(callback, delay);+ const id = ++serial; timers.set(id, { at: now + delay, callback }); return id;+}) as typeof window.setTimeout;+window.clearTimeout = ((id: number) => { if (!timers.delete(id)) realClear(id); }) as typeof window.clearTimeout;+Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => hidden ? 'hidden' : 'visible' });+Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden });+const fixture = {+ phase: 0, rootsPartial: false, onlyResponse: false, partPartial: false, body: params.get('body') ?? 'pending', deferSummary: false, deferContent: false,+ clearedSessions: new Map<string, string>(), deletedRequests: new Set<string>(), revivedSessions: new Set<string>(),+ clear: (session: string, state = 'deleted') => {+ fixture.clearedSessions.set(session, state);+ fixture.deletedRequests.add(`request/${session}`);+ },+ revive: (session: string) => {+ fixture.clearedSessions.delete(session);+ fixture.revivedSessions.add(session);+ },+ reads: [] as { view: string; query: any; at: number }[], releases: [] as (() => void)[],+ advance: (ms: number) => {+ now += ms;+ for (const [id, timer] of [...timers]) if (timer.at <= now) { timers.delete(id); timer.callback(); }+ },+ visibility: (value: boolean) => { hidden = value; document.dispatchEvent(new Event('visibilitychange')); },+ invalidate: () => window.dispatchEvent(new Event('hiroute-content-invalidated')),+ release: () => { for (const release of fixture.releases.splice(0)) release(); },+};+if (params.has('cleared')) fixture.clear('session-1');+Object.assign(window, { sessionRefreshFixture: fixture });+const summary = (id: string, phase = fixture.phase) => ({ session_id: id, agent_id: 'claude-code', request_count: fixture.revivedSessions.has(id) ? 13 : phase ? 18 : 12, fallback_request_count: 0, last_request_at_ms: fixture.revivedSessions.has(id) ? now : phase ? baseTime + 65000 : baseTime - 60000, correlation_kind: 'native_session', content_completeness: fixture.clearedSessions.get(id) ?? (phase || fixture.revivedSessions.has(id) ? 'complete' : 'partial') });+const request = (session: string) => ({ request_id: `request/${session}`, started_at_ms: baseTime - 60000, outcome: 'completed', native_turn_id: 'turn/one', within_request_fallback: false, final_native_model: 'provider/exact-model', between_turn_model_change: false, previous_native_turn_id: null, previous_turn_model: null, turn_final_native_model: 'provider/exact-model', routing_context: { state: 'recorded', name_state: 'recorded', display_name: 'Daily coding trial', plan_id: 'plan/trial', plan_revision: '1' } });+const body = (requestId: string, state = fixture.body) => ({ state: fixture.partPartial ? 'partial' : ['deleted', 'expired'].includes(state) ? state : 'complete', chunks: state === 'available' ? [{ text: `Ready user content for ${requestId}`, original_byte_offset: 0 }] : [], next_cursor: null });+mockIPC(async (command, payload: any) => {+ if (command === 'observation_delete') { fixture.clear(payload.input.session_id); return {}; }+ if (command !== 'observation_read') throw Error(`Unexpected command ${command}`);+ const { view, query } = payload.request.intent;+ fixture.reads.push({ view, query, at: now });+ if (view === 'sessions') {+ if (query.session_id) {+ const result = { sessions: [summary(query.session_id)], next_cursor: null };+ if (fixture.deferSummary) return await new Promise(resolve => fixture.releases.push(() => resolve(result)));+ return result;+ }+ return { sessions: query.cursor ? [summary('older-page')] : Array.from({ length: 12 }, (_, index) => summary(`session-${index + 1}`)), next_cursor: query.cursor ? null : 'page-two' };+ }+ const sessionRequests = (id: string) => fixture.revivedSessions.has(id)+ ? [{ ...request(id), request_id: `request/${id}/new`, started_at_ms: baseTime + 65000 }, request(id)] : [request(id)];+ if (view === 'timeline') return { requests: sessionRequests(query.session_id), next_cursor: null };+ if (view === 'routing_timeline') return {+ turns: params.has('routed') ? sessionRequests(query.session_id).map(item => ({+ turn_id: item.request_id, agent_turn_id: `agent-turn/${item.request_id}`, segment_id: null, started_at_ms: item.started_at_ms,+ finished_at_ms: item.started_at_ms + 1000, boundary: 'new_user_message', plan_id: null, plan_revision: null,+ branch_id: null, model_configuration_id: 'provider/exact-model', reasoning_profile_id: null, group: 'regular',+ selection: null, tool_continuations: 0, relays: [], assessment_state: 'unrated', assessment: null,+ competence_floor_millis: null, protected_turn_ids: [], status: 'completed',+ requests: [{ ...item, duration_ms: 1000, native_model: 'provider/exact-model', input_tokens: null, output_tokens: null, cache_read_tokens: null, cache_read_share: null, costs: [] }],+ transitions: [], cost_by_model: [], evidence_partial: false, content_digest: 'unchanged-digest',+ })) : [], complete: true, watermark: 'constant-timeline-digest',+ };+ if (view === 'catalog') {+ if (fixture.body === 'error') throw { code: 'OBSERVATION_READ_TIMEOUT' };+ // Production cleanup removes catalog rows and transcript roots; it does not+ // leave a synthetic entry whose state is deleted.+ const cleared = fixture.deletedRequests.has(query.request_id);+ return { contents: cleared || fixture.body === 'pending' ? [] : [{ content_id: 'content/one', role: fixture.onlyResponse ? 'assistant' : 'user', kind: 'text', state: 'complete', direction: 'ingress', media_type: 'text/plain', message_occurrence_id: 'message/one', message_ordinal: 1, part_ordinal: 1 }], transcript_roots: [], roots_partial: cleared || fixture.rootsPartial, next_cursor: null };+ }+ if (view === 'content') {+ const result = body(query.request_id, fixture.deletedRequests.has(query.request_id) ? 'deleted' : fixture.body);+ if (fixture.deferContent) return await new Promise(resolve => fixture.releases.push(() => resolve(result)));+ return result;+ }+ if (view === 'ancestry') return { roots: [], gap: null };+ if (view === 'facts') return { facts: [], projection_partial: false, next_cursor: null };+ if (view === 'status') return { running: true, index_running: true, error_count: 0 };+ throw Error(`Unexpected view ${view}`);+});+function Fixture() {+ const [active, setActive] = useState(true);+ return <PresentationRoot theme={params.get('theme') === 'dark' ? 'dark' : 'light'} language={language} textScale={1}>+ <button id="toggle-active" className="btn" onClick={() => setActive(value => !value)}>Toggle active page</button>+ {params.get('mode') === 'excerpt' ? <main style={{ padding: 24, height: 'calc(100vh - 64px)', overflowY: 'auto' }}><h1>Selected request</h1><p className="selected-excerpt"><ContentExcerpt request="request/selected" active={active} language={language} revision="unchanged-digest" fallback="No user message recorded" /></p><div style={{ height: 1400 }} /><p>Offscreen target</p></main> : <Sessions language={language} active={active} />}+ </PresentationRoot>;+}+createRoot(document.getElementById('root')!).render(<Fixture />);diff --git a/apps/desktop/tests/v3/browser/timeline-presentation.html b/apps/desktop/tests/v3/browser/timeline-presentation.htmlnew file mode 100644index 00000000..1b5702a4--- /dev/null+++ b/apps/desktop/tests/v3/browser/timeline-presentation.html@@ -0,0 +1 @@+<!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Timeline presentation regression</title></head><body><div id="root"></div><script type="module" src="./timeline-presentation.tsx"></script></body></html>diff --git a/apps/desktop/tests/v3/browser/timeline-presentation.tsx b/apps/desktop/tests/v3/browser/timeline-presentation.tsxnew file mode 100644index 00000000..0e2103a3--- /dev/null+++ b/apps/desktop/tests/v3/browser/timeline-presentation.tsx@@ -0,0 +1,47 @@+import { useState } from 'react';+import { createRoot } from 'react-dom/client';+import { mockIPC } from './host-mock';+import { RoutingTimeline, type TimelineTurn } from '../../../src/features/RoutingTimeline';+import { PresentationRoot, ProductPage } from '../../../src/ui';+import '../../../src/occami/styles.css';++const params = new URLSearchParams(location.search);+const language = params.get('lang') === 'zh' ? 'zh' : 'en';+const scenario = params.get('scenario') ?? 'coordinates';+const reads: { at: number; error: string | null }[] = [];+const model = 'managed-provider/exact-model-id';+const turns = Array.from({ length: 18 }, (_, offset): TimelineTurn => {+ const n = offset + 1;+ const request = { request_id: `request-${n}`, started_at_ms: 1_790_000_000_000 + n * 1000, duration_ms: 500, native_model: model, input_tokens: 1000, output_tokens: 20, cache_read_tokens: 800, cache_read_share: .8, costs: [], outcome: 'completed' };+ return { turn_id: `turn-${n}`, agent_turn_id: `agent-turn-${n}`, segment_id: `segment-${n}`, started_at_ms: request.started_at_ms, finished_at_ms: request.started_at_ms + 500, boundary: 'new_user_message', plan_id: 'plan-1', plan_revision: 2, branch_id: 'smart', model_configuration_id: 'configuration-1', reasoning_profile_id: null, group: n % 2 ? 'regular' : 'primary', selection: { simple_probability: .8, simple_threshold_millis: 700, selection_reason: 'simple_task' }, tool_continuations: 0, relays: [], assessment_state: 'scored', assessment: { score: .4, partial: false, target_from_ordinal: 2, target_through_ordinal: 2, target_from_turn_id: n === 15 ? 'outside-retained-scope' : 'agent-turn-14', target_through_turn_id: n === 15 ? 'agent-turn-15' : 'agent-turn-14' }, competence_floor_millis: 500, protected_turn_ids: [], status: 'completed', requests: [request], transitions: [], cost_by_model: [], evidence_partial: false, content_digest: `digest-${n}` };+});+// The two known endpoints share a turn, so this gap is a request comparison,+// not a claim that the completed cross-turn comparison is missing.+turns[13].requests.push({ ...turns[13].requests[0], request_id: 'request-14-extra' });+turns[13].transitions = [+ { kind: 'unknown', request_id: 'request-14-extra', previous_request_id: 'request-14', model: { native_model: model }, previous_model: { native_model: model }, completeness: 'unknown' },+ { kind: 'between_turn_change', request_id: 'request-14-extra', previous_request_id: 'request-13', model: { native_model: model }, previous_model: { native_model: 'earlier-model' }, completeness: 'complete' },+ { kind: 'within_request_fallback', request_id: 'request-14-extra', previous_request_id: 'request-14', model: { native_model: model }, previous_model: { native_model: 'failed-model' }, completeness: 'complete' },+];+turns[13].transitions.push({ kind: 'unknown', request_id: 'request-14-extra', previous_request_id: 'request-14', model: { native_model: model }, previous_model: { native_model: 'different-model' }, model_changed: true, completeness: 'complete' });+turns[16].agent_turn_id = turns[17].agent_turn_id = 'duplicate-agent-turn';+turns[15].assessment = { ...turns[15].assessment!, target_from_turn_id: 'duplicate-agent-turn', target_through_turn_id: 'duplicate-agent-turn' };+turns[14].transitions = [{ kind: 'unknown', request_id: 'request-15', previous_request_id: 'outside-retained-request', model: { native_model: model }, previous_model: null, completeness: 'unknown' }];+Object.assign(window, { presentationFixture: { reads, turns } });+mockIPC((command, payload: any) => {+ if (command !== 'observation_read') throw new Error(`Unexpected ${command}`);+ const { view } = payload.request.intent;+ if (view === 'catalog') return { entries: [], next_cursor: null };+ if (view !== 'routing_timeline') throw new Error(`Unexpected observation ${view}`);+ const count = reads.length;+ const error = scenario === 'timeout' && (count === 1 || count === 2) ? 'timeout' : scenario === 'scope' && count === 0 ? 'scope' : null;+ reads.push({ at: performance.now(), error });+ if (error === 'timeout') throw { code: 'OBSERVATION_UNAVAILABLE', observation_read: { reason: 'timeout' } };+ if (error === 'scope') throw { code: 'OBSERVATION_SCOPE_TOO_LARGE' };+ return { turns: count === 0 || scenario === 'scope' ? turns : [], watermark: `watermark-${count}`, complete: true };+});+function Fixture() {+ const [requestId, select] = useState<string | null>(null);+ return <PresentationRoot theme={params.get('theme') === 'dark' ? 'dark' : 'light'} textScale={1} language={language}><ProductPage title={language === 'zh' ? '会话' : 'Sessions'}><div className="session-routing-and-conversation"><RoutingTimeline session="presentation-session" language={language} active displayed refreshVersion={0} requestId={requestId} onSelectRequest={request => select(request.request_id)} onOpenPerformance={() => {}} /></div></ProductPage></PresentationRoot>;+}+createRoot(document.getElementById('root')!).render(<Fixture />);diff --git a/apps/desktop/tests/v3/visual/new-model-trial-active.mjs b/apps/desktop/tests/v3/visual/new-model-trial-active.mjsindex b865e9f4..e8ef79e7 100644--- a/apps/desktop/tests/v3/visual/new-model-trial-active.mjs+++ b/apps/desktop/tests/v3/visual/new-model-trial-active.mjs@@ -296,7 +296,8 @@ try {await open(`lang=${lang}&view=timeline&timeline-error=1`);await waitFor(client,`document.querySelector('.routing-timeline [role=alert]')?.getClientRects().length>0`);assert.ok(await evaluate(client,`document.querySelector('.session-view-tabs')?.getClientRects().length>0`),'a failed first read keeps the timeline tab');- assert.ok(await evaluate(client,`document.querySelector('.routing-timeline [role=alert]').textContent.includes(${JSON.stringify(lang==='zh'?'更新暂时不可用':'temporarily unavailable')})`));+ assert.ok(await evaluate(client,`document.querySelector('.routing-timeline [role=alert]').textContent.includes(${JSON.stringify(lang==='zh'?'暂时无法读取':'temporarily unavailable')})`));+ assert.ok(await evaluate(client,`!document.querySelector('.routing-timeline [role=alert]').textContent.includes(${JSON.stringify(lang==='zh'?'上次读取的内容':'last successful read')})`),'a failed first read does not imply retained content');await shot(`timeline-initial-failure-${lang}-755`);await evaluate(client,`window.timelineFail=false;true`);const retriedAt=await evaluate(client,'performance.now()');diff --git a/apps/desktop/tests/v3/visual/new-model-trial.mjs b/apps/desktop/tests/v3/visual/new-model-trial.mjsindex 846644c0..99f0e0bb 100644--- a/apps/desktop/tests/v3/visual/new-model-trial.mjs+++ b/apps/desktop/tests/v3/visual/new-model-trial.mjs@@ -69,7 +69,14 @@ try {chrome = spawn(chromeExecutable, ['--headless=new', '--disable-gpu', `--remote-debugging-port=${cdpPort}`, '--remote-allow-origins=*', `--user-data-dir=${profile}`, '--window-size=1280,900', 'about:blank'], { detached: true, stdio: ['ignore', 'pipe', 'pipe'] });await new Promise((resolve, reject) => { chrome.once('spawn', resolve); chrome.once('error', reject); });await waitFor(`http://127.0.0.1:${cdpPort}/json/version`);- const runner = spawn(process.execPath, [path.join(here, process.argv.includes('--metadata') ? 'model-metadata-active.mjs' : process.argv.includes('--protection') ? 'new-model-trial-protection-active.mjs' : process.argv.includes('--polish') ? 'new-model-trial-polish-active.mjs' : 'new-model-trial-active.mjs'), String(cdpPort), `http://127.0.0.1:${httpPort}/`, outputRoot, ...(process.argv.includes('--timeline-pricing') ? ['--timeline-pricing'] : [])], { cwd: desktopRoot, stdio: 'inherit' });+ const selectedRunner = [+ ['--session-live-refresh', 'session-live-refresh-active.mjs'],+ ['--presentation', 'timeline-presentation-active.mjs'],+ ['--metadata', 'model-metadata-active.mjs'],+ ['--protection', 'new-model-trial-protection-active.mjs'],+ ['--polish', 'new-model-trial-polish-active.mjs'],+ ].find(([flag]) => process.argv.includes(flag))?.[1] ?? 'new-model-trial-active.mjs';+ const runner = spawn(process.execPath, [path.join(here, selectedRunner), String(cdpPort), `http://127.0.0.1:${httpPort}/`, outputRoot, ...(process.argv.includes('--timeline-pricing') ? ['--timeline-pricing'] : [])], { cwd: desktopRoot, stdio: 'inherit' });const outcome = await waitForExit(runner);if (outcome.code !== 0) process.exitCode = outcome.code ?? 1;} finally {diff --git a/apps/desktop/tests/v3/visual/session-live-refresh-active.mjs b/apps/desktop/tests/v3/visual/session-live-refresh-active.mjsnew file mode 100644index 00000000..ac206ff2--- /dev/null+++ b/apps/desktop/tests/v3/visual/session-live-refresh-active.mjs@@ -0,0 +1,165 @@+import assert from 'node:assert/strict';+import { writeFile } from 'node:fs/promises';+import path from 'node:path';+import { connectPage, evaluate, waitFor } from './cdp-client.mjs';+const [port, base, output] = process.argv.slice(2);+const client = await connectPage(Number(port));+const keepAlive = setInterval(() => {}, 1000);+const results = [];+const fixture = 'sessionRefreshFixture';+const flush = () => new Promise(resolve => setTimeout(resolve, 100));+const readCount = filter => evaluate(client, `${fixture}.reads.filter(r=>${filter}).length`);+async function advance(ms) { await evaluate(client, `${fixture}.advance(${ms});true`); await flush(); }+async function open(query, width = 1200, height = 813) {+ await client.send('Page.enable'); await client.send('Runtime.enable');+ await client.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });+ await client.send('Page.navigate', { url: `${base}session-live-refresh.html?${query}` });+ await waitFor(client, '!!document.querySelector("#toggle-active")');+ await evaluate(client, 'document.fonts.ready.then(()=>true)');+}+async function shot(name) { const capture = await client.send('Page.captureScreenshot', { format: 'png' }); await writeFile(path.join(output, `${name}.png`), Buffer.from(capture.data, 'base64')); }+async function run(id, action) { if (process.env.SESSION_REFRESH_CASE && !id.includes(process.env.SESSION_REFRESH_CASE)) return; try { await action(); results.push({ id, status: 'passed' }); } catch (error) { results.push({ id, status: 'failed', error: String(error) }); throw error; } }+try {+ await run('session.selected-summary-refresh-preserves-pages-selection-and-scroll', async () => {+ await open('body=available');+ await waitFor(client, 'document.querySelectorAll(".session-item").length===12 && !!document.querySelector(".transcript-head p")');+ await evaluate(client, 'document.querySelector(".session-more").click();true');+ await waitFor(client, 'document.querySelectorAll(".session-item").length===13');+ const before = await evaluate(client, `(()=>{const list=document.querySelector('.session-list');list.scrollTop=80;return {time:document.querySelector('.session-item-time').textContent,header:document.querySelector('.transcript-head p').textContent,scroll:list.scrollTop,listReads:${fixture}.reads.filter(r=>r.view==='sessions'&&!r.query.session_id).length};})()`);+ await evaluate(client, `${fixture}.phase=1;true`);+ await advance(70000);+ await waitFor(client, `document.querySelector('.session-item-time').textContent!==${JSON.stringify(before.time)}`);+ const after = await evaluate(client, `({count:document.querySelectorAll('.session-item').length,selected:[...document.querySelectorAll('.session-item')].findIndex(n=>n.getAttribute('aria-current')==='page'),scroll:document.querySelector('.session-list').scrollTop,header:document.querySelector('.transcript-head p').textContent,badge:document.querySelector('.session-item:first-child .badge')?.textContent,listReads:${fixture}.reads.filter(r=>r.view==='sessions'&&!r.query.session_id).length,query:${fixture}.reads.filter(r=>r.view==='sessions'&&r.query.session_id).at(-1)?.query})`);+ assert.equal(after.count, 13); assert.equal(after.selected, 0); assert.ok(after.scroll > 0 && Math.abs(after.scroll - before.scroll) < 32, 'the list keeps its visible location as the completeness badge disappears'); assert.equal(after.listReads, before.listReads);+ assert.notEqual(after.header, before.header); assert.equal(after.badge, undefined); assert.ok(after.header.includes('Plan: Daily coding trial'));+ assert.equal(after.query.limit, 1); assert.equal(after.query.cursor, null); assert.ok(after.query.to_ms > after.query.from_ms);+ await shot('session-summary-live-en-light-1200');+ });+ await run('session.summary-hidden-inactive-and-late-selection-response', async () => {+ await open('body=available'); await waitFor(client, '!!document.querySelector(".transcript-head p")');+ await evaluate(client, `${fixture}.visibility(true);true`);+ const hiddenCount = await readCount("r.view==='sessions'"); await advance(60000); assert.equal(await readCount("r.view==='sessions'"), hiddenCount);+ await evaluate(client, `${fixture}.visibility(false);true`); await flush();+ assert.ok(await readCount("r.view==='sessions'") > hiddenCount);+ await evaluate(client, `document.querySelector('#toggle-active').click();true`); await flush();+ const inactive = await readCount("r.view==='sessions'"); await advance(60000); assert.equal(await readCount("r.view==='sessions'"), inactive);+ await evaluate(client, `document.querySelector('#toggle-active').click();true`); await flush();+ await evaluate(client, `${fixture}.deferSummary=true;${fixture}.phase=1;true`); await advance(2000);+ await waitFor(client, `${fixture}.releases.length>0`);+ await evaluate(client, `document.querySelectorAll('.session-item')[1].click();${fixture}.deferSummary=false;${fixture}.phase=0;${fixture}.release();true`); await flush();+ assert.equal(await evaluate(client, `document.querySelectorAll('.session-item')[1].getAttribute('aria-current')`), 'page');+ assert.ok(await evaluate(client, `document.querySelector('.transcript-head h2').textContent.includes('session-2')`));+ });+ for (const [language, theme, width, height] of [['en', 'light', 755, 600], ['zh', 'dark', 1200, 813]]) {+ for (const initial of ['pending', 'error']) await run(`session.excerpt-${initial}-recovers-with-unchanged-digest.${language}`, async () => {+ await open(`mode=excerpt&body=${initial}&lang=${language}&theme=${theme}`, width, height);+ await waitFor(client, `${fixture}.reads.some(r=>r.view==='catalog')`); await flush();+ const initialText = await evaluate(client, `document.querySelector('.selected-excerpt').textContent`);+ await shot(`session-excerpt-${initial}-${language}-${theme}-${width}`);+ await evaluate(client, `${fixture}.body='available';true`); await advance(2000);+ await waitFor(client, `document.querySelector('.selected-excerpt').textContent.includes('Ready user content')`);+ assert.ok(!initialText.includes('No user message recorded'));+ const reads = await readCount("r.view==='catalog'"); await advance(60000); assert.equal(await readCount("r.view==='catalog'"), reads);+ await shot(`session-excerpt-recovered-${initial}-${language}-${theme}-${width}`);+ });+ }+ await run('session.excerpt-complete-items-do-not-hide-request-or-body-gaps', async () => {+ await open('mode=excerpt'); await waitFor(client, `${fixture}.reads.length===1`);+ await evaluate(client, `${fixture}.body='available';${fixture}.onlyResponse=true;${fixture}.rootsPartial=true;true`); await advance(2000);+ assert.equal(await evaluate(client, `document.querySelector('.selected-excerpt span').dataset.contentState`), 'pending');+ await evaluate(client, `${fixture}.onlyResponse=false;${fixture}.rootsPartial=false;${fixture}.partPartial=true;true`); await advance(4000);+ await waitFor(client, `document.querySelector('.selected-excerpt').textContent.includes('Ready user content')`);+ const partialReads = await readCount("r.view==='content'");+ await evaluate(client, `${fixture}.partPartial=false;true`); await advance(8000);+ assert.equal(await readCount("r.view==='content'"), partialReads + 1);+ const completeReads = await readCount('true'); await advance(60000); assert.equal(await readCount('true'), completeReads);+ await evaluate(client, `${fixture}.onlyResponse=true;${fixture}.invalidate();true`); await flush();+ assert.equal(await evaluate(client, `document.querySelector('.selected-excerpt').textContent`), 'No user message recorded');+ const absentReads = await readCount('true'); await advance(60000); assert.equal(await readCount('true'), absentReads);+ });+ await run('session.excerpt-bounded-backoff-hidden-offscreen-inactive', async () => {+ await open('mode=excerpt'); await waitFor(client, `${fixture}.reads.length===1`);+ for (const delay of [2000, 4000, 8000, 16000, 30000, 30000]) { const previous = await readCount("r.view==='catalog'"); await advance(delay - 1); assert.equal(await readCount("r.view==='catalog'"), previous); await advance(1); assert.equal(await readCount("r.view==='catalog'"), previous + 1); }+ await evaluate(client, `${fixture}.visibility(true);true`); const hidden = await readCount('true'); await advance(60000); assert.equal(await readCount('true'), hidden);+ await evaluate(client, `${fixture}.visibility(false);true`); await flush(); assert.equal(await readCount('true'), hidden + 1);+ await evaluate(client, `document.querySelector('#toggle-active').click();true`); await flush(); const inactive = await readCount('true'); await advance(60000); assert.equal(await readCount('true'), inactive);+ await evaluate(client, `document.querySelector('#toggle-active').click();true`); await flush();+ await evaluate(client, `document.querySelector('main').scrollTop=document.querySelector('main').scrollHeight;true`); await flush(); const offscreen = await readCount('true'); await advance(60000); assert.equal(await readCount('true'), offscreen);+ await evaluate(client, `${fixture}.body='available';document.querySelector('main').scrollTop=0;true`); await waitFor(client, `document.querySelector('.selected-excerpt').textContent.includes('Ready user content')`);+ });+ await run('session.cleanup-already-cleared-session-opens-without-body-reads', async () => {+ await open('body=available&routed&cleared');+ await waitFor(client, "document.querySelector('.transcript-head h2')?.textContent==='Content cleared'");+ await waitFor(client, "document.querySelector('.routing-quote span')?.dataset.contentState==='cleared'");+ await advance(60000);+ assert.equal(await readCount("['catalog','content'].includes(r.view)&&r.query.request_id==='request/session-1'"), 0);+ });+ await run('session.excerpt-empty-partial-catalog-is-not-proof-of-cleanup', async () => {+ await open('mode=excerpt'); await waitFor(client, `${fixture}.reads.length===1`);+ await evaluate(client, `${fixture}.rootsPartial=true;true`); await advance(2000);+ assert.equal(await evaluate(client, "document.querySelector('.selected-excerpt span').dataset.contentState"), 'pending');+ await evaluate(client, `${fixture}.rootsPartial=false;${fixture}.body='available';true`); await advance(4000);+ await waitFor(client, "document.querySelector('.selected-excerpt').textContent.includes('Ready user content')");+ });+ await run('session.cleanup-empty-catalog-invalidates-in-flight-and-stops-retries', async () => {+ await open('body=available&routed');+ await waitFor(client, "!!document.querySelector('.session-pane:not([hidden]) .routing-quote')");+ await evaluate(client, "document.querySelector('.routing-quote').scrollIntoView({block:'center'});true");+ await waitFor(client, "document.querySelector('.routing-quote').textContent.includes('Ready user content')");+ await evaluate(client, `${fixture}.deferContent=true;${fixture}.invalidate();true`);+ await waitFor(client, `${fixture}.releases.length>0`);+ await evaluate(client, `document.querySelector('[aria-label="Clear this session"]').click();true`);+ await waitFor(client, "!!document.querySelector('[role=dialog] .btn-danger')");+ await evaluate(client, "document.querySelector('[role=dialog] .btn-danger').click();true");+ await waitFor(client, `${fixture}.clearedSessions.has('session-1')`);+ await waitFor(client, "document.querySelector('.transcript-head h2').textContent==='Content cleared'");+ await evaluate(client, `${fixture}.deferContent=false;${fixture}.release();true`); await flush();+ await waitFor(client, "!document.querySelector('[role=dialog]')");+ await waitFor(client, "document.querySelector('.routing-quote span')?.dataset.contentState==='cleared'");+ const filter = "['catalog','content'].includes(r.view)&&r.query.request_id==='request/session-1'";+ const reads = await readCount(filter); await advance(60000); assert.equal(await readCount(filter), reads);+ assert.equal(await evaluate(client, "document.querySelector('.routing-quote').textContent"), 'Content cleared');+ assert.equal(await evaluate(client, "document.querySelector('.transcript-head h2').textContent"), 'Content cleared');+ assert.equal(await evaluate(client, "document.querySelector('.session-item[aria-current=page] .session-item-title').textContent"), 'Content cleared');+ await shot('session-cleanup-empty-catalog-en-light');+ // Timeline and summary reads are independent. Do not permanently classify+ // a newly arrived request as cleared using an older session summary.+ await evaluate(client, `${fixture}.deferSummary=true;true`); await advance(2000);+ await waitFor(client, `${fixture}.releases.length>0`);+ await evaluate(client, `${fixture}.revivedSessions.add('session-1');true`); await advance(2000);+ await waitFor(client, "document.querySelectorAll('.routing-turn').length===2");+ await evaluate(client, `${fixture}.deferSummary=false;${fixture}.release();true`); await flush();+ await evaluate(client, `${fixture}.revive('session-1');true`); await advance(2000);+ await waitFor(client, "document.querySelector('.transcript-head h2').textContent.includes('session-1/new')");+ await waitFor(client, "document.querySelectorAll('.routing-turn').length===2");+ await evaluate(client, `document.querySelector('[data-turn-id="request/session-1"]').click();true`);+ await waitFor(client, "document.querySelector('.routing-quote').textContent==='Content cleared'");+ await evaluate(client, `document.querySelector('[data-turn-id="request/session-1/new"]').click();true`);+ await evaluate(client, "document.querySelector('.routing-quote').scrollIntoView({block:'center'});true");+ await waitFor(client, "document.querySelector('.routing-quote').textContent.includes('session-1/new')");+ assert.ok(!(await evaluate(client, "document.querySelector('.session-item[aria-current=page]').textContent")).includes('Content cleared'));+ });+ for (const state of ['deleted', 'expired']) await run(`session.cleanup-${state}-summary-invalidates-cached-excerpts-and-reopens`, async () => {+ await open('body=available&routed&lang=zh&theme=dark', 755, 600);+ await waitFor(client, "document.querySelector('.transcript-head h2')?.textContent.includes('Ready user content')");+ await evaluate(client, "document.querySelector('.routing-quote').scrollIntoView({block:'center'});true");+ await waitFor(client, "document.querySelector('.routing-quote').textContent.includes('Ready user content')");+ const summaryBefore = await readCount("r.view==='sessions'&&r.query.session_id");+ await evaluate(client, `${fixture}.clear('session-1','${state}');true`); await advance(2000);+ await waitFor(client, "document.querySelector('.transcript-head h2').textContent==='正文已清理'");+ assert.ok(await readCount("r.view==='sessions'&&r.query.session_id") > summaryBefore);+ assert.equal(await evaluate(client, "document.querySelector('.session-item[aria-current=page] .session-item-title').textContent"), '正文已清理');+ assert.equal(await evaluate(client, "document.querySelector('.routing-quote').textContent"), '正文已清理');+ const filter = "['catalog','content'].includes(r.view)&&r.query.request_id==='request/session-1'";+ const reads = await readCount(filter); await advance(60000); assert.equal(await readCount(filter), reads);+ await shot(`session-cleanup-${state}-zh-dark-755`);+ await evaluate(client, "document.querySelectorAll('.session-item')[1].click();true");+ await waitFor(client, "document.querySelector('.transcript-head h2').textContent.includes('session-2')");+ await evaluate(client, "document.querySelectorAll('.session-item')[0].click();true");+ await waitFor(client, "document.querySelector('.routing-quote span')?.dataset.contentState==='cleared'");+ assert.equal(await readCount(filter), reads, 'reopening a known cleared session does not fetch body');+ });+} finally {+ await writeFile(path.join(output, 'session-live-refresh-results.json'), JSON.stringify(results, null, 2));+ clearInterval(keepAlive); client.close();+}diff --git a/apps/desktop/tests/v3/visual/timeline-presentation-active.mjs b/apps/desktop/tests/v3/visual/timeline-presentation-active.mjsnew file mode 100644index 00000000..831b112b--- /dev/null+++ b/apps/desktop/tests/v3/visual/timeline-presentation-active.mjs@@ -0,0 +1,108 @@+import assert from 'node:assert/strict';+import { writeFile } from 'node:fs/promises';+import path from 'node:path';+import { connectPage, evaluate, waitFor } from './cdp-client.mjs';++const [port, base, output] = process.argv.slice(2);+const client = await connectPage(Number(port));+const results = [];+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));+const shot = async name => {+ const image = await client.send('Page.captureScreenshot', { format: 'png' });+ await writeFile(path.join(output, `${name}.png`), Buffer.from(image.data, 'base64'));+};+async function open(scenario, lang = 'en', theme = 'light', width = 1200, height = 813) {+ await client.send('Page.enable'); await client.send('Runtime.enable');+ await client.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });+ await client.send('Page.navigate', { url: `${base}timeline-presentation.html?scenario=${scenario}&lang=${lang}&theme=${theme}` });+ await waitFor(client, `!!document.querySelector('.routing-timeline') && !!window.presentationFixture`);+ await evaluate(client, 'document.fonts.ready.then(()=>true)');+}+async function select(n) {+ await evaluate(client, `document.querySelector('[data-overview-turn="turn-${n}"]').dispatchEvent(new MouseEvent('click', { bubbles: true }));true`);+ await waitFor(client, `document.querySelector('.routing-detail-head > strong')?.textContent === 'T${n}'`);+ await evaluate(client, `document.querySelector('.routing-turn-detail').scrollIntoView({block:'center'});true`);+}+async function check(id, run) {+ if (process.env.PRESENTATION_CASE && !id.startsWith(process.env.PRESENTATION_CASE)) return;+ try { await run(); results.push({ id, status: 'passed' }); }+ catch (error) { await shot(`failure-${id}`); results.push({ id, status: 'failed', error: String(error.stack ?? error) }); }+}+try {+ for (const lang of ['en', 'zh']) for (const theme of ['light', 'dark']) for (const [width, height] of [[1200, 813], [755, 600]]) {+ const name = `${lang}-${theme}-${width}`;+ await check(`identity-${name}`, async () => {+ await open('coordinates', lang, theme, width, height);+ await waitFor(client, `document.querySelectorAll('.routing-turn').length === 18`);+ await select(14);+ const details = await evaluate(client, `document.querySelector('.routing-turn-detail').textContent`);+ assert.ok(details.includes(lang === 'zh' ? '覆盖轮次 T14' : 'covers turn T14'), details);+ assert.ok(!details.includes('2–2'), details);+ assert.ok(details.includes(lang === 'zh' ? '请求间切换证据尚不完整' : 'Request transition evidence incomplete'), details);+ assert.ok(details.includes(lang === 'zh' ? '跨轮模型切换' : 'Between-turn model change'), details);+ assert.ok(details.includes(lang === 'zh' ? '本轮请求间模型变化' : 'Model change between requests in this turn'), details);+ assert.ok(details.includes('different-model → managed-provider/exact-model-id'), details);+ assert.ok(details.includes(lang === 'zh' ? '请求内模型回退' : 'Within-request fallback'), details);+ const model = await evaluate(client, `document.querySelector('.routing-detail-head').textContent`);+ assert.ok(model.includes(lang === 'zh' ? '模型:managed-provider/exact-model-id' : 'Model: managed-provider/exact-model-id'), model);+ assert.ok(await evaluate(client, `document.documentElement.scrollWidth <= innerWidth + 1 && [...document.querySelectorAll('.routing-turn-detail,.routing-overview')].every(e=>e.scrollWidth<=e.clientWidth+1)`));+ await shot(`identity-${name}`);+ await select(15);+ const missing = await evaluate(client, `document.querySelector('.routing-turn-detail').textContent`);+ assert.ok(missing.includes(lang === 'zh' ? '当前已加载范围外' : 'outside the loaded range'), missing);+ assert.ok(missing.includes(lang === 'zh' ? '切换证据尚不完整' : 'Transition evidence incomplete'), missing);+ assert.ok(!missing.includes(lang === 'zh' ? '请求间切换证据尚不完整' : 'Request transition evidence incomplete'), missing);+ await select(16);+ const ambiguous = await evaluate(client, `document.querySelector('.routing-detail-block:last-of-type').textContent`);+ assert.ok(ambiguous.includes(lang === 'zh' ? '身份未确认' : 'without a confirmed identity'), ambiguous);+ assert.ok(!ambiguous.includes('T17') && !ambiguous.includes('T18'), ambiguous);+ });+ await check(`occlusion-focus-${name}`, async () => {+ await open('coordinates', lang, theme, width, height);+ await waitFor(client, `document.querySelectorAll('.routing-turn').length === 18`);+ await evaluate(client, `document.querySelector('.routing-lanes-scroll').scrollIntoView({block:'center'});true`);+ const mask = await evaluate(client, `(()=>{const s=document.querySelector('.routing-lanes-scroll'),label=s.querySelector('.routing-lane-label');let leak=null;for(let x=100;x<Math.min(s.scrollWidth-s.clientWidth,1800);x+=8){s.scrollLeft=x;const r=s.getBoundingClientRect(),l=label.getBoundingClientRect(),hit=document.elementFromPoint(r.left+1,l.top+l.height/2);if(hit?.closest('.routing-turn')){leak={x,hit:hit.className};break;}}const r=s.getBoundingClientRect(),l=label.getBoundingClientRect();return {gap:l.left-r.left,leak};})()`);+ assert.equal(mask.gap, 0, 'sticky layer must cover the scroller left edge');+ assert.equal(mask.leak, null, 'hidden cards must not intercept pointer input beneath labels');+ await evaluate(client, `(()=>{const s=document.querySelector('.routing-lanes-scroll');s.scrollLeft=0;const b=s.querySelector('.routing-turn');b.focus();return true;})()`);+ await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });+ await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });+ const focus = await evaluate(client, `(()=>{const b=document.activeElement,s=document.querySelector('.routing-lanes-scroll'),r=b.getBoundingClientRect(),p=s.getBoundingClientRect(),style=getComputedStyle(b);return {button:b.matches('.routing-turn'),visible:b.matches(':focus-visible'),width:parseFloat(style.outlineWidth),offset:parseFloat(style.outlineOffset),left:r.left-p.left,right:p.right-r.right};})()`);+ assert.ok(focus.button && focus.visible && focus.width >= 2, JSON.stringify(focus));+ assert.ok(focus.left >= 0 && focus.right >= 0 && focus.offset <= -focus.width, JSON.stringify(focus));+ await shot(`occlusion-focus-${name}`);+ const click = await evaluate(client, `(()=>{const s=document.querySelector('.routing-lanes-scroll'),b=s.querySelector('[data-turn-id="turn-2"]'),r=b.getBoundingClientRect();return {x:r.left+r.width/2,y:r.top+r.height/2};})()`);+ await client.send('Input.dispatchMouseEvent', { type: 'mousePressed', button: 'left', clickCount: 1, ...click });+ await client.send('Input.dispatchMouseEvent', { type: 'mouseReleased', button: 'left', clickCount: 1, ...click });+ await waitFor(client, `document.querySelector('.routing-detail-head > strong')?.textContent==='T2'`);+ });+ }+ await check('timeout-retains-selection-and-backs-off', async () => {+ await open('timeout'); await waitFor(client, `document.querySelectorAll('.routing-turn').length===18`);+ await select(14);+ await waitFor(client, `!!document.querySelector('[data-error-code]')`);+ const stale = await evaluate(client, `({title:document.querySelector('.routing-detail-head > strong').textContent,status:document.querySelector('.routing-live').textContent,count:document.querySelectorAll('.routing-turn').length})`);+ assert.equal(stale.title, 'T14'); assert.equal(stale.count, 18);+ assert.ok(stale.status.includes('Update delayed'), stale.status);+ await evaluate(client, `document.querySelector('.routing-live').scrollIntoView({block:'start'});true`);+ await shot('timeout-retained');+ await sleep(6500);+ await waitFor(client, `presentationFixture.reads.length>=4 && !document.querySelector('[data-error-code]')`);+ const readTimes = await evaluate(client, 'presentationFixture.reads');+ assert.ok(readTimes[3].at-readTimes[2].at>=3500, JSON.stringify(readTimes));+ assert.equal(await evaluate(client, `document.querySelector('.routing-detail-head > strong').textContent`), 'T14');+ assert.ok(await evaluate(client, `document.querySelector('.routing-live').textContent.includes('Live')`));+ });+ await check('capacity-requires-explicit-retry', async () => {+ await open('scope'); await waitFor(client, `!!document.querySelector('[data-error-code]')`);+ await sleep(4200);+ assert.equal(await evaluate(client, 'presentationFixture.reads.length'), 1);+ await evaluate(client, `document.querySelector('[data-error-code] button').click();true`);+ await waitFor(client, `document.querySelectorAll('.routing-turn').length===18`);+ });+} finally {+ await writeFile(path.join(output, 'timeline-presentation-results.json'), JSON.stringify({ proof: 'production components/styles with controlled IPC; no native/provider calls', results }, null, 2));+ client.close();+}+console.log(JSON.stringify({ suite: 'timeline-presentation', total: results.length, failed: results.filter(r=>r.status!=='passed').length }));+if (!results.length || results.some(result=>result.status!=='passed')) process.exitCode=1;diff --git a/crates/cli/tests/routing_timeline_follow.rs b/crates/cli/tests/routing_timeline_follow.rsindex b936f768..bb4cb537 100644--- a/crates/cli/tests/routing_timeline_follow.rs+++ b/crates/cli/tests/routing_timeline_follow.rs@@ -12,7 +12,7 @@ use std::{struct TracedStore {store: Arc<LocalObservationStore>,busy: mpsc::Sender<bool>,- pages: Option<Mutex<VecDeque<RoutingTimelinePageV1>>>,+ pages: Option<Mutex<VecDeque<Result<RoutingTimelinePageV1, ObservationQueryError>>>>,}impl ObservationQueryPort for TracedStore {@@ -24,19 +24,20 @@ impl ObservationQueryPort for TracedStore {) -> Result<RoutingTimelinePageV1, ObservationQueryError> {// Controlled pages exercise the CLI consumer; storage projections have their own tests.let result = if let Some(pages) = &self.pages {- Ok(pages- .lock()- .unwrap()- .pop_front()- .unwrap_or(RoutingTimelinePageV1 {+ pages.lock().unwrap().pop_front().unwrap_or_else(|| {+ Ok(RoutingTimelinePageV1 {turns: vec![],watermark: "settled".into(),complete: true,- }))+ })+ })} else {ObservationQueryPort::observed_routing_timeline(&*self.store, r, q, now)};- if matches!(&result, Err(ObservationQueryError::ReaderBusy)) {+ if matches!(+ &result,+ Err(ObservationQueryError::ReaderBusy | ObservationQueryError::ReadTimeout)+ ) {self.busy.send(true).unwrap();} else if result.is_ok() {self.busy.send(false).unwrap();@@ -204,13 +205,13 @@ fn review_cli_follow_retries_real_busy_reads() {}#[test]-fn follow_preserves_historical_protection_in_initial_and_changed_turns() {+fn follow_recovers_timeout_and_preserves_historical_protection_in_changed_turns() {if std::env::var_os("HIROUTE_PROTECTION_TEST_CHILD").is_none() {let home = tempfile::tempdir().unwrap();let output = Command::new(std::env::current_exe().unwrap()).args(["--exact",- "follow_preserves_historical_protection_in_initial_and_changed_turns",+ "follow_recovers_timeout_and_preserves_historical_protection_in_changed_turns","--nocapture",]).env("HOME", home.path())@@ -277,21 +278,25 @@ fn follow_preserves_historical_protection_in_initial_and_changed_turns() {changed.finished_at_ms = Some(2000);changed.content_digest = "later-completion".into();let pages = VecDeque::from([- RoutingTimelinePageV1 {+ Ok(RoutingTimelinePageV1 {turns,watermark: "initial".into(),complete: true,- },- RoutingTimelinePageV1 {+ }),+ // Exercise the production Application error envelope and installed CLI+ // retry after a successful page. The store deadline itself is covered+ // by Observation tests; this controlled failure covers its consumer.+ Err(ObservationQueryError::ReadTimeout),+ Ok(RoutingTimelinePageV1 {turns: vec![changed.clone()],watermark: "changed".into(),complete: true,- },- RoutingTimelinePageV1 {+ }),+ Ok(RoutingTimelinePageV1 {turns: vec![changed],watermark: "same".into(),complete: true,- },+ }),]);let (busy, reads) = mpsc::channel();let mut ports = runtime.application_ports();@@ -322,11 +327,12 @@ fn follow_preserves_historical_protection_in_initial_and_changed_turns() {.spawn().unwrap(),));- for _ in 0..4 {- assert!(- !reads+ for failure in [false, true, false, false, false] {+ assert_eq!(+ reads.recv_timeout(Duration::from_secs(8))- .expect("CLI did not consume the next page")+ .expect("CLI did not recover from the timeout and consume the next page"),+ failure,);}nix::sys::signal::kill(diff --git a/crates/observation/src/query_v2/routing_timeline/mod.rs b/crates/observation/src/query_v2/routing_timeline/mod.rsindex b0586fe9..854655f0 100644--- a/crates/observation/src/query_v2/routing_timeline/mod.rs+++ b/crates/observation/src/query_v2/routing_timeline/mod.rs@@ -87,13 +87,6 @@ impl crate::LocalObservationStore {now_ms: i64,) -> Result<RoutingTimelinePageV1, ObservationV2Error> {self.routing_timeline_inner(reader, query, now_ms, || {})- .map_err(|error| {- if matches!(error, ObservationV2Error::Timeout) {- ObservationV2Error::ScopeTooLarge- } else {- error- }- })}fn routing_timeline_inner(@@ -174,31 +167,19 @@ impl crate::LocalObservationStore {} else {None};- state- .refresh(- &tx,- reader,- &query.session_id,- target,- now_ms,- changed.as_ref(),- )- .map_err(|error| {- if matches!(- error,- ObservationV2Error::Unavailable | ObservationV2Error::Timeout- ) && started.elapsed() >= std::time::Duration::from_millis(500)- {- ObservationV2Error::ScopeTooLarge- } else {- error- }- })?;+ state.refresh(+ &tx,+ reader,+ &query.session_id,+ target,+ now_ms,+ changed.as_ref(),+ )?;}state.visibility = visibility;cursor.expires_at = state.expires_at;if started.elapsed() > std::time::Duration::from_millis(500) {- return Err(ObservationV2Error::ScopeTooLarge);+ return Err(ObservationV2Error::Timeout);}let start = cursor.after.as_ref().map_or(0, |after| {state.turns.partition_point(|turn| {@@ -313,7 +294,7 @@ mod tests {}#[test]- fn expired_timeline_deadline_is_a_scope_error() {+ fn expired_timeline_deadline_remains_transient_and_a_fresh_read_recovers() {let dir = tempfile::tempdir().unwrap();let store = crate::query_v2::tests::open(dir.path());let reader = ObservationReaderContext::local_user(@@ -335,7 +316,54 @@ mod tests {store.observed_routing_timeline(&reader, &query, 5000).unwrap_err(),- ObservationV2Error::ScopeTooLarge+ ObservationV2Error::Timeout+ );+ let fresh = ObservationReaderContext::local_user(+ WorkspaceId::default(),+ "user".into(),+ 1,+ 10_000,+ false,+ false,+ )+ .unwrap();+ assert!(+ store+ .observed_routing_timeline(&fresh, &query, 5000)+ .is_ok()+ );+ }++ #[test]+ fn elapsed_timeline_budget_remains_transient_and_a_fresh_read_recovers() {+ let dir = tempfile::tempdir().unwrap();+ let store = crate::query_v2::tests::open(dir.path());+ let reader = ObservationReaderContext::local_user(+ WorkspaceId::default(),+ "user".into(),+ 1,+ 10_000,+ false,+ false,+ )+ .unwrap();+ let query = RoutingTimelineQueryV1 {+ session_id: "session/test".into(),+ after_watermark: None,+ limit: 50,+ };+ assert_eq!(+ store+ .routing_timeline_inner(&reader, &query, 5000, || {+ std::thread::sleep(std::time::Duration::from_millis(510));+ })+ .unwrap_err(),+ ObservationV2Error::Timeout+ );+ assert!(+ store+ .observed_routing_timeline(&reader, &query, 5000)+ .is_ok());}diff --git a/crates/observation/src/query_v2/routing_timeline/transition_tests.rs b/crates/observation/src/query_v2/routing_timeline/transition_tests.rsnew file mode 100644index 00000000..3e5c36a1--- /dev/null+++ b/crates/observation/src/query_v2/routing_timeline/transition_tests.rs@@ -0,0 +1,220 @@+use super::*;++fn request(id: &str, model: &str, at: i64) -> Request {+ Request {+ view: RoutingTimelineRequestV1 {+ request_id: id.into(),+ started_at_ms: at,+ duration_ms: Some(1),+ native_model: Some(model.into()),+ input_tokens: None,+ output_tokens: None,+ cache_read_tokens: None,+ cache_read_share: None,+ costs: vec![],+ outcome: Some("accepted".into()),+ },+ position: Position::default(),+ first_fact: at,+ native_turn: None,+ run_id: None,+ decision: None,+ candidate: Some((model.into(), Some("default".into()))),+ models: BTreeMap::from([(1, model.into())]),+ credentials: BTreeMap::new(),+ partial: false,+ body_bytes: 0,+ request_bytes: 0,+ fact_count: 0,+ usage_count: 0,+ }+}++fn turn(id: &str, ids: &[&str], requests: &BTreeMap<String, Request>) -> RoutingTimelineTurnV1 {+ RoutingTimelineTurnV1 {+ turn_id: ids[0].into(),+ agent_turn_id: Some(id.into()),+ segment_id: None,+ started_at_ms: requests[ids[0]].view.started_at_ms,+ finished_at_ms: Some(requests[*ids.last().unwrap()].view.started_at_ms + 1),+ boundary: RoutingTurnBoundaryV1::NewUserMessage,+ plan_id: None,+ plan_revision: None,+ branch_id: None,+ model_configuration_id: None,+ reasoning_profile_id: None,+ group: None,+ selection: None,+ tool_continuations: 0,+ relays: vec![],+ transitions: vec![],+ assessment_state: "unrated".into(),+ assessment: None,+ competence_floor_millis: None,+ protected_turn_ids: vec![],+ status: "completed".into(),+ requests: ids.iter().map(|id| requests[*id].view.clone()).collect(),+ cost_by_model: vec![],+ evidence_partial: false,+ content_digest: String::new(),+ }+}++fn scenario(+ opening_model: &str,+) -> (+ RoutingTimelineTurnV1,+ RoutingTimelineTurnV1,+ BTreeMap<String, Request>,+) {+ let requests: BTreeMap<_, _> = [+ request("prior", "regular", 10),+ request("opening", opening_model, 20),+ request("middle", "primary", 30),+ request("final", "primary", 40),+ ]+ .into_iter()+ .map(|r| (r.view.request_id.clone(), r))+ .collect();+ let previous = turn("turn-a", &["prior"], &requests);+ let current = turn("turn-b", &["opening", "middle", "final"], &requests);+ (previous, current, requests)+}++fn classified(+ previous: &RoutingTimelineTurnV1,+ current: &RoutingTimelineTurnV1,+ requests: &BTreeMap<String, Request>,+) -> Vec<AnalysisTransitionV1> {+ classify(+ "session",+ current,+ Some(&(2, "epoch".into())),+ Some((previous, Some(&(1, "epoch".into())))),+ requests,+ )+}++#[test]+fn completed_turn_comparison_replaces_only_the_same_intermediate_endpoint() {+ let (previous, current, requests) = scenario("primary");+ let values = classified(&previous, ¤t, &requests);+ assert!(+ values.iter().all(|v| v.request_id != "opening"),+ "a complete final comparison resolves the redundant intermediate context reset"+ );+ let final_comparison = values.iter().find(|v| v.request_id == "final").unwrap();+ assert_eq!(+ final_comparison.kind,+ AnalysisTransitionKindV1::BetweenTurnChange+ );+ assert_eq!(+ final_comparison.previous_request_id.as_deref(),+ Some("prior")+ );+ assert_eq!(final_comparison.completeness, "complete");+ assert_eq!(+ current.requests.len(),+ 3,+ "request contributions remain intact"+ );+}++#[test]+fn different_intermediate_model_is_not_erased_by_a_complete_turn_comparison() {+ let (previous, current, requests) = scenario("intermediate");+ let values = classified(&previous, ¤t, &requests);+ assert_eq!(values.len(), 3);+ let opening = values.iter().find(|v| v.request_id == "opening").unwrap();+ assert_eq!(opening.kind, AnalysisTransitionKindV1::Unknown);+ assert_eq!(opening.model.native_model.as_deref(), Some("intermediate"));+ let within_turn = values.iter().find(|v| v.request_id == "middle").unwrap();+ assert_eq!(within_turn.previous_request_id.as_deref(), Some("opening"));+ assert_eq!(within_turn.model_changed, Some(true));+ assert_eq!(within_turn.completeness, "complete");+ assert_eq!(+ values.last().unwrap().kind,+ AnalysisTransitionKindV1::BetweenTurnChange+ );+}++#[test]+fn incomplete_turn_or_endpoint_evidence_does_not_resolve_an_intermediate_unknown() {+ for variant in [+ "partial",+ "unfinished",+ "pending",+ "missing_model",+ "overlapping",+ ] {+ let (mut previous, mut current, mut requests) = scenario("primary");+ match variant {+ "partial" => current.evidence_partial = true,+ "unfinished" => current.finished_at_ms = None,+ "pending" => current.requests.last_mut().unwrap().duration_ms = None,+ "missing_model" => current.requests.last_mut().unwrap().native_model = None,+ "overlapping" => {+ previous.requests[0].duration_ms = Some(20);+ requests.get_mut("prior").unwrap().view.duration_ms = Some(20);+ }+ _ => unreachable!(),+ }+ let values = classified(&previous, ¤t, &requests);+ assert!(+ values+ .iter()+ .any(|v| v.request_id == "opening" && v.kind == AnalysisTransitionKindV1::Unknown),+ "{variant} must preserve the intermediate unknown"+ );+ }+}++#[test]+fn model_configuration_and_reasoning_are_part_of_the_comparison_identity() {+ for candidate in [+ ("another-config", "default"),+ ("primary", "different-reasoning"),+ ] {+ let (previous, current, mut requests) = scenario("primary");+ requests.get_mut("opening").unwrap().candidate =+ Some((candidate.0.into(), Some(candidate.1.into())));+ let values = classified(&previous, ¤t, &requests);+ assert!(+ values+ .iter()+ .any(|v| v.request_id == "opening" && v.kind == AnalysisTransitionKindV1::Unknown)+ );+ }+}++#[test]+fn request_fallback_and_credential_relay_survive_the_final_turn_comparison() {+ let (previous, current, mut requests) = scenario("primary");+ let opening = requests.get_mut("opening").unwrap();+ opening.models = BTreeMap::from([+ (1, "regular".into()),+ (2, "primary".into()),+ (3, "primary".into()),+ ]);+ opening.credentials = BTreeMap::from([+ (1, ("source".into(), "key-a".into())),+ (2, ("source".into(), "key-a".into())),+ (3, ("source".into(), "key-b".into())),+ ]);+ let values = classified(&previous, ¤t, &requests);+ for kind in [+ AnalysisTransitionKindV1::WithinRequestFallback,+ AnalysisTransitionKindV1::CredentialRelay,+ ] {+ assert!(+ values+ .iter()+ .any(|v| v.request_id == "opening" && v.kind == kind)+ );+ }+ assert!(+ values+ .iter()+ .all(|v| v.request_id != "opening" || v.kind != AnalysisTransitionKindV1::Unknown)+ );+}diff --git a/crates/observation/src/query_v2/routing_timeline/transitions.rs b/crates/observation/src/query_v2/routing_timeline/transitions.rsindex 93f96518..015fa222 100644--- a/crates/observation/src/query_v2/routing_timeline/transitions.rs+++ b/crates/observation/src/query_v2/routing_timeline/transitions.rs@@ -30,10 +30,59 @@ pub(super) fn classify(.iter().map(|r| r.request_id.as_str()).collect();- routing_transitions(&rows)+ let mut values: Vec<_> = routing_transitions(&rows).into_iter().filter(|t| ids.contains(t.request_id.as_str()))- .collect()+ .collect();+ coalesce_completed_comparison(turn, identity, &mut values);+ values+}++fn coalesce_completed_comparison(+ turn: &RoutingTimelineTurnV1,+ identity: Option<&Identity>,+ values: &mut Vec<AnalysisTransitionV1>,+) {+ if turn.finished_at_ms.is_none() || turn.evidence_partial || identity.is_none() {+ return;+ }+ let Some(last) = turn.requests.last() else {+ return;+ };+ let Some(final_comparison) = values+ .iter()+ .find(|t| {+ t.request_id == last.request_id+ && t.completeness == "complete"+ && t.previous_session_id.is_some()+ && t.previous_request_id.is_some()+ && matches!(+ t.kind,+ AnalysisTransitionKindV1::BetweenTurnChange+ | AnalysisTransitionKindV1::ReasoningChange+ | AnalysisTransitionKindV1::Unchanged+ )+ })+ .cloned()+ else {+ return;+ };+ // The shared classifier keeps per-request diagnostics. A nonfinal request+ // cannot yet prove the turn's final endpoint, so it may report context reset.+ // Only the same proven predecessor and identical model/reasoning endpoints+ // make that diagnostic redundant with this completed turn comparison.+ // Other intermediate models, gaps, pending requests and relays remain visible.+ values.retain(|t| {+ !(t.request_id != final_comparison.request_id+ && t.kind == AnalysisTransitionKindV1::Unknown+ && t.completeness == "turn_context_reset"+ && t.previous_session_id == final_comparison.previous_session_id+ && t.previous_request_id == final_comparison.previous_request_id+ && t.previous_model == final_comparison.previous_model+ && t.model == final_comparison.model+ && t.model_changed == final_comparison.model_changed+ && t.reasoning_changed == final_comparison.reasoning_changed)+ });}fn append(session: &str,@@ -100,3 +149,7 @@ fn append(});}}++#[cfg(test)]+#[path = "transition_tests.rs"]+mod tests;diff --git a/crates/observation/src/store/tests/plan_quality/timeline_cache.rs b/crates/observation/src/store/tests/plan_quality/timeline_cache.rsindex 4021926e..33e08885 100644--- a/crates/observation/src/store/tests/plan_quality/timeline_cache.rs+++ b/crates/observation/src/store/tests/plan_quality/timeline_cache.rs@@ -2,6 +2,156 @@ use super::*;use crate::query_v2::ObservationV2Error;use hiroute_domain::{RoutingTimelineQueryV1, WorkspaceId};+#[test]+fn timeline_late_completion_resolves_only_its_redundant_intermediate_comparison() {+ use super::super::support;+ use hiroute_domain::AnalysisTransitionKindV1;+ let directory = tempfile::tempdir().unwrap();+ let store = open_store(directory.path());+ let prior = Fixture::new("comparison-prior");+ let mut opening = Fixture::new("comparison-opening");+ let mut closing = Fixture::new("comparison-closing");+ for fixture in [&mut opening, &mut closing] {+ fixture.session = prior.session.clone();+ fixture.fact_stream = prior.fact_stream.clone();+ }+ let channel = fact_channel(&prior, 256 * 1024);+ let writer = writer(&store);+ let assert_ingested = |envelope: hiroute_domain::ExecutionFactEnvelopeV1| {+ let request = envelope.correlation.request_id.clone();+ let sequence = envelope.sequence;+ let fact_kind = serde_json::to_value(&envelope.fact).unwrap()["kind"]+ .as_str()+ .unwrap()+ .to_owned();+ let outcome = offer_fact(&writer, &channel, envelope);+ assert!(+ matches!(outcome, WriterCycleOutcome::Ack(_)),+ "request={request} sequence={sequence} fact={fact_kind:?}: {outcome:?}"+ );+ };+ let mut sequence = 0;+ for (fixture, model, at) in [+ (&prior, "regular", 1000),+ (&opening, "primary", 1100),+ (&closing, "primary", 1200),+ ] {+ let mut candidate = support::candidate(model);+ if let ExecutionFactV1::CandidateDecision(candidate) = &mut candidate {+ candidate.native_model = model.into();+ }+ let mut started = support::attempt_started(model);+ if let ExecutionFactV1::AttemptStarted { request_model, .. } = &mut started {+ *request_model = model.into();+ }+ let mut facts = vec![+ (support::route_decision(PLAN), false),+ (candidate, false),+ (started, true),+ (support::attempt_finished(), true),+ ];+ if fixture.request == prior.request {+ facts.push((+ finished_for_model(&prior, "stage-1", "turn-1", 1, "smart_saving", 1000, model),+ false,+ ));+ }+ if fixture.request != closing.request {+ facts.push((support::request_finished(), false));+ }+ for (offset, (fact, attempt)) in facts.into_iter().enumerate() {+ sequence += 1;+ let envelope = if attempt {+ fixture.attempt_fact(+ sequence,+ &format!("attempt/{}", fixture.request.as_str()),+ fact,+ at + offset as i64,+ PLAN,+ )+ } else {+ fixture.fact(sequence, fact, at + offset as i64)+ };+ assert_ingested(envelope);+ }+ }+ let mut query = RoutingTimelineQueryV1 {+ session_id: prior.session.to_string(),+ after_watermark: None,+ limit: 50,+ };+ let provisional = store+ .observed_routing_timeline(&reader(), &query, 5000)+ .unwrap();+ assert_eq!(provisional.turns.len(), 3);+ assert!(+ provisional.turns[1]+ .transitions+ .iter()+ .any(|t| t.kind == AnalysisTransitionKindV1::Unknown)+ );+ // Turn completion belongs to the still-open final request. Appending it to+ // the already-frozen opening request would violate receipt immutability.+ let mut finished = finished_for_model(+ &closing,+ "stage-2",+ "turn-2",+ 2,+ "smart_saving",+ 1100,+ "primary",+ );+ if let ExecutionFactV1::AgentTurnFinished {+ first_request_id,+ finished_at_ms,+ ..+ } = &mut finished+ {+ *first_request_id = Some(opening.request.clone());+ *finished_at_ms = 1210;+ }+ for (fact, at) in [(finished, 1210), (support::request_finished(), 1211)] {+ sequence += 1;+ assert_ingested(closing.fact(sequence, fact, at));+ }+ query.after_watermark = Some(provisional.watermark);+ let delta = store+ .observed_routing_timeline(&reader(), &query, 5000)+ .unwrap();+ let completed = delta+ .turns+ .iter()+ .find(|t| t.turn_id == opening.request.as_str())+ .unwrap();+ assert_eq!(completed.requests.len(), 2);+ assert_eq!(completed.transitions.len(), 1);+ let comparison = &completed.transitions[0];+ assert_eq!(comparison.kind, AnalysisTransitionKindV1::BetweenTurnChange);+ assert_eq!(comparison.request_id, closing.request.as_str());+ assert_eq!(+ comparison.previous_request_id.as_deref(),+ Some(prior.request.as_str())+ );+ assert_eq!(comparison.completeness, "complete");+ query.after_watermark = Some(delta.watermark);+ assert!(+ store+ .observed_routing_timeline(&reader(), &query, 5000)+ .unwrap()+ .turns+ .is_empty()+ );+ query.after_watermark = None;+ let cold = store+ .observed_routing_timeline(&reader(), &query, 5000)+ .unwrap();+ assert_eq!(cold.turns.len(), 2);+ assert_eq!(+ serde_json::to_value(&cold.turns[1]).unwrap(),+ serde_json::to_value(completed).unwrap()+ );+}+#[test]fn timeline_late_turn_completion_reemits_the_opening_and_absorbed_request_membership() {let directory = tempfile::tempdir().unwrap();diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.mdindex 09c59ca8..fe62aab1 100644--- a/docs/code-map/architecture.md+++ b/docs/code-map/architecture.md@@ -271,6 +271,18 @@ file size nor test churn alone justifies another abstraction or a broad rewrite.Trial cost reads use the internal admitted `TrustCostScopeV1`, joining retained analysis stage identity to Plan/revision/category/group before calling the shared per-attempt comparison engine. [Evidence-gap scenarios](../../crates/observation/src/store/tests/trust_cost_tests.rs) distinguish partial history from conflicting membership, pending projections from unresolved turns, and conservative coverage from paired subtotals. They preserve the general value query and frozen settlement contracts. The [Desktop timeline](../../apps/desktop/src/features/RoutingTimeline.tsx) reconciles absorbed provisional rows using returned request membership; [focused presentation checks](../../apps/desktop/tests/v3/visual/new-model-trial-active.mjs) cover selection, actual focus transfer without stealing focus, and partial monetary subtotals. Live timeline transition presentation adapts the same endpoint/time membership and classifier used by retained analysis; cache mutexes cover only taking and returning snapshots, never SQL or projection. [Real reader exhaustion](../../crates/daemon/src/control/runtime_timeline_retry_tests.rs) and [CLI follow](../../crates/cli/tests/routing_timeline_follow.rs) verify the structured failure boundary and retry recovery.+[Session detail](../../apps/desktop/src/features/Sessions.tsx) separately refreshes+the selected summary and visible unresolved excerpts; turn-fact digests do not+describe body availability. [Live refresh scenarios](../../apps/desktop/tests/v3/visual/session-live-refresh-active.mjs)+cover delayed content, stale responses and cleanup. Current summary visibility and+successful cleanup govern cached titles and request excerpts even when cleanup+removes every catalog row; new requests do not revive cleared request content.+[Timeline presentation scenarios](../../apps/desktop/tests/v3/visual/timeline-presentation-active.mjs)+cover exact assessment identities, transient-read recovery and fixed-label geometry.+The [transition adapter](../../crates/observation/src/query_v2/routing_timeline/transitions.rs)+coalesces only redundant intermediate comparisons proven by the same completed+turn endpoints; shared retained-analysis classification and recorded facts remain authoritative.+### Complete official data and saved default intentThe [feed service](../../crates/daemon/src/model_feed) owns complete snapshot selection,diff --git a/issue-spec/specs/session-history/spec.md b/issue-spec/specs/session-history/spec.mdindex 9a765b3b..3d1590cf 100644--- a/issue-spec/specs/session-history/spec.md+++ b/issue-spec/specs/session-history/spec.md@@ -496,7 +496,46 @@ The view SHALL disclose that client background messages can satisfy the new-messThe opening request supplies stable display identity before completion. Late assessments and valuations update that turn. When late authoritative request membership absorbs provisional rows into a completed turn, Desktop SHALL remove the absorbed rows by their exact opening-request identities, transfer their selection/focus to the owning turn, and reconcile overview, request and turn counts. Names, timing or model similarity SHALL NOT infer membership. Incremental cursors MUST be authenticated and bound to reader, session, page size and retained visibility; pagination freezes fact, valuation and link positions until its changed page is consumed. Reconnect deduplicates equal content digests. Cleared or expired scope invalidates the cursor. Unknown usage/cost remains unknown; per-model currency and valuation basis are preserved. A per-model sum SHALL retain available known amounts when another contribution is unknown, disclose that it is a known subtotal and retain the missing contribution. No known contribution means amount unknown, not zero. Frozen API-equivalent amounts SHALL be labeled estimates in summary and request detail.-Reads retain shared authorization, a 500 ms storage deadline, and explicit retryable scope errors beyond 10,000 requests, 50,000 facts or a 1 MiB response. Cache locks cover only take/return, never database reads, projection or serialization. Visible Desktop timelines refresh every two seconds; hidden views stop polling and catch up when shown. A storage timeout stops automatic retries until explicit Retry. Busy readers quietly honor the bounded retry hint while retaining content. CLI --follow emits NDJSON through the same query, preserves terminal errors, remains interruptible while busy and retries at most three consecutive transient unavailable failures. Live and retained readers use recorded endpoint/start-time membership and the same retained transition classifier; unrelated timestamp ties stay unassigned.+Reads retain shared authorization, a 500 ms storage deadline, and explicit scope errors beyond 10,000 requests, 50,000 facts or a 1 MiB response. Deadline exhaustion is a transient read timeout, not evidence that the retained population exceeds a capacity limit. Cache locks cover only take/return, never database reads, projection or serialization. Visible Desktop timelines refresh every two seconds; hidden views stop polling and catch up when shown. Transient failures retain the last successful view, disclose that it is awaiting refresh, and retry with bounded backoff while visible. Actual capacity failures require explicit Retry. Busy readers honor the bounded retry hint while retaining content. CLI --follow emits NDJSON through the same query, preserves terminal errors, remains interruptible while busy and retries at most three consecutive transient unavailable failures. Live and retained readers use recorded endpoint/start-time membership and the same retained transition classifier; unrelated timestamp ties stay unassigned.++Selected-session summary metadata and visible unresolved excerpts SHALL refresh independently of the turn-fact digest. Refreshing an existing session SHALL preserve selection, loaded list pages and scroll position; a stale response from an earlier selection SHALL NOT replace the current session. Transient content failures and pending content SHALL NOT be described as proven deletion. Content cleanup invalidates visible excerpts and later reads SHALL respect current visibility instead of restoring cleared content.++Displayed assessment ranges SHALL resolve exact target Agent-turn identities through the same chronological display coordinates as the overview and lanes. Agent-turn identity is distinct from the opening-request identity used for stable timeline selection. Producer-local ordinals SHALL NOT stand in for displayed turn numbers. A target outside the loaded or retained range, or with ambiguous identity, SHALL be disclosed without inventing a number. Plan names and execution model identifiers SHALL be labeled by their distinct meaning; a friendly model name requires an authoritative mapping, and the exact execution identifier remains available.++Timeline transition summaries SHALL distinguish a completed turn comparison from intermediate request comparisons. A complete authoritative comparison may subsume a redundant nonfinal unknown comparison only when both identify the same known predecessor and the same previous/current model and reasoning identities and change facts. Different endpoints, different models, pending or partial evidence, within-request fallback and credential relays remain distinguishable. A missing request-level comparison SHALL NOT be presented as a missing final turn comparison.++#### Scenario: A bounded timeline read times out and recovers++- **WHEN** a timeline within capacity limits temporarily exhausts its read deadline+- **THEN** the response identifies a retryable timeout, Desktop retains its last successful view and retries while visible, and recovery resumes updates without manual navigation.+- **AND** a real request, fact or response-size limit still produces a capacity failure rather than an unbounded read.++#### Scenario: Summary changes while a timeline is selected++- **WHEN** later requests update a selected session's last activity or content completeness+- **THEN** its header and existing list entry refresh without resetting selected turns, list pagination or scroll position, and an older response cannot overwrite a later selection.++#### Scenario: Excerpt becomes readable without another turn fact++- **WHEN** a visible excerpt's content becomes readable after an empty or failed read while its turn digest remains unchanged+- **THEN** a bounded recheck displays the content; inactive or hidden views stop rechecking and resume when visible.+- **AND** cleanup removes the excerpt and a stale in-flight read cannot restore it.++#### Scenario: Confirmed cleanup is distinct from content awaiting capture++- **WHEN** successful cleanup or current session metadata confirms deleted or expired content, including when request counts, activity timestamps and turn digests remain unchanged+- **THEN** visible titles and excerpts discard cached text, show cleared content and stop body retries, including after reopening the session. An empty catalog alone is not proof of deletion.+- **AND** a later request may make new session content readable without restoring content from requests already confirmed cleared.++#### Scenario: Assessment after a producer epoch changes++- **WHEN** a producer restarts its local ordinal sequence and a later displayed turn has an assessment+- **THEN** the assessment uses its exact target identities to name the displayed turns, or explicitly reports a target outside the available range.++#### Scenario: A multi-request turn gains a complete comparison++- **WHEN** a completed turn has an authoritative complete comparison and an earlier redundant unknown comparison of the same known predecessor and model identities+- **THEN** the turn summary presents the complete comparison while retaining request records and all distinct request-level changes or evidence gaps.#### Scenario: Assessment arrives during pagination@@ -636,6 +675,11 @@ Above the routing lanes, session detail MUST provide a compact overview with one- **WHEN** turns arrive while the user navigates overview marks or lane controls by keyboard- **THEN** the overview keeps one Tab stop and its readable labels, arrow navigation and activation work, and chronological lane focus and live-follow or explicit-selection behavior remain available as matching marks are added+#### Scenario: Scroll beneath fixed lane labels++- **WHEN** lane cards move behind the fixed label column during horizontal scrolling+- **THEN** the entire fixed column occludes those cards visually and for pointer hit testing, while keyboard focus remains visible and the focused turn can be brought into view.+Source SPEC comments:- https://github.com/higress-group/HiRoute/issues/140#issuecomment-6253019758