Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 67 additions & 19 deletions frontend/src/components/QuestionBankQuestionAction.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {useState} from "react";
import {useEffect,useRef,useState} from "react";
import {announceQuestionBankConfigChanged} from "../questionBankChangeSignal";
import {
friendlyBridgeError,questionBankList,questionBankQuery,
Expand All @@ -14,46 +14,94 @@ import "./QuestionBank.css";
export function QuestionBankQuestionAction({desktop,question}:{
desktop:boolean;question:QuestionBankQuestion;
}){
const [open,setOpen]=useState(false);
// The same question row can be reused for another round. An old async
// answer must never be displayed for a different stem, options or type.
const questionKey=JSON.stringify([question.title,question.question_type??"",question.options??[]]);
const visit=useRef({key:questionKey,revision:0});
const listReadId=useRef(0);
const answerReadId=useRef(0);
if(visit.current.key!==questionKey){
visit.current={key:questionKey,revision:visit.current.revision+1};
listReadId.current++;
answerReadId.current++;
}
const revision=visit.current.revision;
const mounted=useRef(false);
const [openRevision,setOpenRevision]=useState<number|null>(null);
const open=openRevision===revision;
const [loading,setLoading]=useState(false);
const [busy,setBusy]=useState(false);
const [state,setState]=useState<QuestionBankState>({providers:[],tokens:[]});
const [provider,setProvider]=useState("");
const [tokenId,setTokenId]=useState("");
const [error,setError]=useState("");
const [result,setResult]=useState<QuestionBankAnswer|null>(null);
const [result,setResult]=useState<{revision:number;answer:QuestionBankAnswer}|null>(null);
const visibleResult=result?.revision===revision?result.answer:null;

useEffect(()=>{
mounted.current=true;
return ()=>{
mounted.current=false;
listReadId.current++;
answerReadId.current++;
};
},[]);
useEffect(()=>{
// A different question starts closed, with no previous answer or pending
// indicator. The revision guard also invalidates late callbacks instantly.
setOpenRevision(null);setLoading(false);setBusy(false);
setState({providers:[],tokens:[]});setProvider("");setTokenId("");
setError("");setResult(null);
},[revision]);

const reveal=async()=>{
if(!desktop||busy)return;
if(open){setOpen(false);return;}
setOpen(true);setLoading(true);setError("");setResult(null);
if(open){
listReadId.current++;
setOpenRevision(null);setLoading(false);
return;
}
const requestId=++listReadId.current;
const isCurrent=()=>mounted.current&&visit.current.revision===revision
&&listReadId.current===requestId;
setOpenRevision(revision);setLoading(true);setError("");setResult(null);
try{
const saved=await questionBankList();
if(!isCurrent())return;
setState(saved);
const available=saved.providers.filter(p=>saved.tokens.some(t=>t.provider_id===p.id));
const target=available[0]?.id||saved.providers[0]?.id||"";
setProvider(target);
setTokenId("");
}catch(cause){setError(friendlyBridgeError(cause));}
finally{setLoading(false);}
}catch(cause){
if(isCurrent())setError(friendlyBridgeError(cause));
}finally{
if(isCurrent())setLoading(false);
}
};
const chooseProvider=(id:string)=>{
setProvider(id);
setTokenId("");
setResult(null);setError("");
};
const query=async()=>{
if(busy||!provider||!tokens.length)return;
if(busy||loading||!open||!provider||!tokens.length||!question.title.trim())return;
const requestId=++answerReadId.current;
const isCurrent=()=>mounted.current&&visit.current.revision===revision
&&answerReadId.current===requestId;
setBusy(true);setError("");setResult(null);
try{
const answer=await questionBankQuery(provider,question,tokenId);
setResult(answer);
// The shared vault persists numeric balances returned by normal lookups.
// Invalidate open summaries; the event contains no question or token data.
if(isCurrent())setResult({revision,answer});
// The lookup can update the vault even if the user moved to another
// question. Refresh shared balances, but never show its stale answer.
if(typeof answer.remaining==="number"&&answer.remaining>=0)
announceQuestionBankConfigChanged();
}catch(cause){setError(friendlyBridgeError(cause));}
finally{setBusy(false);}
}catch(cause){
if(isCurrent())setError(friendlyBridgeError(cause));
}finally{
if(isCurrent())setBusy(false);
}
};
const tokens=state.tokens.filter(t=>t.provider_id===provider);

Expand All @@ -80,18 +128,18 @@ export function QuestionBankQuestionAction({desktop,question}:{
{tokens.map(t=><option key={t.id} value={t.id}>{t.label}{t.active?"(默认)":""}</option>)}
</select>
</label>
<button type="button" disabled={busy||tokens.length===0||!question.title.trim()}
<button type="button" disabled={busy||loading||tokens.length===0||!question.title.trim()}
onClick={()=>void query()}>{busy?"查询中…":"查询这道题"}</button>
</div>
<p className="sf-qb-hint">每次仅使用本题库的一条 Token;可自动轮流或手动固定。结果仅供核对,不自动提交。</p>
</>}
{error&&<p role="alert" className="sf-qb-error">{error}</p>}
{result&&<div className="sf-qb-answer" role="status">
{result.found
?<><strong>{result.provider_name} · 参考答案(未核验)</strong>
<pre>{result.answer}</pre></>
{visibleResult&&<div className="sf-qb-answer" role="status">
{visibleResult.found
?<><strong>{visibleResult.provider_name} · 参考答案(未核验)</strong>
<pre>{visibleResult.answer}</pre></>
:<strong>当前题库未找到该题的参考答案</strong>}
<small>查询 Token:{result.token_label}{result.remaining!==null?" · 剩余次数:"+result.remaining:""}</small>
<small>查询 Token:{visibleResult.token_label}{visibleResult.remaining!==null?" · 剩余次数:"+visibleResult.remaining:""}</small>
</div>}
</div>}
</div>;
Expand Down
126 changes: 126 additions & 0 deletions frontend/tests/questionBankInlineQuestionRace.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
const test=require("node:test");
const assert=require("node:assert/strict");
const React=require("react");
const {create,act}=require("react-test-renderer");
const load=require("./helpers/load.cjs");

const deferred=()=>{
let resolve,reject;
const promise=new Promise((yes,no)=>{resolve=yes;reject=no;});
return {promise,resolve,reject};
};
const textOf=node=>typeof node==="string"?node:(node.children??[]).map(textOf).join("");
const Q1={title:"同一题号的题目",question_type:"单选",options:[{key:"A",text:"甲"}]};
const Q2={title:"同一题号的题目",question_type:"单选",options:[{key:"A",text:"乙"}]};
const BANK_A={providers:[{id:"a",name:"旧题库"}],
tokens:[{id:"1".repeat(32),provider_id:"a",label:"旧 Token",active:true}]};
const BANK_B={providers:[{id:"b",name:"新题库"}],
tokens:[{id:"2".repeat(32),provider_id:"b",label:"新 Token",active:true}]};
const answer=(value,remaining=null)=>({
found:true,answer:value,remaining,status:"matched",provider_id:"b",
provider_name:"新题库",token_id:"2".repeat(32),token_label:"新 Token",verified:false,
});

async function withAction(list,query,check){
const original=global.window;
const bus=new EventTarget();
global.window=bus;
let view;
let signals=0;
bus.addEventListener("studyflow:question-bank-config-changed",()=>signals++);
try{
const {QuestionBankQuestionAction}=load("components/QuestionBankQuestionAction.tsx",{
"bridge.ts":{
questionBankList:list,questionBankQuery:query,
friendlyBridgeError:err=>String(err?.message||err),
}
});
await act(async()=>view=create(React.createElement(QuestionBankQuestionAction,{
desktop:true,question:Q1,
})));
const button=label=>{
const found=view.root.findAllByType("button").find(b=>textOf(b).includes(label));
assert.ok(found,"missing button "+label);
return found;
};
const change=async question=>act(async()=>view.update(React.createElement(
QuestionBankQuestionAction,{desktop:true,question},
)));
await check({view,button,change,signals:()=>signals});
}finally{
if(view)await act(async()=>view.unmount());
global.window=original;
}
}

test("late answer for old options never appears under a changed question, but still invalidates balance",async()=>{
const previous=deferred(),calls=[];
await withAction(async()=>BANK_B,async(provider,question)=>{
calls.push([provider,question]);
return calls.length===1?previous.promise:answer("B_CORRECT",7);
},async({view,button,change,signals})=>{
await act(async()=>button("题库查题").props.onClick());
await act(async()=>button("查询这道题").props.onClick());
assert.match(textOf(view.root),/查询中…/);
await change(Q2);
assert.match(textOf(view.root),/题库查题/);
assert.doesNotMatch(textOf(view.root),/查询中…/);
await act(async()=>previous.resolve(answer("A_OLD_WRONG",5)));
assert.doesNotMatch(textOf(view.root),/A_OLD_WRONG|剩余次数:5/);
assert.equal(signals(),1,"old request may update balance in the shared vault");
await act(async()=>button("题库查题").props.onClick());
await act(async()=>button("查询这道题").props.onClick());
assert.equal(calls.length,2);
assert.deepEqual(calls.map(x=>x[1].options[0].text),["甲","乙"]);
assert.match(textOf(view.root),/B_CORRECT/);
assert.doesNotMatch(textOf(view.root),/A_OLD_WRONG/);
assert.equal(signals(),2);
});
});

test("late list from previous question does not overwrite the newly opened provider",async()=>{
const oldList=deferred();
let reads=0;
await withAction(()=>++reads===1?oldList.promise:Promise.resolve(BANK_B),
async()=>answer("unused"),async({view,button,change})=>{
await act(async()=>button("题库查题").props.onClick());
assert.match(textOf(view.root),/正在读取本机题库/);
await change(Q2);
await act(async()=>button("题库查题").props.onClick());
assert.equal(reads,2);
const selected=()=>view.root.findAllByType("select")[0]?.props.value;
assert.equal(selected(),"b");
await act(async()=>oldList.resolve(BANK_A));
assert.equal(selected(),"b");
assert.match(textOf(view.root),/新题库/);
assert.doesNotMatch(textOf(view.root),/旧题库/);
});
});

test("closing and reopening while first bank read hangs discards its late failure",async()=>{
const first=deferred();
let reads=0;
await withAction(()=>++reads===1?first.promise:Promise.resolve(BANK_B),
async()=>answer("unused"),async({view,button})=>{
await act(async()=>button("题库查题").props.onClick());
await act(async()=>button("收起题库").props.onClick());
await act(async()=>button("题库查题").props.onClick());
assert.equal(reads,2);
assert.match(textOf(view.root),/新题库/);
await act(async()=>first.reject(new Error("OLD_LIST_FAILURE")));
assert.doesNotMatch(textOf(view.root),/OLD_LIST_FAILURE/);
assert.match(textOf(view.root),/新 Token/);
});
});

test("a previously displayed answer is hidden when the same row changes question",async()=>{
await withAction(async()=>BANK_B,async()=>answer("OLD_RESULT"),
async({view,button,change})=>{
await act(async()=>button("题库查题").props.onClick());
await act(async()=>button("查询这道题").props.onClick());
assert.match(textOf(view.root),/OLD_RESULT/);
await change(Q2);
assert.doesNotMatch(textOf(view.root),/OLD_RESULT/);
assert.equal(button("题库查题").props["aria-expanded"],false);
});
});
Loading