Skip to content

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.

fix: preserve configured execution prices and reconcile live timeline turns (#206)

澄潭f556e64c7b6b
diff --git a/apps/desktop/src/features/RoutingTimeline.tsx b/apps/desktop/src/features/RoutingTimeline.tsx
index 0d5514b3..ae125659 100644
--- a/apps/desktop/src/features/RoutingTimeline.tsx
+++ b/apps/desktop/src/features/RoutingTimeline.tsx
@@ -60,6 +60,8 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV
const lastRead = useRef(-Infinity);
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(() => {
@@ -79,6 +81,26 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV
if (controller.signal.aborted) return;
let changed = false;
const fresh = watermark.current !== null && probed.current ? page.turns.filter(turn => !stored.current.has(turn.turn_id)).map(turn => turn.turn_id) : [];
+ const owners = new Map(page.turns.flatMap(turn => turn.requests.map(request => [request.request_id, turn.turn_id] as const)));
+ const absorbed = new Map<string, string>();
+ for (const id of stored.current.keys()) {
+ const owner = owners.get(id);
+ if (owner && owner !== id) { stored.current.delete(id); absorbed.set(id, owner); changed = true; }
+ }
+ if (absorbed.size) {
+ const focused = document.activeElement;
+ if (focused && timeline.current?.contains(focused)) {
+ const overview = focused.closest('[data-overview-turn]');
+ const control = overview ?? focused.closest('.routing-turn[data-turn-id]');
+ const attribute = overview ? 'data-overview-turn' : 'data-turn-id';
+ const owner = absorbed.get(control?.getAttribute(attribute) ?? '');
+ if (owner) pendingFocus.current = { from: focused, owner, attribute };
+ }
+ setSelected(current => current ? absorbed.get(current) ?? current : null);
+ setOverviewFocus(current => current ? absorbed.get(current) ?? current : null);
+ setArrivals(current => new Set([...current].filter(id => !absorbed.has(id))));
+ setUnseen(current => current.filter(id => !absorbed.has(id)));
+ }
for (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)));
@@ -106,6 +128,15 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV
if (displayed && probed.current && since < 2000) schedule(2000 - since); else void load();
return () => { controller.abort(); window.clearTimeout(timer); document.removeEventListener('visibilitychange', visible); window.removeEventListener('hiroute-content-invalidated', invalidate); };
}, [session, active, displayed, refreshVersion, retry]);
+ useLayoutEffect(() => {
+ const focus = pendingFocus.current;
+ pendingFocus.current = null;
+ if (!focus || !displayed || !timeline.current) return;
+ // A removed control loses focus to the body. Never take it from another control.
+ if (document.activeElement !== document.body && document.activeElement !== focus.from) return;
+ [...timeline.current.querySelectorAll<HTMLElement | SVGGElement>(`[${focus.attribute}]`)]
+ .find(element => element.getAttribute(focus.attribute) === focus.owner)?.focus();
+ }, [turns, displayed]);
useEffect(() => { const turn = turns.find(t => t.requests.some(r => r.request_id === requestId)); if (turn) setSelected(turn.turn_id); }, [requestId, turns]);
const blocked = error.toLowerCase().includes('scope_too_large');
const availability: TimelineAvailability = turns.length ? 'turns' : blocked ? 'blocked' : error ? 'unavailable' : loaded ? 'empty' : 'loading';
@@ -156,6 +187,8 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV
const score = (turn: TimelineTurn) => turn.assessment ? `${turn.assessment.partial ? text('部分评分', 'Partial') : text('评分', 'Score')} ${turn.assessment.score.toFixed(2)}`
: turn.status === 'running' ? text('进行中…', 'Running…') : turn.assessment_state === 'pending' ? text('等待评分', 'Awaiting score') : text('未评分', 'Unscored');
const amount = (micros: number | null, currency: string | null) => micros === null || !currency ? text('金额未知', 'Amount unknown') : formatMoney(currency, (micros / 1_000_000).toFixed(micros >= 10_000 ? 3 : 4));
+ const costBasis = (cost: Cost) => cost.valuation_kind === 'api_equivalent' ? text('API 等价估算', 'API equivalent estimate') : text('估算', 'estimate');
+ const costAmount = (cost: Cost) => `${cost.valuation_kind === 'api_equivalent' ? `${costBasis(cost)} ` : ''}${amount(cost.known_micros, cost.currency)}${cost.unknown_contributions ? text(' + 未知部分', ' + unknown') : ''}`;
const percent = (share: number | null) => share === null ? text('未知', 'unknown') : `${Math.round(share * 100)}%`;
const tokens = (count: number | null) => count === null ? '—' : formatTokenCount(count, language);
@@ -169,7 +202,12 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV
const key = `${cost.model_configuration_id}\u0000${cost.currency}\u0000${cost.valuation_kind}`;
const total = totals.get(key);
if (!total) totals.set(key, { cost: { ...cost }, lane: laneOf(turn) });
- else total.cost = { ...total.cost, known_micros: total.cost.known_micros === null || cost.known_micros === null ? null : total.cost.known_micros + cost.known_micros, unknown_contributions: total.cost.unknown_contributions + cost.unknown_contributions };
+ else {
+ const sum = (total.cost.known_micros ?? 0) + (cost.known_micros ?? 0);
+ const known = total.cost.known_micros !== null || cost.known_micros !== null;
+ const overflow = known && !Number.isSafeInteger(sum);
+ total.cost = { ...total.cost, known_micros: known && !overflow ? sum : null, unknown_contributions: total.cost.unknown_contributions + cost.unknown_contributions + Number(overflow) };
+ }
}
const last = turns[turns.length - 1];
const running = last?.status === 'running';
@@ -274,22 +312,22 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV
<span className="routing-detail-label">{text(`请求(${selectedTurn.requests.length})`, `Requests (${selectedTurn.requests.length})`)}</span>
<div className="routing-turn-requests">{requests.map((request, i) => <button className={`routing-request${request.request_id === requestId ? ' selected' : ''}${failed(request) ? ' failed' : ''}`} type="button" key={request.request_id} onClick={() => onSelectRequest(request)}>
<span className="routing-request-index">#{i + 1}</span>
- <span className="routing-request-main"><span>{text('输入', 'In')} {tokens(request.input_tokens)} · {text('输出', 'Out')} {tokens(request.output_tokens)}</span><small>{[request.native_model ?? text('模型未记录', 'Model unknown'), request.duration_ms === null ? '' : `${(request.duration_ms / 1000).toFixed(1)} s`, request.costs.map(cost => amount(cost.known_micros, cost.currency) + (cost.unknown_contributions ? text(' + 未知部分', ' + unknown') : '')).join(' · '), failed(request) ? text('失败', 'Failed') : ''].filter(Boolean).join(' · ')}</small></span>
+ <span className="routing-request-main"><span>{text('输入', 'In')} {tokens(request.input_tokens)} · {text('输出', 'Out')} {tokens(request.output_tokens)}</span><small>{[request.native_model ?? text('模型未记录', 'Model unknown'), request.duration_ms === null ? '' : `${(request.duration_ms / 1000).toFixed(1)} s`, request.costs.map(costAmount).join(' · '), failed(request) ? text('失败', 'Failed') : ''].filter(Boolean).join(' · ')}</small></span>
<span className={`badge no-dot ${request.cache_read_share !== null && request.cache_read_share >= 0.5 ? 'good' : ''}`}>{text('缓存', 'Cache')} {percent(request.cache_read_share)}</span>
</button>)}</div>
{!allRequests && selectedTurn.requests.length > REQUESTS && <button type="button" className="btn btn-quiet" onClick={() => setAllRequests(true)}>{text(`显示全部 ${selectedTurn.requests.length} 个请求`, `Show all ${selectedTurn.requests.length} requests`)}</button>}
- {selectedTurn.cost_by_model.length > 0 && <p className="routing-detail-facts">{text('这一轮按模型估算:', 'This turn by model: ')}{selectedTurn.cost_by_model.map(cost => `${names.get(cost.model_configuration_id ?? '') ?? cost.model_configuration_id ?? text('模型未知', 'unknown model')} ${amount(cost.known_micros, cost.currency)}${cost.unknown_contributions ? text(' + 未知部分', ' + unknown') : ''}`).join(' · ')}</p>}
+ {selectedTurn.cost_by_model.length > 0 && <p className="routing-detail-facts">{text('这一轮按模型估算:', 'This turn by model: ')}{selectedTurn.cost_by_model.map(cost => `${names.get(cost.model_configuration_id ?? '') ?? cost.model_configuration_id ?? text('模型未知', 'unknown model')} ${costAmount(cost)}`).join(' · ')}</p>}
</div>
</div>;
})();
- return <section className="routing-timeline" aria-label={text('路由时间线', 'Routing timeline')}>
+ 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>}
{!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">
- {[...totals.values()].map(({ cost, lane }) => <div className="routing-tile" key={`${cost.model_configuration_id}/${cost.currency}/${cost.valuation_kind}`}><span>{names.get(cost.model_configuration_id ?? '') ?? cost.model_configuration_id ?? text('模型未知', 'Unknown model')} · {cost.valuation_kind === 'api_equivalent' ? text('API 等价', 'API equivalent') : text('估算', 'estimate')}</span><strong className={tone(lane)}>{amount(cost.known_micros, cost.currency)}</strong>{cost.unknown_contributions > 0 && <small>{text('另有未知部分', 'Plus an unknown portion')}</small>}</div>)}
+ {[...totals.values()].map(({ cost, lane }) => <div className="routing-tile" key={`${cost.model_configuration_id}/${cost.currency}/${cost.valuation_kind}`}><span>{names.get(cost.model_configuration_id ?? '') ?? cost.model_configuration_id ?? text('模型未知', 'Unknown model')} · {costBasis(cost)}</span><strong className={tone(lane)}>{amount(cost.known_micros, cost.currency)}</strong>{cost.unknown_contributions > 0 && <small>{cost.known_micros === null ? text('记录不足,暂不能估算', 'Not enough evidence to estimate') : text('已知小计 · 另有未知部分', 'Known subtotal · Plus an unknown portion')}</small>}</div>)}
<div className="routing-tile"><span>{text('Agent 轮次', 'Agent turns')}</span><strong>{turns.length}</strong><small>{text(`${turns.reduce((n, turn) => n + turn.requests.length, 0)} 个请求`, `${turns.reduce((n, turn) => n + turn.requests.length, 0)} requests`)}</small></div>
</div>}
{turns.length > 0 && <div className="routing-lanes-card">
diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.md
index bb405aa4..6c049dc2 100644
--- a/apps/desktop/tests/README.md
+++ b/apps/desktop/tests/README.md
@@ -62,6 +62,21 @@ proves native authorization, persistence, process cleanup or real model calls.
| 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. |
+The focused timeline pricing checks run with
+`node tests/v3/visual/new-model-trial.mjs <evidence-directory> --timeline-pricing`.
+They also run in the default trial suite. Production components must remove a
+provisional row absorbed by exact completed-request membership, retain selection,
+actual keyboard focus and correct counts, and show known API-equivalent subtotals alongside unknown
+contributions in Chinese and English. Mock IPC proves presentation, while the
+native model-save publication journey covers installed price edits, real Gateway
+valuation, frozen history and restart.
+
+Completion focus scenarios exercise overview and lane controls with real keyboard
+and mouse events, including visible keyboard focus. They retain focus on an
+unrelated search field, a surviving turn or the page body instead of moving it
+because selection changed. English/light at 755×600 and Chinese/dark at 1200×813
+use production components and styles; native WebView acceptance remains separate.
+
The [historical protection and overview scenarios](v3/visual/new-model-trial-protection-active.mjs)
run with `node tests/v3/visual/new-model-trial.mjs <evidence-directory> --protection`.
They verify scope-matched release counts and explicit unavailable reasons, a selectable
diff --git a/apps/desktop/tests/v3/browser/new-model-trial.tsx b/apps/desktop/tests/v3/browser/new-model-trial.tsx
index a7953073..e1382160 100644
--- a/apps/desktop/tests/v3/browser/new-model-trial.tsx
+++ b/apps/desktop/tests/v3/browser/new-model-trial.tsx
@@ -68,6 +68,15 @@ const homeSuggestions = [
const timelineRequests = (params.has('polish') ? Array.from({length:Number(params.get('turns')??2)},(_,i)=>i+1) : params.has('stale-timeline') ? [1,2,3] : [1,2]).map(i => ({request_id:`request-${i}`,started_at_ms:Date.now()-10000+i*1000,duration_ms:1500,native_model:i===1?'primary-model':'trial-model',input_tokens:1000,output_tokens:200,cache_read_tokens:990,cache_read_share:0.99,costs:[{model_configuration_id:i===1?'Primary':'Trial',currency:'USD',valuation_kind:'usage_estimate',known_micros:1250,unknown_contributions:i===1?0:1}],outcome:params.get('request-outcome')??'accepted'}));
let timelinePolls=0; let busyReturned=false;
const timelineTurn = (i:number,updated=false): TimelineTurn => { const turn: TimelineTurn = {turn_id:`request-${i}`,agent_turn_id:`turn-${i}`,segment_id:`stage-${i}`,started_at_ms:timelineRequests[i-1].started_at_ms,finished_at_ms:timelineRequests[i-1].started_at_ms+1500,boundary:i===1?'new_user_message':params.get('boundary')==='rebuilt'?'context_rebuilt':'unknown',plan_id:dailyPlan.agent_plan_id,plan_revision:8,branch_id:'smart_saving',model_configuration_id:i===1?'Primary model with a long readable name':'Trial model',reasoning_profile_id:'high',group:i===1?'primary':'regular',selection:{simple_probability:i===1?0.62:0.94,simple_threshold_millis:900,selection_reason:i===1?'complex_task':'simple_task',competence_trigger:null},tool_continuations:1,relays:[],assessment_state:updated?'scored':'pending',assessment:updated?{score:0.4,partial:false,target_from_ordinal:1,target_through_ordinal:1}:null,competence_floor_millis:500,protected_turn_ids:[],status:'completed',requests:[timelineRequests[i-1]],cost_by_model:timelineRequests[i-1].costs,evidence_partial:false,content_digest:`digest-${i}-${updated}`};
+ if(params.has('absorbed-turn')) {
+ turn.agent_turn_id=null;turn.status='running';turn.group='regular';turn.model_configuration_id='Trial model';
+ turn.requests=[{...turn.requests[0],native_model:'trial-model'}];
+ }
+ if(params.has('partial-cost')) {
+ turn.model_configuration_id='Trial model'; turn.group='regular';
+ turn.requests=[{...turn.requests[0],native_model:'trial-model',costs:[{model_configuration_id:'Trial model',currency:'USD',valuation_kind:'api_equivalent',known_micros:i===1?null:1250,unknown_contributions:i===1?1:0}]}];
+ turn.cost_by_model=turn.requests[0].costs;
+ }
if(params.has('protection')) {
const outcome = (['applied','suppressed','retained_unavailable','not_needed','not_considered',null] as const)[(i-1)%6];
const protectedTurn = outcome==='applied' || outcome==='retained_unavailable';
@@ -128,6 +137,16 @@ mockIPC(async (command, payload: any) => {
if(params.has('timeline-error') && (window as any).timelineFail!==false) throw {code:'OBSERVATION_UNAVAILABLE'};
if(params.has('timeline-empty')) return {turns:[],watermark:'empty',complete:true};
timelinePolls++;
+ if(params.has('absorbed-turn')) {
+ if(timelinePolls===1)return {turns:[timelineTurn(1),timelineTurn(2)],watermark:'watermark-1',complete:true};
+ if(timelinePolls===2) {
+ const turn=timelineTurn(1,true);turn.agent_turn_id='closed-turn';turn.status='completed';
+ turn.requests=[...timelineTurn(1).requests,...timelineTurn(2).requests];
+ turn.cost_by_model=turn.requests.flatMap(request=>request.costs);turn.content_digest='closed-with-two-requests';
+ return {turns:[turn],watermark:'watermark-2',complete:true};
+ }
+ return {turns:[],watermark:`watermark-${timelinePolls}`,complete:true};
+ }
if(params.has('polish')) {
const indices=query.after_watermark==null?timelineRequests.map((_,i)=>i+1):pendingTimelineTurns;
const turns=indices.map(i=>timelineTurn(i));pendingTimelineTurns=[];
diff --git a/apps/desktop/tests/v3/visual/new-model-trial-active.mjs b/apps/desktop/tests/v3/visual/new-model-trial-active.mjs
index fec0f219..154531b5 100644
--- a/apps/desktop/tests/v3/visual/new-model-trial-active.mjs
+++ b/apps/desktop/tests/v3/visual/new-model-trial-active.mjs
@@ -22,7 +22,57 @@ const timelineReads=()=>evaluate(client,timelineReadsExpr);
const setVisibility=state=>evaluate(client,`(()=>{Object.defineProperty(document,'visibilityState',{configurable:true,get:()=>${JSON.stringify(state)}});document.dispatchEvent(new Event('visibilitychange'));return true;})()`);
const typeInto=(selector,value)=>evaluate(client,`(()=>{const input=document.querySelector(${JSON.stringify(selector)});if(!input)throw Error('Missing input');Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(input,${JSON.stringify(value)});input.dispatchEvent(new Event('input',{bubbles:true}));return true;})()`);
async function geometry(){return evaluate(client,`(()=>{const nodes=[...document.querySelectorAll('.model-feed-panel,.trust-control,.plan-quality,.trust-suggestion,.modal,.trial-wizard')].filter(e=>e.getClientRects().length);return nodes.map(e=>({class:e.className,width:e.clientWidth,scroll:e.scrollWidth,left:e.getBoundingClientRect().left,right:e.getBoundingClientRect().right}));})()`);}
+async function timelineFocusChecks() {
+ const enter=async()=>{for(const type of ['keyDown','keyUp'])await client.send('Input.dispatchKeyEvent',{type,key:'Enter',code:'Enter',windowsVirtualKeyCode:13});};
+ for(const [lang,theme,width,height] of [['en','light',755,600],['zh','dark',1200,813]]) {
+ for(const kind of ['overview-keyboard','lane-keyboard','lane-mouse','outside-control','retained-turn','body']) {
+ await open(`lang=${lang}&theme=${theme}&view=timeline&absorbed-turn=1`,width,height);
+ await waitFor(client,`document.querySelectorAll('.routing-turn').length===2 && [...document.querySelectorAll('.routing-turn')].every(node=>node.getClientRects().length>0)`);
+ const overview=kind==='overview-keyboard';
+ const selector=overview?'[data-overview-turn="request-2"]':`.routing-turn[data-turn-id="${kind==='retained-turn'?'request-1':'request-2'}"]`;
+ if(kind==='lane-mouse') {
+ const point=await evaluate(client,`(()=>{const node=document.querySelector(${JSON.stringify(selector)});node.scrollIntoView({block:'center',inline:'center'});const r=node.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};})()`);
+ for(const type of ['mousePressed','mouseReleased'])await client.send('Input.dispatchMouseEvent',{type,...point,button:'left',clickCount:1});
+ } else if(kind==='body') await evaluate(client,`document.querySelector(${JSON.stringify(selector)}).click()`);
+ else {await evaluate(client,`document.querySelector(${JSON.stringify(selector)}).focus()`);await enter();}
+ if(kind==='outside-control')await evaluate(client,`document.querySelector('.search-box input').focus()`);
+ const before=kind==='outside-control'?'.search-box input':selector;
+ assert.equal(await evaluate(client,kind==='body'?`document.activeElement===document.body`:`document.activeElement.matches(${JSON.stringify(before)})`),true,`${kind}.${lang}: establishes the real focused control before completion`);
+ await waitFor(client,`document.querySelectorAll('.routing-turn').length===1`);
+ await shot(`timeline-focus-${kind}-${lang}-${width}`);
+ const expected=kind==='outside-control'?'.search-box input':overview?'[data-overview-turn="request-1"]':'.routing-turn[data-turn-id="request-1"]';
+ assert.equal(await evaluate(client,kind==='body'?`document.activeElement===document.body`:`document.activeElement.matches(${JSON.stringify(expected)})`),true,`${kind}: completion transfers only an absorbed control's DOM focus`);
+ assert.equal(await evaluate(client,`document.querySelector('.routing-turn-detail').textContent.includes(${JSON.stringify(lang==='zh'?'请求(2)':'Requests (2)')})`),true,'the selected owner retains both requests');
+ if(kind.endsWith('keyboard'))assert.equal(await evaluate(client,`document.activeElement.matches(':focus-visible')`),true,'keyboard focus remains visible');
+ results.push({id:`timeline.completion-focus.${kind}.${lang}.${width}`,status:'passed'});
+ }
+ }
+}
+async function timelinePricingChecks() {
+ await timelineFocusChecks();
+ await open('lang=en&view=timeline&absorbed-turn=1');
+ await waitFor(client,`document.querySelectorAll('.routing-turn').length===2`);
+ await click('.routing-turn','Turn 2');
+ await waitFor(client,`document.querySelectorAll('.routing-turn').length===1`);
+ assert.equal(await evaluate(client,`document.querySelector('.routing-turn-detail').textContent.includes('Requests (2)')`),true,'selection follows the completed opening turn');
+ assert.equal(await evaluate(client,`document.querySelector('.routing-tile:last-child strong').textContent`),'1','the absorbed row is not counted as another Agent turn');
+ assert.equal(await evaluate(client,`${timelineReadsExpr}>1 && trialTrace.filter(x=>x.command==='observation_read'&&x.payload.request.intent.view==='routing_timeline').every((x,i)=>i===0||x.payload.request.intent.query.after_watermark!==null)`),true,'normal completion needs no failed read or full reload');
+ await shot('timeline-completion-removes-provisional-row-en-755');
+ results.push({id:'timeline.completion-removes-provisional-row-and-preserves-selection',status:'passed'});
+ for(const lang of ['en','zh']) {
+ await open(`lang=${lang}&view=timeline&partial-cost=1`);
+ await waitFor(client,`document.querySelectorAll('.routing-turn').length===2`);
+ const subtotal=await evaluate(client,`document.querySelector('.routing-tile').textContent`);
+ assert.ok(subtotal.includes('0.0013'),'known request amounts survive another request with unknown amount');
+ assert.ok(subtotal.includes(lang==='zh'?'另有未知部分':'Plus an unknown portion'),'partial totals retain the gap');
+ assert.ok(subtotal.includes(lang==='zh'?'API 等价估算':'API equivalent estimate'),'reference value is labeled as an estimate');
+ await shot(`timeline-partial-reference-subtotal-${lang}-755`);
+ results.push({id:`timeline.known-reference-subtotal-with-unknown-requests.${lang}`,status:'passed'});
+ }
+}
try {
+ if(process.argv.includes('--timeline-pricing')) { await timelinePricingChecks(); }
+ else {
for(const [lang,theme,width,height] of [['en','light',755,600],['zh','dark',755,600],['en','dark',1200,813],['zh','light',1200,813]]) {
await open(`lang=${lang}&theme=${theme}&view=feed-home`,width,height);
await waitFor(client,`!!document.querySelector('.new-model-card')`);
@@ -233,6 +283,7 @@ try {
assert.equal(await evaluate(client,`document.querySelectorAll('.routing-ticks .failed').length`),2,'actual request failures retain failed ticks');
assert.ok(await evaluate(client,`document.querySelectorAll('.routing-request.failed').length>0`),'actual request failures retain failed detail rows');
results.push({id:'timeline.actual-request-outcomes',status:'passed'});
+ await timelinePricingChecks();
await open('lang=en&view=timeline&stale-timeline=1');
await waitFor(client,`document.querySelectorAll('.routing-turn').length===2`);
await waitFor(client,`document.querySelectorAll('.routing-turn').length===3`);
@@ -376,6 +427,7 @@ try {
await waitFor(client,`!document.querySelector('.trial-page') && !!document.querySelector('.new-models')`);
results.push({id:`quickstart.${lang}.inline-connection-guard.model-change-and-back`,status:'passed'});
}
+ }
await writeFile(path.join(output,'report.json'),JSON.stringify({proof:'production components with synthetic IPC; no native or provider claim',results},null,2));console.log(JSON.stringify({passed:results.length,output}));
} catch(error) {
const failure={error:String(error.stack??error),results};
diff --git a/apps/desktop/tests/v3/visual/new-model-trial.mjs b/apps/desktop/tests/v3/visual/new-model-trial.mjs
index 5ad5fdb0..f0b245d7 100644
--- a/apps/desktop/tests/v3/visual/new-model-trial.mjs
+++ b/apps/desktop/tests/v3/visual/new-model-trial.mjs
@@ -69,7 +69,7 @@ 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('--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], { cwd: desktopRoot, stdio: 'inherit' });
+ const runner = spawn(process.execPath, [path.join(here, 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 outcome = await waitForExit(runner);
if (outcome.code !== 0) process.exitCode = outcome.code ?? 1;
} finally {
diff --git a/crates/application/src/prices/control.rs b/crates/application/src/prices/control.rs
index a172602a..ea195c49 100644
--- a/crates/application/src/prices/control.rs
+++ b/crates/application/src/prices/control.rs
@@ -157,6 +157,7 @@ pub fn preview_source_price_change(
Some(entry) => entry.source_override = Some(change.after),
None => entries.push(PriceIndexEntryV1 {
target: target.clone(),
+ execution_binding_id: Some(change.binding_id.clone()),
actual_offer_ref: None,
reference_model_offer_ref: None,
catalog_rules: vec![],
diff --git a/crates/application/src/prices/snapshot.rs b/crates/application/src/prices/snapshot.rs
index ab246add..c98b23b3 100644
--- a/crates/application/src/prices/snapshot.rs
+++ b/crates/application/src/prices/snapshot.rs
@@ -16,6 +16,8 @@ pub struct CatalogPriceRuleV2 {
#[serde(deny_unknown_fields)]
pub struct PriceIndexEntryV1 {
pub target: PriceTargetV1,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub execution_binding_id: Option<String>,
pub actual_offer_ref: Option<String>,
pub reference_model_offer_ref: Option<PriceReferenceOfferV1>,
pub catalog_rules: Vec<CatalogPriceRuleV2>,
@@ -23,11 +25,34 @@ pub struct PriceIndexEntryV1 {
pub source_override: Option<SourcePriceOverrideV1>,
}
+#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
+struct ExecutionPriceKey {
+ workspace_id: WorkspaceId,
+ source_id: String,
+ source_identity_digest: CanonicalDigest,
+ binding_id: String,
+ currency: String,
+ valuation_kind: PriceValuationKindV1,
+}
+impl ExecutionPriceKey {
+ fn new(target: &PriceTargetV1, binding: &str) -> Self {
+ Self {
+ workspace_id: target.workspace_id.clone(),
+ source_id: target.source_id.clone(),
+ source_identity_digest: target.source_identity_digest.clone(),
+ binding_id: binding.into(),
+ currency: target.currency.clone(),
+ valuation_kind: target.valuation_kind,
+ }
+ }
+}
+
/// Immutable and indexed, constructed by the control writer from verified catalog/mapping facts.
#[derive(Debug)]
pub struct PriceSnapshot {
pub(super) generation: PriceGenerationRefV1,
pub(super) entries: BTreeMap<PriceTargetV1, PriceIndexEntryV1>,
+ execution_targets: BTreeMap<ExecutionPriceKey, Option<PriceTargetV1>>,
}
impl PriceSnapshot {
pub fn build(
@@ -47,8 +72,27 @@ impl PriceSnapshot {
}
catalog_refs.sort_by(|a, b| (&a.id, a.revision).cmp(&(&b.id, b.revision)));
let mut index = BTreeMap::new();
+ let mut execution_targets: BTreeMap<ExecutionPriceKey, Option<PriceTargetV1>> =
+ BTreeMap::new();
for entry in entries {
super::select::validate_entry(&entry)?;
+ if let Some(binding) = &entry.execution_binding_id {
+ if binding.is_empty()
+ || binding.len() > 256
+ || binding.chars().any(char::is_control)
+ {
+ return Err(ComputeContractError::InvalidPrice);
+ }
+ let execution = ExecutionPriceKey::new(&entry.target, binding);
+ execution_targets
+ .entry(execution)
+ .and_modify(|target| {
+ if target.as_ref() != Some(&entry.target) {
+ *target = None;
+ }
+ })
+ .or_insert_with(|| Some(entry.target.clone()));
+ }
if index.insert(entry.target.clone(), entry).is_some() {
return Err(ComputeContractError::DuplicateIdentity);
}
@@ -69,6 +113,7 @@ impl PriceSnapshot {
Ok(Self {
generation,
entries: index,
+ execution_targets,
})
}
pub fn generation_ref(&self) -> &PriceGenerationRefV1 {
@@ -88,6 +133,36 @@ impl PriceSnapshotHandle {
Self::Unavailable(_) => None,
}
}
+ /// The caller supplies the verified binding from its pinned publication. Its
+ /// compiled execution ID can predate a credential/source revision, while the
+ /// stable source/model binding still owns the current price. Never infer this
+ /// association from model names; retain the executed identity in the quote.
+ pub fn freeze_execution_price(
+ &self,
+ target: &PriceTargetV1,
+ binding: &str,
+ at: i64,
+ billing: PriceBillingContextV1,
+ ) -> Result<FrozenPriceQuoteV1, ComputeContractError> {
+ if let Self::Available(snapshot) = self
+ && let Some(mapped) = snapshot
+ .execution_targets
+ .get(&ExecutionPriceKey::new(target, binding))
+ {
+ let Some(mapped) = mapped else {
+ let mut quote = Self::Unavailable(PriceUnknownReasonV1::UnverifiedOfferMapping)
+ .freeze_price(target, at, billing)?;
+ quote.generation_ref = Some(snapshot.generation.clone());
+ quote.quote_digest = quote.computed_digest()?;
+ return Ok(quote);
+ };
+ let mut quote = self.freeze_price(mapped, at, billing)?;
+ quote.exact_target = target.clone();
+ quote.quote_digest = quote.computed_digest()?;
+ return Ok(quote);
+ }
+ self.freeze_price(target, at, billing)
+ }
/// Only bounded in-memory lookup, schedule evaluation and quote serialization.
/// Retain this handle for the whole LogicalRequest, including every retry/relay Attempt.
pub fn freeze_price(
diff --git a/crates/application/src/prices/tests.rs b/crates/application/src/prices/tests.rs
index bb797406..72b2d250 100644
--- a/crates/application/src/prices/tests.rs
+++ b/crates/application/src/prices/tests.rs
@@ -3,6 +3,7 @@ use hiroute_domain::*;
fn entry(source: &str) -> PriceIndexEntryV1 {
PriceIndexEntryV1 {
+ execution_binding_id: None,
target: PriceTargetV1 {
workspace_id: WorkspaceId::default(),
source_id: source.into(),
@@ -31,6 +32,108 @@ fn freeze(handle: &PriceSnapshotHandle, target: &PriceTargetV1, at: i64) -> Froz
.freeze_price(target, at, PriceBillingContextV1::StandardTokens)
.unwrap()
}
+
+#[test]
+fn compiled_custom_identity_uses_only_its_generation_bound_source_override() {
+ let mut custom = entry("custom-source");
+ custom.target.model_identity = PriceModelIdentityV1::LocalModel("model/authoring-ref".into());
+ custom.execution_binding_id = Some("binding-local".into());
+ custom.catalog_rules.clear();
+ custom.actual_offer_ref = None;
+ custom.source_override = Some(SourcePriceOverrideV1 {
+ target: custom.target.clone(),
+ revision: 1,
+ setting: SourcePriceSettingV1::Set {
+ rates: TokenRatesV1::from_legacy(300_000, 1_200_000),
+ },
+ });
+ let slot = PriceSnapshotSlot::default();
+ slot.install(
+ PriceSnapshot::build(1, vec![], vec![custom.clone()]).unwrap(),
+ None,
+ )
+ .unwrap();
+ let handle = slot.capture_current_price_snapshot();
+ let mut executed = custom.target.clone();
+ executed.model_identity =
+ PriceModelIdentityV1::CatalogModel("model/source-local/executed".into());
+ let read = |target: &PriceTargetV1| {
+ handle
+ .freeze_execution_price(
+ target,
+ "binding-local",
+ 100,
+ PriceBillingContextV1::StandardTokens,
+ )
+ .unwrap()
+ };
+ let quote = read(&executed);
+ assert_eq!(quote.rates.input_uncached, TokenRateV1::known(300_000));
+ assert_eq!(quote.exact_target, executed);
+ assert_eq!(
+ quote.applied_override_refs[0].id,
+ custom.target.digest().unwrap().to_string()
+ );
+ quote.verify_digest().unwrap();
+ for changed in ["source", "digest", "currency", "basis"] {
+ let mut wrong = executed.clone();
+ match changed {
+ "source" => wrong.source_id = "another-source".into(),
+ "digest" => wrong.source_identity_digest = CanonicalDigest::of_bytes(b"replaced"),
+ "currency" => wrong.currency = "EUR".into(),
+ _ => wrong.valuation_kind = PriceValuationKindV1::ApiEquivalent,
+ }
+ assert_eq!(read(&wrong).origin, PriceOriginV1::Unknown, "{changed}");
+ }
+ let mut newer_execution = executed.clone();
+ newer_execution.model_identity =
+ PriceModelIdentityV1::CatalogModel("model/source-local/new-revision".into());
+ assert_eq!(
+ read(&newer_execution).rates.input_uncached,
+ TokenRateV1::known(300_000)
+ );
+ assert_eq!(
+ handle
+ .freeze_execution_price(
+ &executed,
+ "other-binding",
+ 100,
+ PriceBillingContextV1::StandardTokens
+ )
+ .unwrap()
+ .origin,
+ PriceOriginV1::Unknown
+ );
+ let mut duplicate = custom.clone();
+ duplicate.target.model_identity =
+ PriceModelIdentityV1::LocalModel("model/other-authoring-ref".into());
+ duplicate.source_override.as_mut().unwrap().target = duplicate.target.clone();
+ slot.install(
+ PriceSnapshot::build(2, vec![], vec![custom, duplicate]).unwrap(),
+ handle.generation_ref(),
+ )
+ .unwrap();
+ let ambiguous = slot
+ .capture_current_price_snapshot()
+ .freeze_execution_price(
+ &executed,
+ "binding-local",
+ 100,
+ PriceBillingContextV1::StandardTokens,
+ )
+ .unwrap();
+ assert_eq!(ambiguous.origin, PriceOriginV1::Unknown);
+ assert_eq!(
+ ambiguous.unknown_reasons,
+ vec![PriceUnknownReasonV1::UnverifiedOfferMapping]
+ );
+ assert!(ambiguous.generation_ref.is_some());
+ ambiguous.verify_digest().unwrap();
+ assert_eq!(
+ read(&executed).rates.input_uncached,
+ TokenRateV1::known(300_000)
+ );
+}
#[test]
fn price_snapshot_manual_without_catalog_is_source_currency_and_identity_isolated() {
let mut a = entry("a");
diff --git a/crates/daemon/src/control/runtime/prices.rs b/crates/daemon/src/control/runtime/prices.rs
index be9b1d4c..03feab68 100644
--- a/crates/daemon/src/control/runtime/prices.rs
+++ b/crates/daemon/src/control/runtime/prices.rs
@@ -336,6 +336,7 @@ impl LocalControlAdapter {
let source_override = overrides.iter().find(|o| o.target == target).cloned();
entries.push(PriceIndexEntryV1 {
target,
+ execution_binding_id: Some(binding.binding_id.clone()),
actual_offer_ref: offer.map(|o| o.offer_id.clone()),
reference_model_offer_ref: None,
catalog_rules,
diff --git a/crates/daemon/src/gateway_ports/pricing.rs b/crates/daemon/src/gateway_ports/pricing.rs
index c1742288..1dda3f06 100644
--- a/crates/daemon/src/gateway_ports/pricing.rs
+++ b/crates/daemon/src/gateway_ports/pricing.rs
@@ -3,7 +3,7 @@
use hiroute_application::prices::{PriceSnapshotHandle, PriceSnapshotSlot};
use hiroute_domain::{
EXECUTION_PRICING_SCHEMA_V1, ExecutionPricingEvidenceV1, PriceModelIdentityV1, PriceOriginV1,
- PriceTargetV1, PriceUnknownReasonV1, PriceValuationKindV1, WorkspaceId,
+ PriceTargetV1, PriceUnknownReasonV1, PriceValuationKindV1, TokenRateV1, WorkspaceId,
};
use hiroute_gateway::server::core_runtime::observation::{
RequestPriceSnapshot, RequestPriceSource,
@@ -131,8 +131,9 @@ impl RequestPriceSnapshot for CapturedPrice {
};
result.usage_semantics = target.usage_semantics;
// The snapshot API uses Unix seconds; execution evidence preserves ms.
- match self.snapshot.freeze_price(
+ match self.snapshot.freeze_execution_price(
&target.target,
+ binding,
at_ms / 1000,
target.billing_context.clone(),
) {
@@ -167,6 +168,26 @@ impl RequestPriceSnapshot for CapturedPrice {
result.unknown_reason = Some(PriceUnknownReasonV1::UnverifiedOfferMapping);
}
}
+ let usable = |quote: &hiroute_domain::FrozenPriceQuoteV1| {
+ matches!(quote.rates.input_uncached, TokenRateV1::Known { .. })
+ && matches!(quote.rates.output, TokenRateV1::Known { .. })
+ };
+ if result.quote.as_ref().is_none_or(|quote| !usable(quote)) {
+ let mut reference = target.target.clone();
+ reference.valuation_kind = PriceValuationKindV1::ApiEquivalent;
+ if let Ok(quote) = self.snapshot.freeze_execution_price(
+ &reference,
+ binding,
+ at_ms / 1000,
+ target.billing_context.clone(),
+ ) && usable(&quote)
+ {
+ // This is an explicitly configured reference estimate, never a
+ // substitute subscription bill or a repricing of old receipts.
+ result.unknown_reason = quote.unknown_reasons.first().copied();
+ result.quote = Some(quote);
+ }
+ }
result
}
}
diff --git a/crates/daemon/src/gateway_ports/pricing/tests.rs b/crates/daemon/src/gateway_ports/pricing/tests.rs
index 29a5ac5b..cf6d75f7 100644
--- a/crates/daemon/src/gateway_ports/pricing/tests.rs
+++ b/crates/daemon/src/gateway_ports/pricing/tests.rs
@@ -9,6 +9,7 @@ fn identity(seed: &str) -> CanonicalDigest {
fn entry(source: &str, model: &str, offer: &str, rate: u64) -> PriceIndexEntryV1 {
PriceIndexEntryV1 {
+ execution_binding_id: None,
target: PriceTargetV1 {
workspace_id: WorkspaceId::default(),
source_id: source.into(),
@@ -270,3 +271,137 @@ fn workspace_identity_is_part_of_the_price_target() {
TokenRateV1::unknown(PriceUnknownReasonV1::TargetNotInSnapshot)
);
}
+
+#[test]
+fn configured_api_equivalent_price_is_frozen_when_billing_price_is_unavailable() {
+ let mut actual = entry("source-a", "model-a", "offer-a", 100);
+ actual.catalog_rules.clear();
+ actual.actual_offer_ref = None;
+ let mut reference = actual.clone();
+ reference.target.valuation_kind = PriceValuationKindV1::ApiEquivalent;
+ reference.source_override = Some(SourcePriceOverrideV1 {
+ target: reference.target.clone(),
+ revision: 1,
+ setting: SourcePriceSettingV1::Set {
+ rates: TokenRatesV1::from_legacy(300_000, 1_200_000),
+ },
+ });
+ let slot = Arc::new(PriceSnapshotSlot::default());
+ slot.install(
+ PriceSnapshot::build(1, vec![], vec![actual, reference]).unwrap(),
+ None,
+ )
+ .unwrap();
+ let evidence = source(slot)
+ .capture_request(
+ WorkspaceId::DEFAULT,
+ &[binding(
+ "binding", "source-a", "model-a", "profile", "offer-a",
+ )],
+ 1000,
+ )
+ .freeze_attempt("binding", "model-a", "profile", 2000);
+ let quote = evidence.quote.as_ref().unwrap();
+ assert_eq!(quote.valuation_kind, PriceValuationKindV1::ApiEquivalent);
+ assert_eq!(quote.origin, PriceOriginV1::Manual);
+ assert_eq!(quote.rates.input_uncached, TokenRateV1::known(300_000));
+ assert_eq!(
+ quote.rates.cache_read,
+ TokenRateV1::unknown(PriceUnknownReasonV1::CacheRateNotCollected)
+ );
+ evidence.validate().unwrap();
+}
+
+#[test]
+fn configured_reference_does_not_replace_a_verified_billing_price() {
+ let actual = entry("source-a", "model-a", "offer-a", 100);
+ let mut reference = actual.clone();
+ reference.target.valuation_kind = PriceValuationKindV1::ApiEquivalent;
+ reference.catalog_rules.clear();
+ reference.source_override = Some(SourcePriceOverrideV1 {
+ target: reference.target.clone(),
+ revision: 1,
+ setting: SourcePriceSettingV1::Set {
+ rates: TokenRatesV1::from_legacy(900, 900),
+ },
+ });
+ let slot = Arc::new(PriceSnapshotSlot::default());
+ slot.install(
+ PriceSnapshot::build(1, vec![], vec![actual, reference]).unwrap(),
+ None,
+ )
+ .unwrap();
+ let evidence = source(slot)
+ .capture_request(
+ WorkspaceId::DEFAULT,
+ &[binding(
+ "binding", "source-a", "model-a", "profile", "offer-a",
+ )],
+ 1000,
+ )
+ .freeze_attempt("binding", "model-a", "profile", 2000);
+ let quote = evidence.quote.unwrap();
+ assert_eq!(quote.valuation_kind, PriceValuationKindV1::UsageEstimate);
+ assert_eq!(quote.rates.input_uncached, TokenRateV1::known(100));
+}
+
+#[test]
+fn pinned_publication_keeps_reference_price_after_source_revision_changes() {
+ let mut reference = entry("source-a", "current-execution", "offer-a", 2_000_000);
+ reference.target.model_identity = PriceModelIdentityV1::LocalModel("authoring-model".into());
+ reference.target.valuation_kind = PriceValuationKindV1::ApiEquivalent;
+ reference.execution_binding_id = Some("stable-binding".into());
+ reference.catalog_rules.clear();
+ reference.source_override = Some(SourcePriceOverrideV1 {
+ target: reference.target.clone(),
+ revision: 2,
+ setting: SourcePriceSettingV1::Set {
+ rates: TokenRatesV1::from_legacy(2_000_000, 2_000_000),
+ },
+ });
+ let slot = Arc::new(PriceSnapshotSlot::default());
+ slot.install(
+ PriceSnapshot::build(2, vec![], vec![reference]).unwrap(),
+ None,
+ )
+ .unwrap();
+ let bindings = [binding(
+ "stable-binding",
+ "source-a",
+ "pinned-older-execution",
+ "profile",
+ "older-offer",
+ )];
+ let captured = source(slot).capture_request(WorkspaceId::DEFAULT, &bindings, 100_000);
+ let evidence = captured.freeze_attempt(
+ "stable-binding",
+ "pinned-older-execution",
+ "profile",
+ 100_001,
+ );
+ evidence.validate().unwrap();
+ let quote = evidence.quote.unwrap();
+ assert_eq!(quote.valuation_kind, PriceValuationKindV1::ApiEquivalent);
+ assert_eq!(quote.rates.input_uncached, TokenRateV1::known(2_000_000));
+ assert_eq!(
+ quote.exact_target.model_identity,
+ PriceModelIdentityV1::CatalogModel("pinned-older-execution".into())
+ );
+ assert!(
+ captured
+ .freeze_attempt("stable-binding", "different-model", "profile", 100_001)
+ .quote
+ .is_none()
+ );
+ assert!(
+ captured
+ .freeze_attempt(
+ "other-binding",
+ "pinned-older-execution",
+ "profile",
+ 100_001
+ )
+ .quote
+ .is_none()
+ );
+}
diff --git a/crates/daemon/src/test_support.rs b/crates/daemon/src/test_support.rs
index cd70b9b6..7f0ae5b7 100644
--- a/crates/daemon/src/test_support.rs
+++ b/crates/daemon/src/test_support.rs
@@ -120,8 +120,15 @@ fn isolated_agent_home_inner(
]) {
command.env_remove(name);
}
- let status = command.status().unwrap();
- assert!(status.success(), "isolated daemon test failed: {test_name}");
+ // Parallel child harnesses must not interleave their summaries with the
+ // parent harness. Retain their diagnostics when a child actually fails.
+ let output = command.output().unwrap();
+ assert!(
+ output.status.success(),
+ "isolated daemon test failed: {test_name}\nstdout:\n{}\nstderr:\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
+ );
true
}
diff --git a/crates/daemon/tests/support/model_connections_product.py b/crates/daemon/tests/support/model_connections_product.py
index 71f5168d..d34c3edc 100644
--- a/crates/daemon/tests/support/model_connections_product.py
+++ b/crates/daemon/tests/support/model_connections_product.py
@@ -15,6 +15,7 @@ from pathlib import Path
from publication_process import configure_model_settings_v2
from publication_product import Product, encoded
+from source_pricing_product import configure_reference_price, timeline_amounts
MODEL = 'gpt-5.4'
@@ -697,15 +698,25 @@ def run(repository, expected_sha=None):
# source/account route instead of weakening the provider-switch coverage check.
product.install_codex_fixture(
MODEL, 'medium', upstream.base_url, replacement_token)
+ configure_reference_price(product, saved['binding_id'], 1_000_000)
publish_plan_and_agent(product, saved['binding_id'])
gateway_request(product)
session_id, observed_model = assert_session_record(product, started_ms)
+ frozen_amounts = timeline_amounts(product, session_id, 1)
+ configure_reference_price(product, saved['binding_id'], 2_000_000)
+ assert timeline_amounts(product, session_id, 1) == frozen_amounts
assert_live_credential_switches(product, upstream, saved)
product.stop()
product.start()
recheck_saved_native_source(product, saved, 3, 'after-restart')
recheck_saved_native_source(product, unknown, 3, 'unknown-after', unknown=True)
assert_session_record(product, started_ms, saved['binding_id'])
+ reopened_amounts = timeline_amounts(product, session_id, 3)
+ for request, costs in frozen_amounts.items():
+ assert reopened_amounts[request] == costs, 'price edits rewrote historical valuation'
+ first_amount = sum(cost['known_micros'] for costs in frozen_amounts.values() for cost in costs)
+ assert all(sum(cost['known_micros'] for cost in costs) == 2 * first_amount
+ for request, costs in reopened_amounts.items() if request not in frozen_amounts)
with upstream.lock:
requests = list(upstream.requests)
expected_host = 'localhost:%d' % upstream.server.server_address[1]
diff --git a/crates/daemon/tests/support/source_pricing_product.py b/crates/daemon/tests/support/source_pricing_product.py
new file mode 100644
index 00000000..0f1506fc
--- /dev/null
+++ b/crates/daemon/tests/support/source_pricing_product.py
@@ -0,0 +1,42 @@
+"""Source-scoped reference prices through the installed CLI and real Gateway valuation."""
+import time
+
+
+def configure_reference_price(product, binding_id, rate):
+ target = {'query_id': 'source-price', 'target_locator': {
+ 'kind': 'binding', 'binding_id': binding_id},
+ 'currency': 'USD', 'valuation_kind': 'api_equivalent'}
+ before = product.preview('prices effective', {'targets': [target]})
+ edit = before['items'][0]['edit_context']
+ rates = {field: {'state': 'known', 'micros_per_million_tokens': rate}
+ for field in ['input_uncached', 'output', 'cache_read', 'cache_write']}
+ preview = product.preview('prices override preview', {
+ **edit, 'currency': 'USD', 'valuation_kind': 'api_equivalent',
+ 'action': {'kind': 'set', 'rates': rates}})
+ product.apply('prices override apply', 'ApplyPriceOverrideChange', preview,
+ {'spec': preview['spec']}, 'source-price-' + str(rate))
+ after = product.preview('prices effective', {'targets': [target]})
+ assert not after['pending_activation'], after
+ assert after['items'][0]['quote']['rates'] == rates, after
+
+
+def timeline_amounts(product, session_id, expected_requests):
+ deadline = time.monotonic() + 20
+ while True:
+ code, reply = product.public_cli('sessions timeline ' + session_id, success=False)
+ if code:
+ assert reply.get('error', {}).get('retryable'), reply
+ amounts = {}
+ else:
+ amounts = {
+ request['request_id']: [cost for cost in request['costs']
+ if cost['valuation_kind'] == 'api_equivalent'
+ and cost['currency'] == 'USD' and cost['known_micros'] is not None]
+ for turn in reply['data']['turns'] for request in turn['requests']}
+ amounts = {key: costs for key, costs in amounts.items() if costs}
+ if len(amounts) == expected_requests:
+ assert all(sum(cost['known_micros'] for cost in costs) > 0
+ for costs in amounts.values()), amounts
+ return amounts
+ assert time.monotonic() < deadline, reply
+ time.sleep(.05)
diff --git a/crates/observation/src/store/tests/plan_quality/timeline_cache.rs b/crates/observation/src/store/tests/plan_quality/timeline_cache.rs
index 4d51cb92..4021926e 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,69 @@ use super::*;
use crate::query_v2::ObservationV2Error;
use hiroute_domain::{RoutingTimelineQueryV1, WorkspaceId};
+#[test]
+fn timeline_late_turn_completion_reemits_the_opening_and_absorbed_request_membership() {
+ let directory = tempfile::tempdir().unwrap();
+ let store = open_store(directory.path());
+ let first = Fixture::new("provisional-opening");
+ let mut continuation = Fixture::new("provisional-continuation");
+ continuation.session = first.session.clone();
+ continuation.fact_stream = first.fact_stream.clone();
+ let channel = fact_channel(&first, 256 * 1024);
+ let writer = writer(&store);
+ for (sequence, fixture, at) in [(1, &first, 1000), (2, &continuation, 1005)] {
+ assert!(matches!(
+ offer_fact(
+ &writer,
+ &channel,
+ fixture.fact(sequence, super::super::support::route_decision(PLAN), at)
+ ),
+ WriterCycleOutcome::Ack(_)
+ ));
+ }
+ let mut query = RoutingTimelineQueryV1 {
+ session_id: first.session.to_string(),
+ after_watermark: None,
+ limit: 50,
+ };
+ let provisional = store
+ .observed_routing_timeline(&reader(), &query, 5000)
+ .unwrap();
+ assert_eq!(provisional.turns.len(), 2);
+ let mut closed = finished(&first, "stage", "closed-turn", 1, "smart_saving", 1000);
+ if let ExecutionFactV1::AgentTurnFinished {
+ last_request_id, ..
+ } = &mut closed
+ {
+ *last_request_id = Some(continuation.request.clone());
+ }
+ assert!(matches!(
+ offer_fact(&writer, &channel, first.fact(3, closed, 1010)),
+ WriterCycleOutcome::Ack(_)
+ ));
+ query.after_watermark = Some(provisional.watermark);
+ let changed = store
+ .observed_routing_timeline(&reader(), &query, 5000)
+ .unwrap();
+ assert_eq!(changed.turns.len(), 1);
+ assert_eq!(changed.turns[0].turn_id, provisional.turns[0].turn_id);
+ assert_eq!(changed.turns[0].requests.len(), 2);
+ assert!(
+ changed.turns[0]
+ .requests
+ .iter()
+ .any(|request| request.request_id == provisional.turns[1].turn_id),
+ "clients can remove the absorbed provisional row by exact request membership"
+ );
+ query.after_watermark = None;
+ let completed = store
+ .observed_routing_timeline(&reader(), &query, 5000)
+ .unwrap();
+ assert_eq!(completed.turns.len(), 1);
+ assert_eq!(completed.turns[0].turn_id, provisional.turns[0].turn_id);
+ assert_eq!(completed.turns[0].requests.len(), 2);
+}
+
#[test]
fn timeline_evicted_frozen_page_restarts_without_skipping_retained_turns() {
let directory = tempfile::tempdir().unwrap();
diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.md
index e9f02056..e61cb565 100644
--- a/docs/code-map/architecture.md
+++ b/docs/code-map/architecture.md
@@ -188,6 +188,7 @@ or closed channels fail closed. Status separates reachability from protected aut
| Source disabled before an upstream attempt | [Exact permission gate](../../crates/local-storage/src/secrets/runtime.rs), [product preparation reply](../../crates/gateway/src/runtime/driver/selection/preparation.rs), [Gateway error guide](../../crates/gateway/README.md#candidate-preparation-errors) | Preserve the closed lease denial in the request fact and local JSON response; a frozen route does not grant current source/Key permission, and rejected preparation remains zero attempts |
| Inspect CPA authentication recovery | [Private response metadata](../../crates/gateway/src/observation/provider/cpa_execution.rs), [pinned CPA adapter](../../vendor/cpa/README.md) | Logical attempts and actual HTTP sends differ; only verified CPA targets can supply recovery counters. Missing evidence remains unknown and does not create token usage. |
| Same-user CLI analysis | [Read admission](../../crates/application/src/observation_query/control/v2.rs), [scoped analysis](../../crates/observation/src/analysis/read.rs), [CLI codec](../../crates/cli/src/observation.rs), [installed journey](../../crates/daemon/tests/support/quickstart_analysis.py) | Conversation, switch/reason, expense ranking and savings paths share retained scopes; control/price composition and indexed content reads keep one 500 ms budget. Supplied grants, current deletion/visibility and legacy calls remain checked. |
+| Recorded request estimates | [Captured price snapshot](../../crates/application/src/prices/snapshot.rs), [source/execution mapping](../../crates/daemon/src/control/runtime/prices.rs), [Gateway freeze](../../crates/daemon/src/gateway_ports/pricing.rs), [installed price regression](../../crates/daemon/tests/support/source_pricing_product.py) | Resolve exact source identity in one pinned generation; a configured API-equivalent estimate can fill unavailable billing prices while preserving its label, partial usage and frozen history. |
| Current API-equivalent comparison | [Analysis price capture](../../crates/application/src/observation_query/control/v2/analysis.rs), [numeric comparison](../../crates/observation/src/analysis/comparison.rs), [legacy adapter](../../crates/observation/src/analysis/legacy.rs) | Source-matched attempt inputs and immutable scoped prices use the same per-attempt arithmetic as the explicit-reference report. Unknown coverage is not zero; recorded valuation remains unchanged. |
| Native compression and actual transitions | [Hermes adapter](../../assets/agents/hermes/__init__.py), [private carrier](../../crates/domain/src/observation/native_continuation.rs), [relationship owner](../../crates/observation/src/analysis/native.rs), [transition reader](../../crates/observation/src/analysis/routing.rs) | Authenticated bounded ancestry does not change physical session identity or prove adjacent user turns. Shared member resolution and current source/deletion guards apply to content and monetary readers. |
| Analysis upgrades and deleted-history revival | [Schema/SQL triggers](../../crates/observation/src/analysis/schema.rs), [native creation proof](../../crates/observation/src/analysis/native_origin.rs), [joint deletion regression](../../crates/observation/src/store/tests/analysis_delete_tests.rs) | Core-table triggers also execute for supported released writers; replace dependent triggers/tables atomically. Full deletion cuts historical edges. Fresh native creation evidence can prove a new child after the cut; unknown origins remain gaps. Strict retained native-event bodies exclude the optional creation extension. |
@@ -268,4 +269,4 @@ foreign-file preservation tests. Assign shared contracts and generated registrie
to one convergence owner. Use the [test map](testing.md) to select evidence; neither
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. 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.
+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.
diff --git a/issue-spec/specs/model-catalog-price/spec.md b/issue-spec/specs/model-catalog-price/spec.md
index 9d8ada2c..7f476cdc 100644
--- a/issue-spec/specs/model-catalog-price/spec.md
+++ b/issue-spec/specs/model-catalog-price/spec.md
@@ -92,6 +92,16 @@ Gateway uses nonblocking read-only price snapshots; Observation settles
asynchronously. SQLite or valuation failure cannot block the model response.
Known failure-attempt usage still counts. Missing usage or pricing remains unknown,
not zero. Subscription API-equivalent value is labeled an estimate, never payment.
+The captured generation MUST include the verified mapping from a source's stable
+management model identity through the verified source/model binding. A pinned
+publication's execution ID may predate credential or availability revisions;
+those revisions MUST NOT detach an unchanged source/model from its current price. Equal names are not
+mapping evidence; conflicting mappings leave execution pricing unknown.
+When an ordinary billing quote lacks known input/output rates, an explicitly
+configured source-specific API-equivalent quote with those rates MAY supply the
+recorded estimate instead. Its valuation kind MUST remain API-equivalent. A usable
+verified billing quote takes precedence. Missing cache rates or usage still produce
+an explicit partial/unknown amount; reference pricing cannot fabricate usage.
A frozen publication cannot revive invalid run tokens, expired deadlines, cancelled
runs, or revoked source/Key access; current Plan delegation policy governs new
Start/Continue without automatically cancelling accepted work.
@@ -103,6 +113,20 @@ Start/Continue without automatically cancelling accepted work.
- **THEN** they MUST share the admitted price generation but freeze their own
applicable time rules; neither uses a newly published generation.
+#### Scenario: A custom model has distinct management and execution identities
+
+- **WHEN** a user configures prices for a custom model through its stable source binding
+- **THEN** new requests use the exact generation-bound execution mapping, while
+ different suppliers, changed source/model bindings, currencies and valuation kinds cannot
+ inherit the quote. The frozen evidence retains the executed model identity.
+
+#### Scenario: A subscription has a reference price but no billing quote
+
+- **WHEN** an exact source has configured API-equivalent input/output rates and
+ ordinary billing rates are unavailable
+- **THEN** new recorded amounts use the frozen API-equivalent estimate with that
+ label and actual coverage; edits affect future requests without repricing old records.
+
### Requirement: Management reports safe current source and price facts
The model-management snapshot MUST return trusted connection identity, billing
diff --git a/issue-spec/specs/session-history/spec.md b/issue-spec/specs/session-history/spec.md
index 96b82d9f..9a765b3b 100644
--- a/issue-spec/specs/session-history/spec.md
+++ b/issue-spec/specs/session-history/spec.md
@@ -494,7 +494,7 @@ Explicit causes override legacy hints. UserMessage displays New message. History
The view SHALL disclose that client background messages can satisfy the new-message rule, so continuity does not prove human authorship. Aliases, tools and timing SHALL NOT establish native provenance. Issue #185 separately tracks shared-history background/subagent isolation and active-turn conflicts; this repair does not infer subdialog identity or claim isolation is fixed. The legend states that a turn keeps its model to preserve cache and new messages or rebuilt context trigger fresh judgment.
-The opening request supplies stable display identity before completion. Late assessments and valuations update that turn. 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.
+The 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.
@@ -504,6 +504,27 @@ Reads retain shared authorization, a 500 ms storage deadline, and explicit retry
- **THEN** the remaining frozen page is delivered first, followed by the updated
earlier turn once; reconnect cannot duplicate its unchanged projection.
+#### Scenario: Completion absorbs a provisional request row
+
+- **WHEN** a later completed turn retains its opening-request identity and includes
+ a request previously displayed as a provisional row
+- **THEN** the live view removes that provisional row, preserves selection on the
+ completed turn, and shows each request and Agent turn once without a failed read.
+
+#### Scenario: Focus survives a provisional turn's completion
+
+- **WHEN** the focused overview mark or lane button belongs to a provisional turn
+ absorbed into a completed turn
+- **THEN** actual keyboard focus moves to the completed turn's corresponding control,
+ with selection and visible keyboard focus retained.
+- **AND** completion leaves focus unchanged when it is outside the absorbed controls.
+
+#### Scenario: Some model amounts are known
+
+- **WHEN** a model has known recorded amounts and another request has unknown value
+- **THEN** the card shows the known subtotal with an unknown-part disclosure,
+ preserving currency and valuation kind; an entirely unknown model stays unknown.
+
#### Scenario: Fresh decision on continuing history
- **WHEN** an old turn without an opening-cause field has a fresh opening decision recording ContextHoldApplied or ContextHoldInvalidated