diff --git a/scripts/runtime-files.mjs b/scripts/runtime-files.mjs
index 3051a0d..3bb98bc 100644
--- a/scripts/runtime-files.mjs
+++ b/scripts/runtime-files.mjs
@@ -33,6 +33,7 @@ const groups = {
"app.mjs",
"core.mjs",
"data.mjs",
+ "feedback-prediction-ui.mjs",
"feedback-story-ui.mjs",
"feedback-story.css",
"feedback-story.mjs",
diff --git a/src/experiments/recommendation/app.mjs b/src/experiments/recommendation/app.mjs
index 7050d6c..861a8e4 100644
--- a/src/experiments/recommendation/app.mjs
+++ b/src/experiments/recommendation/app.mjs
@@ -1,15 +1,20 @@
-import {POSTS,TOPICS,PRESETS,INITIAL_PROFILE} from './data.mjs?v=cat-feedback-v1';
-import {rankPosts,metrics,feedback,challenge,experiment} from './core.mjs?v=cat-feedback-v1';
-import {captureFeedback} from './feedback-story.mjs?v=cat-feedback-v1';
-import {mountFeedbackStory} from './feedback-story-ui.mjs?v=cat-feedback-v1';
-import {mountSeatLesson} from './seat-lesson-ui.mjs?v=cat-feedback-v1';
-import {renderRecommendationCard} from './recommendation-cards.mjs?v=cat-feedback-v1';
+import {POSTS,TOPICS,PRESETS,INITIAL_PROFILE} from './data.mjs?v=feedback-prediction-v1';
+import {rankPosts,metrics,feedback,challenge,experiment} from './core.mjs?v=feedback-prediction-v1';
+import {captureFeedback} from './feedback-story.mjs?v=feedback-prediction-v1';
+import {mountFeedbackStory} from './feedback-story-ui.mjs?v=feedback-prediction-v1';
+import {mountSeatLesson} from './seat-lesson-ui.mjs?v=feedback-prediction-v1';
+import {renderRecommendationCard} from './recommendation-cards.mjs?v=feedback-prediction-v1';
+import {mountFeedbackPrediction} from './feedback-prediction-ui.mjs?v=feedback-prediction-v1';
const $=id=>document.getElementById(id);
const feedbackStory=mountFeedbackStory({document});
let weights={...PRESETS.click.weights},baseline={...PRESETS.click.weights},profile={...INITIAL_PROFILE};
const seatLesson=mountSeatLesson({document,getInputs:()=>({posts:POSTS,weights,profile})});
let completed=null,runCount=0,toastTimer;
+const feedbackPrediction=mountFeedbackPrediction({document,getInputs:()=>({posts:POSTS,weights,profile}),
+ applyFeedback:evidence=>applyPostFeedback(evidence.action.post.id,evidence.action.direction,{evidence,guided:true}),
+ returnToCard:({postId,direction})=>focusFeedback(postId,direction),
+ reducedMotion:()=>matchMedia('(prefers-reduced-motion:reduce)').matches});
const keyOrder=['click','diversity','newcomer'];
const same=(a,b)=>keyOrder.every(k=>a[k]===b[k]);
const strategy=w=>Object.values(PRESETS).find(p=>same(p.weights,w))?.name||'你的自定义规则';
@@ -36,7 +41,7 @@ function render(){
$('challenge-checks').innerHTML=[[goal.click,'预测点击率 ≥ 40%'],[goal.diversity,'至少 4 种主题'],[goal.newcomer,'至少 2 个新人席位']].map(([ok,label])=>`
${ok?'✓':''}${label}${ok?',已达成':',未达成'}`).join('');
$('challenge-status').textContent=goal.won?'挑战达成!再跑一轮,看看代价。':'还差一点,试着调调看。';$('challenge-status').classList.toggle('won',goal.won);
$('taste-bars').innerHTML=Object.entries(TOPICS).map(([key,topic])=>`${topic.short} ${Math.round(profile[key]*100)} `).join('');
- $('baseline-caption').textContent=`对照组:${strategy(baseline)}`;renderComparison();feedbackStory.sync(weights,profile);seatLesson.sync();return m;
+ $('baseline-caption').textContent=`对照组:${strategy(baseline)}`;renderComparison();feedbackStory.sync(weights,profile);seatLesson.sync();feedbackPrediction.sync();return m;
}
function renderComparison(){
@@ -55,18 +60,25 @@ function renderComparison(){
function changeWeights(next){weights={...next};const m=render();announce(`首页已更新:${m.topics} 种主题,${m.newcomers} 个新人席位,预测点击率 ${pct(m.ctr)}%。`);}
document.querySelectorAll('[data-preset]').forEach(button=>button.addEventListener('click',()=>changeWeights(PRESETS[button.dataset.preset].weights)));
for(const key of keyOrder) $(key).addEventListener('input',event=>changeWeights({...weights,[key]:Number(event.target.value)}));
-$('feed').addEventListener('click',event=>{
- const button=event.target.closest('[data-feedback]');if(!button)return;
- const post=POSTS.find(p=>p.id===button.dataset.post),direction=Number(button.dataset.feedback);
- const evidence=feedbackStory.shouldRecord()?captureFeedback(POSTS,weights,profile,post.id,direction):null;
+function focusFeedback(postId,direction,slot=0){
+ const retained=[...$('feed').querySelectorAll('[data-feedback]')].find(b=>b.dataset.post===postId&&Number(b.dataset.feedback)===direction);
+ (retained||$('feed').children[Math.max(0,slot)]?.querySelector(`[data-feedback="${direction}"]`))?.focus({preventScroll:true});
+}
+function applyPostFeedback(postId,direction,{evidence=null,guided=false}={}){
+ const post=POSTS.find(p=>p.id===postId),recording=feedbackStory.shouldRecord();
+ evidence=evidence||(recording?captureFeedback(POSTS,weights,profile,post.id,direction):null);
+ const slot=[...$('feed').children].findIndex(card=>card.dataset.id===post.id);
const before=profile[post.topic];profile=feedback(profile,post.topic,direction);
const note=before===profile[post.topic]?`${TOPICS[post.topic].short}兴趣已${direction>0?'达到上限':'降到下限'}。`:`${direction>0?'多看一点':'少看一点'}${TOPICS[post.topic].short},首页已重新排序。`;
- const slot=[...$('feed').children].indexOf(button.closest('.post-card'));
- if(evidence)feedbackStory.record(evidence);
- render();$('feedback-note').textContent=note;announce(note+(evidence?' 已保留反馈前后对照,可通过首页上方链接查看。':''));toast(note);
+ if(recording&&evidence)feedbackStory.record(evidence);
+ render();$('feedback-note').textContent=note;announce(note+(recording&&evidence?' 已保留反馈前后对照,可通过首页上方链接查看。':''));toast(note);
// Reranking replaces cards; keep keyboard focus on the same action when possible.
- const retained=[...$('feed').querySelectorAll('[data-feedback]')].find(b=>b.dataset.post===post.id&&Number(b.dataset.feedback)===direction);
- (retained||$('feed').children[Math.max(0,slot)]?.querySelector(`[data-feedback="${direction}"]`))?.focus({preventScroll:true});
+ if(!guided)focusFeedback(post.id,direction,slot);
+}
+$('feed').addEventListener('click',event=>{
+ const button=event.target.closest('[data-feedback]');if(!button)return;
+ const postId=button.dataset.post,direction=Number(button.dataset.feedback);
+ if(!feedbackPrediction.request(postId,direction))applyPostFeedback(postId,direction);
});
$('run').addEventListener('click',()=>{
completed={result:experiment(POSTS,weights,baseline,profile),number:++runCount};
@@ -80,6 +92,7 @@ const emptyComparison=$('comparison-result').innerHTML;
$('reset').addEventListener('click',()=>{
weights={...PRESETS.click.weights};baseline={...PRESETS.click.weights};profile={...INITIAL_PROFILE};completed=null;runCount=0;
feedbackStory.reset();
+ feedbackPrediction.reset();
seatLesson.reset();
$('comparison-result').innerHTML=emptyComparison;$('run-number').textContent='未运行';$('feedback-note').textContent='试试卡片上的「喜欢」和「少一点」。';
$('feed').innerHTML='';render();toast('已回到实验起点');announce('全部规则、口味和实验记录已重置。');
diff --git a/src/experiments/recommendation/feedback-prediction-ui.mjs b/src/experiments/recommendation/feedback-prediction-ui.mjs
new file mode 100644
index 0000000..b63387a
--- /dev/null
+++ b/src/experiments/recommendation/feedback-prediction-ui.mjs
@@ -0,0 +1,98 @@
+import {TOPICS} from './data.mjs?v=feedback-prediction-v1';
+import {captureFeedback,recordMatches} from './feedback-story.mjs?v=feedback-prediction-v1';
+import {escapeCardText as escape,recommendationTitle as title,recommendationArt as art,recommendationCharacter as character} from './recommendation-cards.mjs?v=feedback-prediction-v1';
+
+const percent=value=>Math.round(value*100);
+const position=rank=>rank===null?'六席外':`第 ${rank} 位`;
+const answer=choice=>choice==='stays'?'仍在首页六席':'离开首页六席';
+
+// This optional layer defers an existing feedback action. It does not change the
+// scorer, profile persistence, or the separate, user-pinned feedback story.
+export function mountFeedbackPrediction({document,getInputs,applyFeedback,returnToCard=()=>{},reducedMotion=()=>false}){
+ const $=name=>document.getElementById(`feedback-prediction-${name}`);
+ let enabled=false,pending=null,choice=null,completed=null;
+ const status=text=>{$('status').textContent=text;};
+ function moveTo(name){
+ $(name).focus({preventScroll:true});
+ $('panel').scrollIntoView({behavior:reducedMotion()?'instant':'smooth',block:'nearest'});
+ }
+ function hideChoices(){
+ $('choices').hidden=true;$('apply').disabled=true;
+ for(const key of ['stays','leaves'])$(key).setAttribute('aria-pressed','false');
+ }
+ function cancel(message,{restoreFocus=false}={}){
+ const action=pending?.action;pending=null;choice=null;hideChoices();
+ $('panel').hidden=true;status(message);
+ if(action&&restoreFocus)returnToCard({postId:action.post.id,direction:action.direction});
+ }
+ function pendingMatches(){
+ if(!pending)return false;
+ const {weights,profile}=getInputs();
+ return recordMatches({...pending,after:pending.before},weights,profile);
+ }
+ function sync(){
+ if(pending&&!pendingMatches())cancel('规则或口味变了,这次猜测已取消,未发送反馈。请重新选一张卡。');
+ if(completed){
+ const {weights,profile}=getInputs();
+ $('result-state').textContent=recordMatches(completed,weights,profile)
+ ?'本次反馈结果 · 规则未改'
+ :'保留上次反馈结果 · 当前口味或规则已改变';
+ }
+ }
+ function request(postId,direction){
+ if(!enabled)return false;
+ const {posts,weights,profile}=getInputs();
+ pending=captureFeedback(posts,weights,profile,postId,direction);choice=null;completed=null;
+ const {post,beforeRank}=pending.action,topic=TOPICS[post.topic],name=character(post);
+ $('card').innerHTML=`${art(post)||topic.glyph}${escape(title(post))}${name?`出镜:${escape(name)} · `:''}${escape(topic.short)} · 反馈前${position(beforeRank)}
`;
+ $('title').textContent=`点「${direction>0?'喜欢':'少一点'}」后,这张卡还会在首页吗?`;
+ $('panel').hidden=false;$('result').hidden=true;hideChoices();$('choices').hidden=false;
+ status('先猜去留,再检验;这次反馈还没发送,首页和口味都没变。');
+ moveTo('title');return true;
+ }
+ function choose(value){
+ if(!pending)return;
+ if(!pendingMatches()){sync();return;}
+ choice=value;
+ for(const key of ['stays','leaves'])$(key).setAttribute('aria-pressed',String(key===choice));
+ $('apply').disabled=false;status(`你猜「${answer(choice)}」。还没发送反馈,点「检验这次反馈」看实际结果。`);
+ }
+ function reveal(){
+ if(!pending||!choice)return;
+ if(!pendingMatches()){sync();return;}
+ const evidence=pending,guess=choice;
+ // Consume before rendering/applying: repeated clicks cannot send it twice.
+ pending=null;choice=null;hideChoices();
+ applyFeedback(evidence);completed=evidence;
+ const {action:a,before,after,effect}=evidence,topic=TOPICS[a.post.topic].short;
+ $('result').hidden=false;
+ $('verdict').textContent=`你猜:${answer(guess)}。实际:${a.afterRank===null?'离开首页六席':`仍在首页,第 ${a.afterRank} 位`}。`;
+ $('position').textContent=`${position(a.beforeRank)} → ${position(a.afterRank)}`;
+ $('interest-label').textContent=`${topic}兴趣`;
+ $('interest').textContent=`${percent(before.profile[a.post.topic])} → ${percent(after.profile[a.post.topic])}`;
+ const cause=effect==='limit'
+ ?`${topic}兴趣已到${a.direction>0?'上限':'下限'},这次没有变化,首页也没变。`
+ :effect==='unweighted'
+ ?'兴趣变了,但「点击优先」是 0,口味不参与排序,所以首页没变。'
+ :`反馈调整的是「${topic}」主题兴趣,不是屏蔽某张卡;兴趣变了,也不保证它离开首页。`;
+ $('reason').textContent=`${cause}三项规则没变。${a.afterRank===null?'这张卡仍在候选池里,没有被屏蔽。':''}`;
+ $('title').textContent='这张卡,真的离开了吗?';
+ sync();status('已发送一次反馈。你的猜测和真实结果就在下方;可继续选别的卡。');moveTo('result-state');
+ }
+ $('mode').addEventListener('click',()=>{
+ enabled=!enabled;$('mode').setAttribute('aria-pressed',String(enabled));
+ $('mode').textContent=enabled?'退出猜测模式':'先猜再反馈';
+ if(!enabled&&pending)cancel('已退出猜测模式;刚才的反馈没有发送。现在点卡片可直接反馈。',{restoreFocus:true});
+ else status(enabled?'已开启:选一张卡,点「喜欢」或「少一点」,先猜它的去留。':'已恢复直接反馈;点卡片就会更新首页。');
+ });
+ $('stays').addEventListener('click',()=>choose('stays'));
+ $('leaves').addEventListener('click',()=>choose('leaves'));
+ $('apply').addEventListener('click',reveal);
+ $('cancel').addEventListener('click',()=>cancel('已取消,这次没有发送反馈;首页和口味没变。',{restoreFocus:true}));
+ function reset(){
+ enabled=false;pending=null;choice=null;completed=null;hideChoices();
+ $('panel').hidden=true;$('result').hidden=true;$('mode').setAttribute('aria-pressed','false');$('mode').textContent='先猜再反馈';
+ status('可选小挑战:先开启,再点一张卡的反馈。不开启也能照常玩。');
+ }
+ reset();return {request,sync,reset};
+}
diff --git a/src/experiments/recommendation/feedback-story-ui.mjs b/src/experiments/recommendation/feedback-story-ui.mjs
index b57a2dc..713e7cd 100644
--- a/src/experiments/recommendation/feedback-story-ui.mjs
+++ b/src/experiments/recommendation/feedback-story-ui.mjs
@@ -1,6 +1,6 @@
-import {TOPICS} from './data.mjs?v=cat-feedback-v1';
-import {recordMatches} from './feedback-story.mjs?v=cat-feedback-v1';
-import {escapeCardText as escape,recommendationTitle as title,recommendationArt as art,recommendationCharacter as character} from './recommendation-cards.mjs?v=cat-feedback-v1';
+import {TOPICS} from './data.mjs?v=feedback-prediction-v1';
+import {recordMatches} from './feedback-story.mjs?v=feedback-prediction-v1';
+import {escapeCardText as escape,recommendationTitle as title,recommendationArt as art,recommendationCharacter as character} from './recommendation-cards.mjs?v=feedback-prediction-v1';
const interest=value=>Math.round(value*100);
const cast=post=>{const name=character(post);return name?`出镜:${escape(name)}`:'';};
diff --git a/src/experiments/recommendation/feedback-story.css b/src/experiments/recommendation/feedback-story.css
index bd8b2ef..63ab291 100644
--- a/src/experiments/recommendation/feedback-story.css
+++ b/src/experiments/recommendation/feedback-story.css
@@ -2,6 +2,29 @@
.feedback-entry-note p{margin:0;color:var(--muted)}
.feedback-entry-note strong{display:block;color:var(--ink);font-size:13px}
.feedback-entry-note a{color:var(--ink);font-weight:650;text-underline-offset:4px;flex-shrink:0;padding:9px 0}
+.feedback-prediction{margin:0 0 18px;color:var(--ink);font-size:13px;line-height:1.65}
+.feedback-prediction [hidden]{display:none}
+.feedback-prediction-start{display:flex;align-items:center;gap:12px}
+.feedback-prediction-start p{margin:0;color:var(--muted);font-size:12px}
+.feedback-prediction button{min-height:44px;border:1px solid var(--line);border-radius:10px;padding:9px 13px;background:var(--surface);color:var(--ink);font:inherit;font-weight:600;cursor:pointer}
+.feedback-prediction-start button{flex-shrink:0}
+.feedback-prediction button[aria-pressed=true],.feedback-prediction .feedback-prediction-primary{background:var(--ink);color:var(--surface)}
+.feedback-prediction button:disabled{opacity:.45;cursor:default}
+.feedback-prediction button:focus-visible,.feedback-prediction h3:focus-visible,.feedback-prediction h4:focus-visible{outline:3px solid var(--ink);outline-offset:3px}
+.feedback-prediction-panel{padding:18px;margin-top:12px;border:1px solid var(--line);border-radius:14px;background:var(--surface);scroll-margin:16px}
+.feedback-prediction h3{font-size:17px;line-height:1.5;margin:0 0 12px;letter-spacing:-.025em}
+.feedback-prediction h4{font-size:12px;font-weight:600;color:var(--muted);margin:15px 0 6px}
+.feedback-prediction-card{display:flex;align-items:center;gap:12px;margin-bottom:14px}
+.feedback-prediction-card>div{min-width:0}.feedback-prediction-card strong{display:block;font-size:14px;overflow-wrap:anywhere}
+.feedback-prediction-card>div>span{display:block;font-size:11px;color:var(--muted)}
+.feedback-prediction-art{width:52px;height:58px;flex:0 0 52px;border-radius:9px;display:grid;place-items:center;background:var(--topic);color:#20241c;font-size:28px}
+.feedback-prediction-art img{width:100%;height:100%;min-height:0;object-fit:contain;image-rendering:pixelated}
+.feedback-prediction-answers{display:grid;grid-template-columns:1fr 1fr;gap:8px}
+.feedback-prediction-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px}
+.feedback-prediction-numbers{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin:12px 0;padding:12px;background:var(--soft);border-radius:10px}
+.feedback-prediction-numbers dt{font-size:11px;color:var(--muted)}.feedback-prediction-numbers dd{margin:3px 0 0;font-weight:700;font-variant-numeric:tabular-nums;font-size:16px;letter-spacing:-.035em}
+#feedback-prediction-verdict{margin:0;font-weight:600}#feedback-prediction-reason{margin:0;color:var(--muted);font-size:12px}
+@media(max-width:600px){.feedback-prediction-start{align-items:flex-start;flex-direction:column;gap:7px}.feedback-prediction-panel{padding:14px}.feedback-prediction h3{font-size:16px}.feedback-prediction-numbers{gap:8px;padding:10px}.feedback-prediction-numbers dd{font-size:14px}.feedback-prediction-answers button{padding:9px 7px}}
.feedback-story{margin-top:32px;padding:28px;border:1px solid var(--line);border-radius:20px;background:var(--surface);scroll-margin-top:20px}
.feedback-story [hidden]{display:none}
.feedback-story h2{font-size:clamp(21px,2.2vw,28px);letter-spacing:-.035em;margin:8px 0 10px}
diff --git a/src/experiments/recommendation/feedback-story.mjs b/src/experiments/recommendation/feedback-story.mjs
index 1038b96..24ff0cf 100644
--- a/src/experiments/recommendation/feedback-story.mjs
+++ b/src/experiments/recommendation/feedback-story.mjs
@@ -1,4 +1,4 @@
-import {feedback,rankPosts,scorePost,probability,metrics} from './core.mjs?v=cat-feedback-v1';
+import {feedback,rankPosts,scorePost,probability,metrics} from './core.mjs?v=feedback-prediction-v1';
function freeze(value){
if(value&&typeof value==='object'){
diff --git a/src/experiments/recommendation/recommendation-cards.mjs b/src/experiments/recommendation/recommendation-cards.mjs
index 80f45d7..b3d5910 100644
--- a/src/experiments/recommendation/recommendation-cards.mjs
+++ b/src/experiments/recommendation/recommendation-cards.mjs
@@ -1,5 +1,5 @@
-import {TOPICS} from './data.mjs?v=cat-feedback-v1';
-import {probability} from './core.mjs?v=cat-feedback-v1';
+import {TOPICS} from './data.mjs?v=feedback-prediction-v1';
+import {probability} from './core.mjs?v=feedback-prediction-v1';
// Display-only remapping. The same post IDs and original data still go to the scorer.
const studioPosts={
diff --git a/src/experiments/recommendation/recommendation.html b/src/experiments/recommendation/recommendation.html
index d9f25d5..c9eda87 100644
--- a/src/experiments/recommendation/recommendation.html
+++ b/src/experiments/recommendation/recommendation.html
@@ -5,7 +5,7 @@
-
+
算法游乐场 · 首页,交给你了
@@ -47,7 +47,23 @@
只追点击48 条候选 → 6 个席位
给首页排一次座位不只看谁入选:猜下一席,再查它赢过谁、为什么。
亲手排六席 ↓
- 点一次反馈,看懂首页为什么变默认第一张是波比。点「少一点」,猜猜这张卡还会不会留在首页。
看反馈前后对照 ↓
+ 点一次反馈,看懂首页为什么变默认第一张是波比。少看一点,不一定会让这张卡离开首页。
看反馈前后对照 ↓
+
+
可选小挑战:先开启,再点一张卡的反馈。不开启也能照常玩。
+
+
+
+
+
+
+
+
+
+
你的模拟口味试试卡片上的「喜欢」和「少一点」。
反馈只改变这一位模拟用户的兴趣,不代表真实用户行为。
diff --git a/src/experiments/recommendation/seat-lesson-ui.mjs b/src/experiments/recommendation/seat-lesson-ui.mjs
index c9ff123..933446c 100644
--- a/src/experiments/recommendation/seat-lesson-ui.mjs
+++ b/src/experiments/recommendation/seat-lesson-ui.mjs
@@ -1,7 +1,7 @@
-import {TOPICS,PRESETS} from './data.mjs?v=cat-feedback-v1';
-import {probability,scorePost} from './core.mjs?v=cat-feedback-v1';
-import {createSeatLesson,chooseSeat,nextSeat,currentRound,lessonMatches,diversityCounterfactual,carryoverComparison,seatGuessOptions} from './seat-lesson.mjs?v=cat-feedback-v1';
-import {escapeCardText as escape,recommendationTitle as title,recommendationThumbnail as art} from './recommendation-cards.mjs?v=cat-feedback-v1';
+import {TOPICS,PRESETS} from './data.mjs?v=feedback-prediction-v1';
+import {probability,scorePost} from './core.mjs?v=feedback-prediction-v1';
+import {createSeatLesson,chooseSeat,nextSeat,currentRound,lessonMatches,diversityCounterfactual,carryoverComparison,seatGuessOptions} from './seat-lesson.mjs?v=feedback-prediction-v1';
+import {escapeCardText as escape,recommendationTitle as title,recommendationThumbnail as art} from './recommendation-cards.mjs?v=feedback-prediction-v1';
const label=post=>TOPICS[post.topic]?.short||post.topic;
const number=value=>Number(value.toPrecision(12)).toString();
diff --git a/src/experiments/recommendation/seat-lesson.mjs b/src/experiments/recommendation/seat-lesson.mjs
index bed44d1..3415a05 100644
--- a/src/experiments/recommendation/seat-lesson.mjs
+++ b/src/experiments/recommendation/seat-lesson.mjs
@@ -1,4 +1,4 @@
-import {traceRanking} from './core.mjs?v=cat-feedback-v1';
+import {traceRanking} from './core.mjs?v=feedback-prediction-v1';
export function createSeatLesson(posts,weights,profile,size=6){
const snapshot=structuredClone({posts,weights,profile});
diff --git a/src/experiments/world-model/world-model.html b/src/experiments/world-model/world-model.html
index b6b7c14..876324c 100644
--- a/src/experiments/world-model/world-model.html
+++ b/src/experiments/world-model/world-model.html
@@ -4,7 +4,7 @@
-
+
算法游乐场 · 脑内预演室
diff --git a/src/experiments/world-model/world-model.mjs b/src/experiments/world-model/world-model.mjs
index 03a6d12..906e157 100644
--- a/src/experiments/world-model/world-model.mjs
+++ b/src/experiments/world-model/world-model.mjs
@@ -235,9 +235,12 @@ function animate(time,myToken){
if(lastTime===null)lastTime=time;
remainder+=Math.max(0,time-lastTime);lastTime=time;
const count=Math.floor(remainder/100);remainder-=count*100;
- if(count)session=advanceFlight(session,Math.min(count,STEPS));
- if(session.flight?.done){complete();return;}
- render();frame=requestAnimationFrame(t=>animate(t,myToken));
+ if(count){
+ session=advanceFlight(session,Math.min(count,STEPS));
+ if(session.flight?.done){complete();return;}
+ render();
+ }
+ frame=requestAnimationFrame(t=>animate(t,myToken));
}
function play(){
if(media.matches){session=advanceFlight(session,STEPS);complete();return;}
diff --git a/src/home/home.mjs b/src/home/home.mjs
index 8dfb81d..b93412e 100644
--- a/src/home/home.mjs
+++ b/src/home/home.mjs
@@ -95,6 +95,9 @@ if(!legacyRoute()){
if(ctx){
const scene=createShowcaseScene(),clock=createHeroClock(),reduced=matchMedia('(prefers-reduced-motion: reduce)');
const studioImages=new Map();
+ const observesHero='IntersectionObserver' in window;
+ // Keep the animation clock unchanged; only image requests wait for the viewport signal.
+ let heroInViewport=!observesHero;
let raf=0,epoch=0,disposed=false,lastPaint=-Infinity;
const col=i=>i%scene.map.cols,row=i=>Math.floor(i/scene.map.cols),depth=i=>col(i)+row(i);
const walls=new Set(scene.map.walls),cells=Array.from({length:scene.map.cols*scene.map.rows},(_,i)=>i).sort((a,b)=>depth(a)-depth(b));
@@ -149,28 +152,42 @@ if(!legacyRoute()){
const state=clock.read();canvas.dataset.motion=state.running?'playing':state.reduced?'reduced':'paused';
motion.disabled=state.reduced;motion.setAttribute('aria-pressed',String(state.paused));motion.innerHTML=state.reduced?'静态展示 · 已减少动态效果':state.paused?'▶ 播放动画':'Ⅱ 暂停动画';
draw(state.reduced?scene.duration-1:state.elapsed);
- if(state.running&&!disposed){const token=epoch;const tick=now=>{if(token!==epoch||disposed)return;const elapsed=clock.tick(now);if(now-lastPaint>=33){draw(elapsed);lastPaint=now;}raf=requestAnimationFrame(tick);};raf=requestAnimationFrame(tick);}
+ if(state.running&&!disposed){
+ // Prewarm during the search, before any cat needs its running pose.
+ if(heroInViewport&&!document.hidden&&!reduced.matches)loadArt('run');
+ const token=epoch;const tick=now=>{if(token!==epoch||disposed)return;const elapsed=clock.tick(now);if(now-lastPaint>=33){draw(elapsed);lastPaint=now;}raf=requestAnimationFrame(tick);};raf=requestAnimationFrame(tick);
+ }
}
const visibility=()=>{clock.set({visible:!document.hidden});sync();};
const preference=()=>{clock.set({reduced:reduced.matches});sync();};
const resize=()=>draw(clock.read().reduced?scene.duration-1:clock.read().elapsed);
let artReady=0;
- for(const src of studioMotionAssets){
- const image=new Image();
- studioImages.set(src,image);
- image.addEventListener('load',()=>{
- if(++artReady===studioMotionAssets.length)canvas.dataset.catArt='studio';
- if(!disposed)resize();
- },{once:true});
- image.src=src;
+ function loadArt(pose){
+ for(const src of studioMotionAssets){
+ if(!src.endsWith(`-${pose}.png`)||studioImages.has(src))continue;
+ const image=new Image();
+ studioImages.set(src,image);
+ image.addEventListener('load',()=>{
+ if(++artReady===studioMotionAssets.length)canvas.dataset.catArt='studio';
+ if(!disposed)resize();
+ },{once:true});
+ image.src=src;
+ }
}
+ loadArt('idle');
motion.addEventListener('click',()=>{clock.set({paused:!clock.read().paused});sync();});
document.addEventListener('visibilitychange',visibility);reduced.addEventListener('change',preference);
let observer;
- if('IntersectionObserver' in window){observer=new IntersectionObserver(entries=>{clock.set({inView:entries[0].isIntersecting});sync();},{threshold:0});observer.observe(canvas);}
+ if(observesHero){observer=new IntersectionObserver(entries=>{
+ if(disposed)return;
+ heroInViewport=entries.at(-1).isIntersecting;clock.set({inView:heroInViewport});sync();
+ },{threshold:0});observer.observe(canvas);}
const sizeObserver='ResizeObserver' in window?new ResizeObserver(resize):null;
sizeObserver?.observe(canvas);window.addEventListener('resize',resize);theme.addEventListener('click',resize);color.addEventListener('change',resize);
- window.addEventListener('pagehide',()=>{disposed=true;epoch++;cancelAnimationFrame(raf);observer?.disconnect();sizeObserver?.disconnect();});
+ window.addEventListener('pagehide',()=>{
+ disposed=true;heroInViewport=!observesHero;epoch++;cancelAnimationFrame(raf);
+ observer?.disconnect();observer?.takeRecords();sizeObserver?.disconnect();
+ });
window.addEventListener('pageshow',()=>{if(disposed){disposed=false;observer?.observe(canvas);sizeObserver?.observe(canvas);clock.set({visible:!document.hidden});sync();}});
fallback.hidden=true;canvas.hidden=false;motion.hidden=false;clock.set({visible:!document.hidden,reduced:reduced.matches});sync();
}
diff --git a/src/home/index.html b/src/home/index.html
index 07bcf2b..291fc47 100644
--- a/src/home/index.html
+++ b/src/home/index.html
@@ -5,7 +5,7 @@
-
+
算法游乐场 · 算法,玩着就懂了
diff --git a/tests/delivery/delivery.test.mjs b/tests/delivery/delivery.test.mjs
index 848c2c9..e75e7be 100644
--- a/tests/delivery/delivery.test.mjs
+++ b/tests/delivery/delivery.test.mjs
@@ -85,6 +85,7 @@ files.push('mining-shared-evidence.mjs','mining-shared-ui.mjs');
files.push('mining-bayes.mjs','mining-bayes-ui.mjs','mining-bayes.css');
files.push('distributions.html','distributions.css','distributions.mjs','distributions-core.mjs');
files.push('feedback-story.mjs','feedback-story-ui.mjs','feedback-story.css');
+files.push('feedback-prediction-ui.mjs');
files.push('seat-lesson.mjs','seat-lesson-ui.mjs','seat-lesson.css');
files.push('recommendation-cards.mjs');
files.push('evolution-birth.mjs','local-drafts.mjs','world-model.html','world-model.css','world-model.mjs','world-model-core.mjs','world-model-environment.mjs','world-model-session.mjs','world-model-lesson.mjs');
diff --git a/tests/experiments/recommendation/feedback-prediction-ui.test.mjs b/tests/experiments/recommendation/feedback-prediction-ui.test.mjs
new file mode 100644
index 0000000..4942fda
--- /dev/null
+++ b/tests/experiments/recommendation/feedback-prediction-ui.test.mjs
@@ -0,0 +1,94 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {readFile} from 'node:fs/promises';
+import {POSTS,PRESETS,INITIAL_PROFILE} from '../../../dist/data.mjs';
+import {captureFeedback} from '../../../dist/feedback-story.mjs';
+import {mountFeedbackPrediction} from '../../../dist/feedback-prediction-ui.mjs';
+
+class Element extends EventTarget {
+ constructor(){super();this.hidden=false;this.disabled=false;this.textContent='';this.innerHTML='';this.attributes={};}
+ setAttribute(name,value){this.attributes[name]=value;}
+ focus(){this.focused=true;}
+ scrollIntoView(){this.scrolled=true;}
+ click(){if(!this.disabled)this.dispatchEvent(new Event('click'));}
+}
+async function setup({weights=PRESETS.click.weights,profile=INITIAL_PROFILE}={}){
+ const html=await readFile(new URL('../../../dist/recommendation.html',import.meta.url),'utf8');
+ const els=Object.fromEntries([...html.matchAll(/id="([^"]+)"/g)].map(([,id])=>[id,new Element()]));
+ const state={posts:POSTS,weights:{...weights},profile:{...profile}},applied=[],returned=[];
+ const ui=mountFeedbackPrediction({document:{getElementById:id=>{assert.ok(els[id],`missing real markup ${id}`);return els[id];}},
+ getInputs:()=>state,applyFeedback:evidence=>{applied.push(evidence);state.profile={...evidence.after.profile};ui.sync();},
+ returnToCard:action=>returned.push(action),reducedMotion:()=>true});
+ return {ui,state,applied,returned,els,click:id=>els[id].click()};
+}
+test('direct feedback remains the default; preparing and guessing do not send or reveal feedback',async()=>{
+ const s=await setup(),before=structuredClone(s.state);
+ assert.equal(s.ui.request('0-0',-1),false);
+ assert.equal(s.els['feedback-prediction-panel'].hidden,true);
+ s.click('feedback-prediction-mode');assert.equal(s.ui.request('0-0',-1),true);
+ assert.match(s.els['feedback-prediction-card'].innerHTML,/波比/);
+ assert.equal(s.els['feedback-prediction-result'].hidden,true);
+ assert.equal(s.els['feedback-prediction-apply'].disabled,true);
+ s.click('feedback-prediction-stays');
+ assert.equal(s.els['feedback-prediction-apply'].disabled,false);
+ assert.equal(s.els['feedback-prediction-result'].hidden,true);
+ assert.deepEqual(s.state,before);assert.equal(s.applied.length,0);
+ assert.match(s.els['feedback-prediction-status'].textContent,/还没发送/);
+});
+test('one explicit check applies the real feedback exactly once and reports a truthful staying card',async()=>{
+ const s=await setup(),expected=captureFeedback(POSTS,s.state.weights,s.state.profile,'0-0',-1);
+ s.click('feedback-prediction-mode');s.ui.request('0-0',-1);s.click('feedback-prediction-stays');s.click('feedback-prediction-apply');
+ s.click('feedback-prediction-apply');
+ assert.equal(s.applied.length,1);assert.deepEqual(s.applied[0],expected);assert.deepEqual(s.state.profile,expected.after.profile);
+ assert.equal(s.els['feedback-prediction-result'].hidden,false);
+ assert.match(s.els['feedback-prediction-verdict'].textContent,/你猜.*仍在.*实际.*第 1 位/);
+ assert.match(s.els['feedback-prediction-position'].textContent,/第 1 位 → 第 1 位/);
+ assert.match(s.els['feedback-prediction-interest'].textContent,/100 → 88/);
+ assert.match(s.els['feedback-prediction-reason'].textContent,/不是屏蔽/);
+ assert.match(s.els['feedback-prediction-reason'].textContent,/规则没变/);
+});
+test('a card leaving six seats is not described as blocked, and a wrong prediction is preserved',async()=>{
+ const s=await setup();s.click('feedback-prediction-mode');s.ui.request('1-0',-1);
+ s.click('feedback-prediction-stays');s.click('feedback-prediction-apply');
+ assert.equal(s.applied[0].action.afterRank,null);
+ assert.match(s.els['feedback-prediction-verdict'].textContent,/你猜.*仍在.*实际.*离开/);
+ assert.match(s.els['feedback-prediction-position'].textContent,/→ 六席外/);
+ assert.match(s.els['feedback-prediction-card'].innerHTML,/反馈前第 5 位/);
+ assert.match(s.els['feedback-prediction-reason'].textContent,/候选.*没.*屏蔽/);
+});
+test('cancel, mode-off and reset never send a pending feedback; repeated selection replaces without applying',async()=>{
+ const s=await setup(),before=structuredClone(s.state);
+ s.click('feedback-prediction-mode');s.ui.request('0-0',-1);s.click('feedback-prediction-stays');
+ s.ui.request('1-0',1);assert.equal(s.els['feedback-prediction-apply'].disabled,true);
+ s.click('feedback-prediction-cancel');assert.equal(s.returned.at(-1).postId,'1-0');
+ assert.match(s.els['feedback-prediction-status'].textContent,/取消.*没.*发送/);
+ s.ui.request('0-0',-1);s.click('feedback-prediction-mode');
+ assert.equal(s.ui.request('0-0',-1),false);
+ s.click('feedback-prediction-mode');s.ui.request('0-0',-1);s.ui.reset();s.click('feedback-prediction-apply');
+ assert.equal(s.applied.length,0);assert.deepEqual(s.state,before);
+ assert.equal(s.ui.request('0-0',-1),false);
+});
+test('effective setting changes cancel a pending guess while identical values do not; late clicks cannot apply it',async()=>{
+ const s=await setup();s.click('feedback-prediction-mode');s.ui.request('0-0',-1);s.click('feedback-prediction-stays');
+ s.state.weights={...s.state.weights};s.ui.sync();assert.equal(s.els['feedback-prediction-apply'].disabled,false);
+ s.state.weights.click=99;s.ui.sync();s.click('feedback-prediction-apply');assert.equal(s.applied.length,0);
+ assert.match(s.els['feedback-prediction-status'].textContent,/规则或口味.*取消.*未发送/);
+ s.ui.request('0-0',-1);s.click('feedback-prediction-stays');s.state.profile.cat=.5;
+ // Guard the final check too, even if no render/sync happened between interactions.
+ s.click('feedback-prediction-apply');assert.equal(s.applied.length,0);
+});
+test('boundary feedback and zero click weight show unchanged results rather than forcing a rank movement',async()=>{
+ for(const options of [{profile:{...INITIAL_PROFILE,cat:0}},{weights:{click:0,diversity:80,newcomer:20}}]){
+ const s=await setup(options);s.click('feedback-prediction-mode');s.ui.request('0-0',-1);
+ s.click('feedback-prediction-leaves');s.click('feedback-prediction-apply');
+ const e=s.applied[0];assert.equal(e.action.beforeRank,e.action.afterRank);
+ assert.match(s.els['feedback-prediction-reason'].textContent,options.profile?/下限.*没有变化/:/点击优先.*0.*不参与排序/);
+ }
+});
+test('completed prediction stays frozen and is clearly history after later changes',async()=>{
+ const s=await setup();s.click('feedback-prediction-mode');s.ui.request('0-0',-1);s.click('feedback-prediction-stays');s.click('feedback-prediction-apply');
+ const verdict=s.els['feedback-prediction-verdict'].textContent,interest=s.els['feedback-prediction-interest'].textContent;
+ s.state.weights.click=50;s.ui.sync();
+ assert.equal(s.els['feedback-prediction-verdict'].textContent,verdict);assert.equal(s.els['feedback-prediction-interest'].textContent,interest);
+ assert.match(s.els['feedback-prediction-result-state'].textContent,/上次.*当前/);
+});
diff --git a/tests/experiments/world-model/world-model-ui.test.mjs b/tests/experiments/world-model/world-model-ui.test.mjs
index 8d26f4d..f94eaf9 100644
--- a/tests/experiments/world-model/world-model-ui.test.mjs
+++ b/tests/experiments/world-model/world-model-ui.test.mjs
@@ -11,8 +11,9 @@ test('Heim sits inside the one real ship and is introduced outside the trajector
assert.match(html.replace(plot,''),/嘿姆[^<]*试飞/,'crew introduction must not be painted on top of evidence');
});
let serial=0;
-async function boot({reduced=false,height=568}={}){
- const html=await readFile(new URL('../../../dist/world-model.html',import.meta.url),'utf8');
+async function boot({reduced=false,height=568,source=false}={}){
+ const base=source?'../../../src/experiments/world-model/':'../../../dist/';
+ const html=await readFile(new URL(base+'world-model.html',import.meta.url),'utf8');
class Element extends EventTarget{
constructor(){super();this.dataset={};this.attrs={};this.value='';this.textContent='';this.hidden=false;this.disabled=false;this.style={setProperty(){}};this.bounds={top:0,bottom:0};this.scrolls=[];}
setAttribute(k,v){this.attrs[k]=String(v);}getAttribute(k){return this.attrs[k];}getBoundingClientRect(){return this.bounds;}scrollIntoView(options){this.scrolls.push(options);}focus(){doc.activeElement=this;}
@@ -24,7 +25,7 @@ async function boot({reduced=false,height=568}={}){
const old=new Map(Object.keys(globals).map(k=>[k,Object.getOwnPropertyDescriptor(globalThis,k)]));
const restore=()=>{for(const[k,d]of old)d?Object.defineProperty(globalThis,k,d):delete globalThis[k];};
for(const[k,value]of Object.entries(globals))Object.defineProperty(globalThis,k,{value,writable:true,configurable:true});
- try{await import(new URL('../../../dist/world-model.mjs?t='+ ++serial,import.meta.url));}catch(e){restore();throw e;}
+ try{await import(new URL(base+'world-model.mjs?t='+ ++serial,import.meta.url));}catch(e){restore();throw e;}
const fire=(node,type)=>node.dispatchEvent(new Event(type));
return {els,frames,doc,media,win,restore,click:id=>{const e=els.get(id);if(!e.disabled&&!e.hidden)fire(e,'click');},
input:(id,value)=>{els.get(id).value=String(value);fire(els.get(id),'input');},
@@ -32,6 +33,28 @@ async function boot({reduced=false,height=568}={}){
finish(){for(let i=0;i<=65;i++)this.tick(i*100);},
hide(){doc.hidden=true;fire(doc,'visibilitychange');},show(){doc.hidden=false;fire(doc,'visibilitychange');}};
}
+test('flight paints only when a simulation beat advances, even at 120Hz',async()=>{
+ const u=await boot({source:true});try{
+ const path=u.els.get('actual-path'),progress=u.els.get('progress');
+ u.click('fly');
+ const prediction=u.els.get('prediction-path').getAttribute('points');
+ const setAttribute=path.setAttribute.bind(path);let writes=0;
+ path.setAttribute=(key,value)=>{if(key==='points')writes++;setAttribute(key,value);};
+ for(let i=0;i<12;i++)u.tick(i*1000/120);
+ assert.equal(writes,0,'frames before the first 100ms beat must not rewrite the path');
+ assert.match(progress.textContent,/^0 \/ 60/);
+ u.tick(100);
+ assert.equal(writes,1);
+ assert.equal(path.getAttribute('points'),'12.000,45.000 12.160,45.021');
+ for(let i=13;i<=720;i++)u.tick(i*1000/120);
+ assert.equal(writes,60,'the entire flight paints once per beat, including completion');
+ assert.equal(u.frames.size,0);
+ assert.match(progress.textContent,/^60 \/ 60/);
+ assert.equal(u.els.get('prediction-path').getAttribute('points'),prediction);
+ assert.equal(u.els.get('prediction-error').textContent,'16.6 单位');
+ assert.equal(u.els.get('target-distance').textContent,'14.1 单位');
+ }finally{u.restore();}
+});
test('Heim reports only the displayed flight stage and waits for actual completion before a result',async()=>{
const u=await boot();try{
const e=id=>u.els.get(id);
diff --git a/tests/home/home-art-loading.test.mjs b/tests/home/home-art-loading.test.mjs
new file mode 100644
index 0000000..fd37529
--- /dev/null
+++ b/tests/home/home-art-loading.test.mjs
@@ -0,0 +1,114 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+
+const idle = ['./studio-heim-idle.png', './studio-bobby-idle.png', './studio-chouchou-idle.png'];
+const run = ['./studio-heim-run.png', './studio-bobby-run.png', './studio-chouchou-run.png'];
+let bootId = 0;
+
+async function boot(t, { hidden = false, reduced = false, observe = true } = {}) {
+ const images = new Map(), frames = new Map();
+ const drawn = [];
+ let intersect, frameId = 0;
+ const ctx = Object.fromEntries('arc beginPath clearRect closePath ellipse fill fillRect fillText lineTo moveTo restore rotate save scale setTransform translate'.split(' ').map(name => [name, () => {}]));
+ ctx.createRadialGradient = () => ({ addColorStop() {} });
+ ctx.drawImage = image => drawn.push(image.src);
+ class Sprite extends EventTarget {
+ set src(src) { this.url = src; images.set(src, this); requests.push(src); }
+ get src() { return this.url; }
+ }
+ const requests = [];
+ class Observer {
+ constructor(callback) { intersect = isIntersecting => callback([{ isIntersecting }]); }
+ observe() {}
+ disconnect() {}
+ takeRecords() { return []; }
+ }
+ const element = () => Object.assign(new EventTarget(), { dataset: {}, setAttribute() {} });
+ const canvas = Object.assign(element(), { getContext: () => ctx, getBoundingClientRect: () => ({ width: 900, height: 330 }) });
+ const motion = element();
+ const elements = { '#home-theme': element(), '#hero-canvas': canvas, '#hero-fallback': element(), '#hero-motion': motion, '#hero-cat-stage': element() };
+ const document = Object.assign(new EventTarget(), { hidden, documentElement: element(), querySelector: selector => elements[selector] });
+ const media = Object.assign(new EventTarget(), { matches: reduced });
+ const color = Object.assign(new EventTarget(), { matches: false });
+ const window = new EventTarget();
+ if (observe) window.IntersectionObserver = Observer;
+ const globals = { window, document, location: { hash: '', search: '' }, Image: Sprite, devicePixelRatio: 1, IntersectionObserver: Observer,
+ matchMedia: query => query === '(prefers-reduced-motion: reduce)' ? media : color,
+ requestAnimationFrame: callback => (frames.set(++frameId, callback), frameId), cancelAnimationFrame: id => frames.delete(id) };
+ for (const [key, value] of Object.entries(globals)) {
+ const prior = Object.getOwnPropertyDescriptor(globalThis, key);
+ Object.defineProperty(globalThis, key, { value, configurable: true });
+ t.after(() => prior ? Object.defineProperty(globalThis, key, prior) : delete globalThis[key]);
+ }
+ await import(`../../src/home/home.mjs?art-test=${++bootId}`);
+ const fire = (target, type) => target.dispatchEvent(new Event(type));
+ return { canvas, motion, requests, drawn,
+ intersect: value => intersect(value),
+ visible(value) { document.hidden = !value; fire(document, 'visibilitychange'); },
+ reduce(value) { media.matches = value; fire(media, 'change'); },
+ leave: () => fire(window, 'pagehide'), restore: () => fire(window, 'pageshow'),
+ clickMotion: () => fire(motion, 'click'),
+ load(src) { const image = images.get(src); Object.assign(image, { complete: true, naturalWidth: 360, naturalHeight: 200 }); fire(image, 'load'); },
+ tick(now) { const callbacks = [...frames.values()]; frames.clear(); for (const callback of callbacks) callback(now); }
+ };
+}
+
+test('visible playback prewarms the running art once and uses it on the original first run', async t => {
+ const page = await boot(t);
+ assert.deepEqual(page.requests, idle, 'waiting cats need only their static poses before the first viewport observation');
+ page.intersect(false);
+ assert.deepEqual(page.requests, idle);
+ page.intersect(true);
+ assert.deepEqual(page.requests, [...idle, ...run], 'prewarm while the cats are still waiting for A*');
+ for (const src of [...idle, ...run]) page.load(src);
+ assert.equal(page.canvas.dataset.catArt, 'studio');
+ page.tick(0);
+ page.tick(4759);
+ assert.equal(page.canvas.dataset.catPhase, 'searching');
+ page.drawn.length = 0;
+ page.tick(4800);
+ assert.equal(page.canvas.dataset.catPhase, 'running');
+ assert.deepEqual(new Set(page.drawn), new Set([run[0], idle[1], idle[2]]));
+ page.clickMotion();
+ page.intersect(false);
+ page.intersect(true);
+ page.clickMotion();
+ assert.deepEqual(page.requests, [...idle, ...run]);
+});
+
+test('a hidden or reduced-motion page does not prewarm until it can play', async t => {
+ const page = await boot(t, { hidden: true, reduced: true });
+ page.intersect(true);
+ assert.deepEqual(page.requests, idle);
+ assert.equal(page.canvas.dataset.catPhase, 'arrived');
+ assert.equal(page.motion.disabled, true);
+ for (const src of idle) page.load(src);
+ assert.deepEqual(new Set(page.drawn), new Set(idle), 'the reduced-motion frame uses the unchanged idle art');
+ page.reduce(false);
+ assert.deepEqual(page.requests, idle, 'still hidden');
+ page.reduce(true);
+ page.visible(true);
+ assert.deepEqual(page.requests, idle, 'still reduced motion');
+ page.reduce(false);
+ assert.deepEqual(page.requests, [...idle, ...run]);
+});
+
+test('a paused animation waits for both playback and a fresh viewport observation after restore', async t => {
+ const page = await boot(t);
+ page.clickMotion();
+ page.intersect(true);
+ assert.deepEqual(page.requests, idle, 'paused before first paint');
+ page.leave();
+ page.restore();
+ page.clickMotion();
+ assert.deepEqual(page.requests, idle, 'do not reuse the prior viewport observation');
+ page.intersect(true);
+ assert.deepEqual(page.requests, [...idle, ...run]);
+});
+
+test('playback still prewarms when IntersectionObserver is unavailable', async t => {
+ const page = await boot(t, { observe: false });
+ assert.equal(page.requests.length, 6);
+ assert.deepEqual(new Set(page.requests), new Set([...idle, ...run]));
+ assert.equal(page.canvas.dataset.motion, 'playing');
+});
diff --git a/tests/home/home.test.mjs b/tests/home/home.test.mjs
index 7d45215..9519126 100644
--- a/tests/home/home.test.mjs
+++ b/tests/home/home.test.mjs
@@ -63,10 +63,13 @@ test('legacy recommendation bookmarks preserve query and hash without taking ove
assert.equal(legacyRecommendationTarget('#%66eed-section'), './recommendation.html#%66eed-section');
for(const hash of ['','#experiments','#about','#top','#unknown','#%E0%A4%A'])assert.equal(legacyRecommendationTarget(hash),null);
});
-test('every preserved recommendation element bookmark remains reachable except the new about section',async()=>{
+test('legacy recommendation bookmarks remain reachable without claiming newly introduced controls were homepage anchors',async()=>{
const html=await readFile(new URL('../../dist/recommendation.html',import.meta.url),'utf8');
for(const [,id] of html.matchAll(/\bid="([^"]+)"/g)){
if(id==='about')continue;
+ // This optional flow was introduced after recommendation moved to its own URL.
+ // Do not extend the homepage redirect surface for controls that never lived there.
+ if(id.startsWith('feedback-prediction-')){assert.equal(legacyRecommendationTarget('#'+id),null);continue;}
assert.equal(legacyRecommendationTarget('#'+id,'?v=saved'),`./recommendation.html?v=saved#${id}`,id);
}
});