VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 6)
5afd2f7 verified
Raw History Blame Contribute Delete
23.3 kB
import {arrangementCounts} from './arrangements.ts';
import {ReviewLanes} from './ReviewLanes.tsx';
import {MotionTimelines} from './MotionTimelines.tsx';
import {QuestionPicker,ScriptReviewPanel} from './ScriptReview.tsx';
import type {ReviewEvent,ReviewQuestion} from './contract.ts';
import {explanation} from './text.ts';
import { useEffect, useMemo, useRef, useState } from 'react';
import type { MetricUnits, DiscardGroup, Intent, SegmentView, Actor, RenderMedia } from './contract.ts';
import {metric} from './format.ts';
import { animate, ReviewClock, seekFromInput } from './clock.ts';
import { Scene } from './Scene.tsx';
import {NotesPanel} from './Notes.tsx';
import {GenerationRows} from './GenerationRows.tsx';
import {OmittedObservers} from './OmittedObservers.tsx';
import {MediaPanel} from './Media.tsx';
import { segmentHash, parseRoute } from './route.ts';
import { actorStyle, INTENT_LABELS, KIND_LABELS, shapePath, STATE_LABELS, STATUS_LABELS } from './visual.ts';
function SymbolIcon({actor}: {actor: Actor}) {
const {color, shape} = actorStyle(actor);
return <svg width="18" height="18" viewBox="-1.4 -1.4 2.8 2.8" aria-hidden="true"><path d={shapePath(shape)} fill={color} /></svg>;
}
export function Controls({clock}: {clock: ReviewClock}) {
const range = useRef<HTMLInputElement>(null), display = useRef<HTMLOutputElement>(null), play = useRef<HTMLButtonElement>(null);
useEffect(() => clock.subscribe(({time, playing}) => {
if (range.current) range.current.value = String(time);
if (display.current) {display.current.value = `${time.toFixed(1)} / ${clock.end.toFixed(1)} 秒`; display.current.dataset.time = String(time);}
if (play.current) {play.current.textContent = playing ? '暂停' : '播放'; play.current.setAttribute('aria-label', playing ? '暂停' : '播放');}
}), [clock]);
const step = (seconds: number) => {clock.setPlaying(false); clock.step(seconds);};
return <div className="controls"><div className="control-buttons"><button onClick={() => clock.frame(-1)} title="前一控制帧">|‹</button><button onClick={() => step(-1)}>−1 秒</button>
<button id="play" className="primary" ref={play} onClick={() => clock.setPlaying(!clock.snapshot().playing)}>播放</button><button onClick={() => step(1)}>+1 秒</button><button onClick={() => clock.frame(1)} title="后一控制帧">›|</button>
<label>倍速<select id="speed" defaultValue="1" onChange={e => clock.setSpeed(Number(e.target.value))}><option value="1">1×</option><option value="4">4×</option><option value="10">10×</option></select></label>
<output ref={display} id="time-display" /></div><input ref={range} id="time-slider" type="range" min={clock.start} max={clock.end} data-clock-start={clock.start} data-clock-end={clock.end} step="0.001" defaultValue={clock.snapshot().time} aria-label="当前时刻" onChange={e => seekFromInput(clock, e.currentTarget)} /></div>;
}
function Timeline({view, clock, visible, onRange,highlight}: {highlight?:[number,number]|null;view: SegmentView; clock: ReviewClock; visible: Set<string>; onRange: (span: [number, number]) => void}) {
const cursor = useRef<HTMLDivElement>(null), span = clock.end - clock.start;
const selecting = useRef<{x: number; rect: DOMRect; start: number} | null>(null), suppressClick = useRef(false);
const [range, setRange] = useState<[number, number] | null>(null);
useEffect(() => clock.subscribe(({time}) => {if (cursor.current) cursor.current.style.left = `${(time - clock.start) / span * 100}%`;}), [clock, span]);
const seek = (event: React.MouseEvent<HTMLDivElement>) => {
if (suppressClick.current) {suppressClick.current = false; return;}
const rect = event.currentTarget.getBoundingClientRect();
if (!Number.isFinite(rect.width) || rect.width <= 0) return;
const time = clock.start + (event.clientX - rect.left) / rect.width * span;
if (!Number.isFinite(time)) return;
clock.setPlaying(false); clock.seek(time);
};
type Row = {id: string; label: string; actor?: Actor; owner?: string};
const rows: Row[] = view.actors.flatMap(a => [
{id: a.id, label: a.id, actor: a},
]);
const colorBands = (ids: string[]) => {
if (!ids.length) return '#e9eef2';
const colors = ids.map(id => actorStyle(view.actors.find(a => a.id === id)!).color);
return `linear-gradient(180deg, ${colors.map((color, i) => `${color} ${i / colors.length * 100}% ${(i + 1) / colors.length * 100}%`).join(',')})`;
};
const place = (start: number, end: number) => ({left: `${(start - clock.start) / span * 100}%`, width: `${(end - start) / span * 100}%`});
return <section className="timeline-panel"><div className="timeline-heading"><strong>状态与观察时间轴</strong><details className="timeline-legend"><summary aria-label="时间轴图例">?</summary><div className="state-key">{Object.entries(STATE_LABELS).filter(([key]) => !['unclassified', 'uncovered'].includes(key)).map(([key, label]) => <span key={key}><i className={'state-swatch state-' + key} />{label}</span>)}<span data-timeline-symbol="discard"><b>×</b>丢弃时刻</span></div></details></div>
<div className="timeline-grid"><div className="timeline-names">{rows.map(row => <div key={row.id} title={row.owner || row.label} className={row.actor && !visible.has(row.actor.id) ? 'hidden-actor' : row.actor ? '' : 'observation-row-name'}>{row.actor && <SymbolIcon actor={row.actor} />}<span>{row.label}</span></div>)}</div>
<div className="timeline-tracks"><div ref={cursor} className="timeline-cursor" />
{rows.map(row => <div key={row.id} className={'timeline-track ' + (row.actor && !visible.has(row.actor.id) ? 'hidden-actor' : '')} data-timeline-actor={row.actor?.id} role="slider" aria-label={`${row.owner || row.label} ${row.label} 时间轴`} aria-valuemin={clock.start} aria-valuemax={clock.end} tabIndex={0}
onClick={seek}
onPointerDown={e => {const rect = e.currentTarget.getBoundingClientRect(); if (rect.width <= 0) return; clock.setPlaying(false); selecting.current = {x: e.clientX, rect, start: clock.start + Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)) * span}; e.currentTarget.setPointerCapture(e.pointerId);}}
onPointerMove={e => {const start = selecting.current; if (!start || Math.abs(e.clientX - start.x) < 3) return; const end = clock.start + Math.max(0, Math.min(1, (e.clientX - start.rect.left) / start.rect.width)) * span; setRange([Math.min(start.start, end), Math.max(start.start, end)]);}}
onPointerUp={e => {const start = selecting.current; selecting.current = null; if (!start || Math.abs(e.clientX - start.x) < 3) return; const end = clock.start + Math.max(0, Math.min(1, (e.clientX - start.rect.left) / start.rect.width)) * span; const selected: [number, number] = [Math.min(start.start, end), Math.max(start.start, end)]; suppressClick.current = true; setRange(selected); onRange(selected);}}
onPointerCancel={() => {selecting.current = null;}}
onKeyDown={e => {if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {e.preventDefault(); clock.setPlaying(false); clock.step(e.key === 'ArrowRight' ? 1 : -1);}}}>
{row.actor && view.states[row.actor.id].map((state, i) => <div key={i} data-state={state.state} data-forced={state.forced === null ? undefined : String(state.forced)} data-waiting-for={state.waiting_for.join(',')} className={'state-block state-' + state.state + (state.forced === true ? ' state-forced' : '')} style={{...place(state.start_s, state.end_s), '--actor-color': actorStyle(row.actor!).color} as React.CSSProperties} title={`${STATE_LABELS[state.state]} · ${state.start_s.toFixed(2)}–${state.end_s.toFixed(2)} 秒\n${explanation(state.reason)}${state.waiting_for.length ? '\n在等:' + state.waiting_for.join('、') : ''}`} />)}
{row.actor && view.generation.events.filter(e => e.actor_id === row.actor!.id && e.kind === 'retargeting').map((e, i) => <span key={i} className="timeline-retarget state-retargeting" data-generation-event="retargeting" data-event-time={e.time_s} style={{left: `${(e.time_s - clock.start) / span * 100}%`}} title={`${e.time_s.toFixed(2)} 秒 · 换目标 · ${e.original_target?.stop_id} → ${e.new_target?.stop_id}`}>↻</span>)}
{row.actor && view.generation.events.filter(d => d.actor_id === row.actor!.id && (d.kind === 'discard' || d.kind === 'proposal_failure')).map((d, i) => <span key={i} className={'timeline-discard' + (d.kind === 'proposal_failure' ? ' timeline-proposal-failure' : '')} data-rejection-kind={d.kind} data-discard-class={d.discard_class || undefined} data-event-time={d.time_s} style={{left: `${(d.time_s - clock.start) / span * 100}%`}} title={`${d.time_s.toFixed(1)} 秒 · ${d.kind === 'proposal_failure' ? '提案失败' : '丢弃'} · ${d.discard_class ? d.discard_class + ' 类 · ' : ''}${explanation(d.reason)}`}>{d.kind === 'proposal_failure' ? '◇' : '×'}</span>)}
</div>)}
{highlight&&<div className="timeline-selection question-selection" data-question-span={highlight.join(',')} style={{left:`${(highlight[0]-clock.start)/span*100}%`,width:`${(highlight[1]-highlight[0])/span*100}%`}}/>}
{range && <div className="timeline-selection" data-selected-span={range.join(',')} style={{left: `${(range[0] - clock.start) / span * 100}%`, width: `${(range[1] - range[0]) / span * 100}%`}} />}
<div className="timeline-ticks">{Array.from({length: 7}, (_, i) => <span key={i} style={{left: `${i / 6 * 100}%`}}>{(clock.start + i / 6 * span).toFixed(0)}s</span>)}</div>
</div>
</div></section>;
}
function IntentRows({actorId, rows, groups, clock, units}: {units: MetricUnits; actorId: string; rows: Intent[]; groups: DiscardGroup[]; clock: ReviewClock}) {
const parent = useRef<HTMLDivElement>(null);
useEffect(() => clock.subscribe(({time}) => {
parent.current?.querySelectorAll<HTMLElement>('[data-start]').forEach(node => {
const active = time >= Number(node.dataset.start) && time < Number(node.dataset.end);
node.classList.toggle('current-intent', active);
});
}), [clock]);
const renderRow = (r: Intent, i: number) => <button key={i} data-start={r.start_s} data-end={r.end_s} data-status={r.status} className={'intent-row intent-' + r.status} onClick={() => {clock.setPlaying(false); clock.seek(r.start_s);}} title={explanation(r.discard_reason || r.reason)}>
<span className="intent-top"><strong>{r.intent_index} · {INTENT_LABELS[r.kind] || r.kind}</strong><span>{STATUS_LABELS[r.status]}{r.discard_class ? ' ' + r.discard_class + ' 类' : ''}</span></span>
<span>{r.start_s.toFixed(1)}–{r.end_s.toFixed(1)} 秒 · {r.target?.stop_id || r.target?.id || r.target?.region_id || '原地'}</span>
{r.planned_duration_s !== undefined && <small data-intent-duration={r.intent_index}>原抽值 {metric(r.requested_duration_s, 'requested_duration_s', units)} · 接受 {metric(r.planned_duration_s, 'planned_duration_s', units)}{r.requested_shortfall_s === undefined ? '' : ' · 差额 ' + metric(r.requested_shortfall_s, 'requested_shortfall_s', units)}{r.duration_adjustment && ' · ' + ({control_quantization: '控制时钟量化', pause_budget: '停顿预算', activity_end: '活动结束截断'}[r.duration_adjustment])}</small>}
{r.discard_reason && <small>{explanation(r.discard_reason)}</small>}
</button>;
const byStart = new Map(groups.map(g => [g.row_indices[0], g])), folded = new Set(groups.flatMap(g => g.row_indices));
return <div className="intent-column" ref={parent} data-intent-actor={actorId}>{rows.map((r, i) => {
const group = byStart.get(i);
if (group) return <details className="discard-run" key={i} data-discard-run={group.count}><summary onClick={() => {clock.setPlaying(false); clock.seek(group.start_s);}}>
<strong>连续丢弃 {group.count} 条</strong><span>{group.start_s.toFixed(1)}–{group.end_s.toFixed(1)} 秒</span>
<div className="group-reasons">{Object.entries(group.reason_counts).map(([reason, count]) => <p key={reason}><b>{count}×</b> {explanation(reason)}</p>)}</div><small>展开逐条查看</small>
</summary><div className="discard-run-rows">{group.row_indices.map(index => renderRow(rows[index], index))}</div></details>;
return folded.has(i) ? null : renderRow(r, i);
})}</div>;
}
export function Review({view, media, mediaError, initialTime, initialActors, onBasemapReady}: {view: SegmentView; media: RenderMedia | null; mediaError: string; initialTime: number; initialActors: string[] | null; onBasemapReady?: () => void}) {
const clock = useMemo(() => new ReviewClock(view.segment.span_s, view.segment.control_hz), [view]);
const [visible, setVisible] = useState(() => new Set(initialActors === null ? view.actors.map(a => a.id) : initialActors.filter(id => view.actors.some(a => a.id === id))));
const [details, setDetails] = useState<'intents' | 'construction'>('intents');
const [intentActor, setIntentActor] = useState(view.actors[0].id);
const [selectedEvent,setSelectedEvent]=useState<ReviewEvent|null>(null),[question,setQuestion]=useState<ReviewQuestion|null>(()=>view.review?.questions.find(q=>q.id===new URLSearchParams(location.hash.split('?')[1]).get('q'))||null);
const questionRef=useRef(question);questionRef.current=question;
const focus=selectedEvent || (question ? {entity_ids:question.entity_ids,span_s:question.span_s,regions_uv:[]} : null);
const selectEvent=(event:ReviewEvent|null)=>{questionRef.current=null;setSelectedEvent(event);setQuestion(null);if(event?.span_s){clock.setPlaying(false);clock.seek(event.span_s[0]);}};
const selectQuestion=(q:ReviewQuestion|null)=>{questionRef.current=q;setQuestion(q);setSelectedEvent(null);if(q?.span_s){clock.setPlaying(false);clock.seek(q.span_s[0]);}};
const subscribeTime=useMemo(()=>(listener:(time:number)=>void)=>clock.subscribe(({time})=>listener(time)),[clock]);
const [motionRange, setMotionRange] = useState<[number, number] | null>(null);
const [noteSpan, setNoteSpan] = useState<[number, number]>(view.segment.span_s);
const visibleRef = useRef(visible), link = useRef<HTMLAnchorElement>(null);
useEffect(() => {visibleRef.current = visible; clock.seek(clock.snapshot().time);}, [visible, clock]);
useEffect(() => {if (visible.size === 1) setIntentActor(Array.from(visible)[0]);}, [visible]);
useEffect(() => {
clock.seek(initialTime);
const stop = animate(clock);
let previousURLTime = -Infinity;
const unsubscribe = clock.subscribe(({time, playing}) => {
const hash = segmentHash(view.segment.id, time, Array.from(visibleRef.current))+(questionRef.current?'&q='+encodeURIComponent(questionRef.current.id):'');
if (link.current) link.current.href = hash;
// Browser display state, not script state. Keep updates cheap at 10×.
if (!playing || Math.abs(time - previousURLTime) >= 1) {
history.replaceState(null, '', hash); previousURLTime = time;
}
});
const hashChange = () => {
const route = parseRoute(location.hash);
if (route.page === 'segment' && route.id === view.segment.id) {
clock.setPlaying(false); clock.seek(route.time);
if (route.actors !== null) setVisible(new Set(route.actors.filter(id => view.actors.some(a => a.id === id))));
}
};
window.addEventListener('hashchange', hashChange);
return () => {stop(); unsubscribe(); window.removeEventListener('hashchange', hashChange);};
}, [clock, view, initialTime]);
function toggle(id: string) {setVisible(old => {const next = new Set(old); if (next.has(id)) next.delete(id); else next.add(id); return next;});}
return <article className="review-page" data-view-schema={view.schema} data-segment-id={view.segment.id}>
<div className="review-title"><a href="#/segments" className="back-link">‹ 段列表</a><div><h1>{view.segment.world_id} <span>{view.segment.duration_s.toFixed(0)} 秒 · {view.actors.length} 主体</span></h1><p className="segment-id">{view.segment.id}</p></div><a ref={link} className="share-link">此刻地址 ↗</a></div>
{view.review&&<><div className="script-review-status"><strong>{view.review.batch} · 渲染前</strong><span>{(() => {const c=arrangementCounts(view.review);return c ? `安排 ${c.total} · 生效 ${c.effective} · 偏了 ${c.deviated} · 没生效 ${c.ineffective}` : '安排:生成器未输出';})()}</span><details><summary>原始数字</summary><span>计划安排 {view.review.planned.length} 类 · {view.review.actual_arrangements ? `生成器安排 ${view.review.actual_arrangements.length} 条` : '实际安排:生成器未输出'} · 轨迹情形 {view.review.situations.length} 段 · {view.review.body_yaw || (Object.values(view.tracks).some(t=>t.yaw_rad) ? '机身朝向:生成器(渲染用)' : '机身朝向:无数据')}</span></details></div><QuestionPicker review={view.review} selected={question?.id||null} onSelect={selectQuestion}/></>}
<details className="provenance"><summary>剧本 {view.segment.script_id.slice(0, 12)} · 指纹已核 · 生成器 {view.provenance.generator_version.split('+')[0]}</summary><dl><dt>剧本 ID</dt><dd>{view.segment.script_id}</dd><dt>产物 SHA-256</dt><dd>{view.provenance.artifact_sha256}</dd><dt>能力表指纹</dt><dd>{view.provenance.capability_fingerprint||"无数据(语义指纹)"}</dd><dt>生成器版本</dt><dd>{view.provenance.generator_version}</dd><dt>数据构建器</dt><dd>{view.builder_version}</dd><dt>位置偏差上界</dt><dd>{(view.tracks_max_error_m * 1000).toFixed(4)} mm</dd></dl></details>
<div className="actor-legend">{view.actors.map(a => <div key={a.id} className={'legend-item ' + (visible.has(a.id) ? '' : 'hidden-actor')}><button aria-pressed={visible.has(a.id)} className="actor-toggle" data-toggle-actor={a.id} onClick={() => toggle(a.id)}><SymbolIcon actor={a} /><strong>{a.id}</strong><span>{KIND_LABELS[a.kind] || a.kind}{a.virtual ? ' · 虚线' : ''}</span></button><button className="solo" data-solo-actor={a.id} onClick={() => setVisible(new Set([a.id]))} title="只看这一个主体">仅此</button></div>)}<button onClick={() => setVisible(new Set(view.actors.map(a => a.id)))}>全显</button></div>
<details className="review-raw"><summary>原始数字与生成记录</summary><OmittedObservers value={view.generation.observer_generation} />
</details>
<div className="review-body"><div className="review-left"><div className={media || view.media_ref ? 'media-and-map' : ''}><Scene view={view} focus={focus} clock={clock} visible={visible} onBasemapReady={onBasemapReady} />{media ? <MediaPanel media={media} segmentId={view.segment.id} clock={clock} /> : view.media_ref && <div className="media-panel"><h2>渲染录像</h2>{view.media_ref.routes.map(r=><section key={r.observer_id} className="media-route"><h3>{r.observer_id}</h3><div className="media-picture"><p role={mediaError ? 'alert' : 'status'}>{mediaError || '录像加载中'}</p></div></section>)}</div>}</div><Controls clock={clock} /><MotionTimelines view={view} clock={clock} visible={visible} range={motionRange} setRange={setMotionRange} onRange={setNoteSpan} highlight={question?.span_s} />
<details className="review-timelines" open><summary>时间轴:状态、安排与情形</summary><Timeline view={view} clock={clock} visible={visible} onRange={setNoteSpan} highlight={question?.span_s} />
{view.review&&<ReviewLanes rows={[...view.actors.map(a=>({id:'arrangement-'+a.id,label:a.id+' · 安排',events:[...view.review!.planned,...(view.review!.actual_arrangements||[])].filter(e=>e.entity_ids.includes(a.id)),empty:'实际未输出 · 计划未绑定'})),{id:'situations',label:'情形',events:view.review.situations,empty:'无数据'}]} span={view.segment.span_s} subscribe={subscribeTime} onSeek={t=>{clock.setPlaying(false);clock.seek(t);}} onSelect={selectEvent} selected={selectedEvent?.id} highlights={question?.span_s?[question.span_s]:[]}/>}
</details>
<p className="note-range">拖动任一时间轴选意见区间 · 当前 {noteSpan[0].toFixed(2)}–{noteSpan[1].toFixed(2)} 秒</p>
<NotesPanel scope={{segment_id: view.segment.id}} fingerprints={{[view.segment.id]: view.provenance.artifact_sha256}} span={noteSpan} actors={Array.from(visible)} /></div>
<aside className="review-aside"><ScriptReviewPanel view={view} review={view.review} selected={selectedEvent} question={question} onSelect={selectEvent} onSeek={t=>{clock.setPlaying(false);clock.seek(t);}}/><details><summary>原始意图与构造</summary><div className="detail-tabs"><button className={details === 'intents' ? 'selected' : ''} onClick={() => setDetails('intents')}>意图串</button><button className={details === 'construction' ? 'selected' : ''} onClick={() => setDetails('construction')}>构造与提醒</button></div>
{details === 'intents' ? <div className="intent-panel"><label className="intent-selector">查看主体<select id="intent-actor" value={intentActor} onChange={e => setIntentActor(e.target.value)}>{view.actors.map(a => <option key={a.id} value={a.id}>{a.id} · {KIND_LABELS[a.kind] || a.kind}</option>)}</select></label><IntentRows units={view.metric_units} key={intentActor} actorId={intentActor} rows={view.intents[intentActor]} groups={view.construction.discard_groups.filter(g => g.actor_id === intentActor)} clock={clock} /><GenerationRows units={view.metric_units} records={view.generation} actorId={intentActor} clock={clock} /></div> : <div className="construction"><h2>构造记录</h2><p>重试 {view.construction.retries} 次</p><h3>{view.generation.method === 'token_passing_event_loop' ? '稳定输出顺序(不是规划优先级)' : '旧版优先级'}</h3><ol>{view.construction.priority_order.map(id => <li key={id}>{id}</li>)}</ol><details><summary>令牌事件 · {view.generation.event_counts.token ?? 0} 条</summary>{view.generation.events.filter(e => e.token).sort((a, b) => a.token!.sequence - b.token!.sequence).map(e => <button className="generation-record" key={e.token!.sequence} data-token-sequence={e.token!.sequence} onClick={() => {clock.setPlaying(false); clock.seek(e.time_s);}}>#{e.token!.sequence} · {e.actor_id} · {e.time_s.toFixed(2)} 秒 · {e.token!.phase === 'moving_token' ? '移动主体令牌' : '固定活动上的观察者'}</button>)}</details><h3>丢弃原因</h3>{Object.entries(view.construction.discard_reason_counts).map(([reason, count]) => <p className="reason" key={reason}><b>{count}</b> {explanation(reason)}</p>)}</div>}
<div className="warnings"><h2>提醒 · {view.warnings.length}</h2>{view.warnings.map((w, i) => <p key={i} className={['UNCOVERED', 'UNCLASSIFIED_WAIT', 'TURN_COUNT_MISMATCH', 'STATION_DISCARDED'].includes(w.code) ? 'warning-strong' : ''}>{w.actor_id && <strong>{w.actor_id}:</strong>}{explanation(w.message)}</p>)}</div>
</details><p className="future-data">{view.review ? [Object.values(view.intents||{}).some((x:any)=>x?.length)?"":"原意图:无数据。", (view.warnings||[]).some((w:any)=>w.code==="SOURCE_BODY_YAW_MISSING")?"机身朝向:无数据。":""].join("") : "事实、情形对照:本段还没有。"}{!view.media_ref && !media && '录像:本段还没有。'}</p>
</aside></div>
</article>;
}