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
5 changes: 5 additions & 0 deletions frontend/src/components/QuestionBankQuestionAction.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {useState} from "react";
import {announceQuestionBankConfigChanged} from "../questionBankChangeSignal";
import {
friendlyBridgeError,questionBankList,questionBankQuery,
type QuestionBankAnswer,type QuestionBankQuestion,type QuestionBankState,
Expand Down Expand Up @@ -47,6 +48,10 @@ export function QuestionBankQuestionAction({desktop,question}:{
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(typeof answer.remaining==="number"&&answer.remaining>=0)
announceQuestionBankConfigChanged();
}catch(cause){setError(friendlyBridgeError(cause));}
finally{setBusy(false);}
};
Expand Down
54 changes: 46 additions & 8 deletions frontend/src/components/QuestionBankSettingsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
type QuestionBankState,type QuestionBankToken,
} from "../bridge";
import {SettingsDialog} from "../ui/SettingsDialog";
import {announceQuestionBankConfigChanged} from "../questionBankChangeSignal";
import {announceQuestionBankConfigChanged,QUESTION_BANK_CONFIG_CHANGED} from "../questionBankChangeSignal";
import {ConfirmDialog} from "../ui/ConfirmDialog";
import "./QuestionBank.css";

Expand Down Expand Up @@ -52,8 +52,19 @@ export function QuestionBankSettingsPanel({desktop,dark=false}:{desktop:boolean;
const [quotaConfirm,setQuotaConfirm]=useState(false);
const [error,setError]=useState("");
const [notice,setNotice]=useState("");
const [externalReadRevision,setExternalReadRevision]=useState(0);
const mounted=useRef(true);
const listReadId=useRef(0);
const pendingExternalRead=useRef(false);
const locallyAnnouncing=useRef(false);

function announceLocalChange(){
// Settings has already applied the mutation result; do not read the same
// state again in response to this panel's own synchronous notification.
locallyAnnouncing.current=true;
try{announceQuestionBankConfigChanged();}
finally{locallyAnnouncing.current=false;}
}

useEffect(()=>{
mounted.current=true;
Expand All @@ -74,6 +85,33 @@ export function QuestionBankSettingsPanel({desktop,dark=false}:{desktop:boolean;
return ()=>{listReadId.current++;};
},[desktop]);

useEffect(()=>{
if(!desktop||typeof window==="undefined"||typeof window.addEventListener!=="function")return;
const onVaultChange=()=>{
if(locallyAnnouncing.current)return;
pendingExternalRead.current=true;
setExternalReadRevision(value=>value+1);
};
window.addEventListener(QUESTION_BANK_CONFIG_CHANGED,onVaultChange);
return ()=>window.removeEventListener(QUESTION_BANK_CONFIG_CHANGED,onVaultChange);
},[desktop]);

useEffect(()=>{
// A lookup or another UI can change the vault while settings is open.
// Coalesce external invalidations; wait until local mutations are finished.
if(!desktop||loading||refreshing||busy||!pendingExternalRead.current)return;
pendingExternalRead.current=false;
const readId=++listReadId.current;
void questionBankList().then(data=>{
if(mounted.current&&readId===listReadId.current){
setState(data);setError("");
}
}).catch(cause=>{
if(mounted.current&&readId===listReadId.current)
setError(friendlyBridgeError(cause));
});
},[desktop,loading,refreshing,busy,externalReadRevision]);

async function refreshList(){
if(!desktop||busy||refreshing)return;
// A newer manual read supersedes a hanging initial request. Its late
Expand All @@ -85,7 +123,7 @@ export function QuestionBankSettingsPanel({desktop,dark=false}:{desktop:boolean;
if(!mounted.current||readId!==listReadId.current)return;
setState(next);
// A manual read may discover changes made in another feature.
announceQuestionBankConfigChanged();
announceLocalChange();
setNotice("已重新载入本机题库和 Token 配置。");
}catch(cause){
if(mounted.current&&readId===listReadId.current)
Expand Down Expand Up @@ -130,15 +168,15 @@ export function QuestionBankSettingsPanel({desktop,dark=false}:{desktop:boolean;
if(!mounted.current)return;
setCheckingId("");setJob(null);setBusy(false);
// Bulk checks may touch many tokens; issue exactly one refresh at the end.
if(updated)announceQuestionBankConfigChanged();
if(updated)announceLocalChange();
setNotice("检测完成:"+done+" 条,失败 "+failed+" 条。余量以题库实际返回的数据为准。");
}
async function checkOne(id:string,quota=false){
if(busy||loading||refreshing)return;
setBusy(true);setCheckingId(id);setError("");setNotice("");
try{
setState(await questionBankCheckToken(id,quota));
announceQuestionBankConfigChanged();
announceLocalChange();
setNotice(quota?"已更新该 Token 可取得的余量信息。":"已完成单条状态检测。");
}catch(cause){setError(friendlyBridgeError(cause));}
finally{setBusy(false);setCheckingId("");}
Expand All @@ -149,7 +187,7 @@ export function QuestionBankSettingsPanel({desktop,dark=false}:{desktop:boolean;
try{
const next=await questionBankImportTokens(selected.id,tokenLines);
setState(next);setTokenLines("");
if((next.added??0)>0)announceQuestionBankConfigChanged();
if((next.added??0)>0)announceLocalChange();
setNotice("已导入 "+(next.added??0)+" 条,跳过重复 "+(next.skipped??0)+" 条。");
}catch(cause){setError(friendlyBridgeError(cause));}
finally{setBusy(false);}
Expand All @@ -159,7 +197,7 @@ export function QuestionBankSettingsPanel({desktop,dark=false}:{desktop:boolean;
setBusy(true);setError("");setNotice("");
try{
setState(await questionBankSetRotation(selected.id,mode));
announceQuestionBankConfigChanged();
announceLocalChange();
}
catch(cause){setError(friendlyBridgeError(cause));}
finally{setBusy(false);}
Expand All @@ -169,7 +207,7 @@ export function QuestionBankSettingsPanel({desktop,dark=false}:{desktop:boolean;
setBusy(true);setError("");setNotice("");
try{
setState(await questionBankSelectToken(id));
announceQuestionBankConfigChanged();
announceLocalChange();
}
catch(cause){setError(friendlyBridgeError(cause));}
finally{setBusy(false);}
Expand All @@ -179,7 +217,7 @@ export function QuestionBankSettingsPanel({desktop,dark=false}:{desktop:boolean;
setBusy(true);setError("");setNotice("");
try{
setState(await questionBankRemoveToken(id));
announceQuestionBankConfigChanged();
announceLocalChange();
setNotice("Token 已从本机加密保险库中删除。");
}catch(cause){setError(friendlyBridgeError(cause));}
finally{setBusy(false);}
Expand Down
75 changes: 74 additions & 1 deletion frontend/tests/questionBankCrossPanelSync.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ async function withPanels(check,{delayInitialMastery=false}={}){
setTimeout:()=>2,clearTimeout:()=>{}});
global.window=bus;
let tokens=[],listCalls=0,mastery,settings;
let lookupRemaining=7;
const lookupCalls=[];
const old=deferred();
const seen=[];
bus.addEventListener("studyflow:question-bank-config-changed",event=>seen.push(event));
Expand Down Expand Up @@ -48,6 +50,19 @@ async function withPanels(check,{delayInitialMastery=false}={}){
{...t,validity:"valid",...(quota?{remaining:12}: {})}:t);
return snap(tokens);
},
questionBankQuery:async(provider,question,tokenId)=>{
lookupCalls.push([provider,question,tokenId]);
assert.equal(provider,"yanxi");
assert.ok(tokens.length);
const id=tokenId||tokens[0].id;
if(lookupRemaining!==null)
tokens=tokens.map(t=>t.id===id?{...t,remaining:lookupRemaining}:t);
return {
found:true,answer:"B",status:"matched",remaining:lookupRemaining,
provider_id:"yanxi",provider_name:"言溪题库",token_id:id,
token_label:"Token 001",verified:false,
};
},
masteryAutoStatus:async()=>EMPTY,
masteryAutoStart:async()=>EMPTY,
masteryAutoControl:async()=>EMPTY,
Expand All @@ -68,6 +83,9 @@ async function withPanels(check,{delayInitialMastery=false}={}){
const {QuestionBankSettingsPanel}=load("components/QuestionBankSettingsPanel.tsx",{
"bridge.ts":mocks,...modal,
});
const {QuestionBankQuestionAction}=load("components/QuestionBankQuestionAction.tsx",{
"bridge.ts":mocks,
});
await act(async()=>{
mastery=create(React.createElement(MasteryAutoPanel,{courseKey:COURSE,desktop:true}));
settings=create(React.createElement(QuestionBankSettingsPanel,{desktop:true}));
Expand All @@ -77,7 +95,9 @@ async function withPanels(check,{delayInitialMastery=false}={}){
.find(b=>b.props.className==="sf-mastery-auto-start");
const checkbox=mastery.root.findAllByType("input").find(x=>x.props.type==="checkbox");
await act(async()=>checkbox.props.onChange({target:{checked:true}}));
await check({mastery,settings,button,start,seen,old,getListCalls:()=>listCalls});
await check({mastery,settings,button,start,seen,old,getListCalls:()=>listCalls,
setLookupRemaining:value=>{lookupRemaining=value;},lookupCalls,
QuestionBankQuestionAction});
}finally{
if(mastery||settings)await act(async()=>{
if(mastery)mastery.unmount();
Expand Down Expand Up @@ -165,3 +185,56 @@ test("bulk checks notify only once after all tokens, and verified quota uses rec
assert.match(textOf(mastery.root),/2\/2 条有有效数值记录/);
});
});

test("ordinary homework lookup synchronizes known quota into open vault and mastery summaries",async()=>{
await withPanels(async context=>{
const {QuestionBankQuestionAction,mastery,settings,button,seen,getListCalls,lookupCalls}=context;
const readsBeforeImport=getListCalls();
await importOne(context);
assert.equal(getListCalls(),readsBeforeImport+1,
"own settings change must notify mastery without reloading settings itself");
const readsBeforeQuery=getListCalls(),signalsBeforeQuery=seen.length;
let lookup;
try{
await act(async()=>lookup=create(React.createElement(QuestionBankQuestionAction,{
desktop:true,question:{title:"普通习题",question_type:"单选"},
})));
await act(async()=>button(lookup,"题库查题").props.onClick());
await act(async()=>button(lookup,"查询这道题").props.onClick());
assert.equal(lookupCalls.length,1);
assert.match(textOf(lookup.root),/剩余次数:7/);
assert.equal(seen.length,signalsBeforeQuery+1,
"successful numeric-balance lookup should invalidate open summaries once");
assert.equal(getListCalls(),readsBeforeQuery+3,
"one lookup list read plus one each from the two subscribed panels");
assert.match(textOf(mastery.root),/已知余量 7 次/);
assert.match(textOf(settings.root),/已知剩余总量7 次/);
assert.equal(seen.at(-1).detail,undefined,"signal must not carry question or token");
}finally{
if(lookup)await act(async()=>lookup.unmount());
}
});
});

test("lookup with unknown remaining balance does not fan out redundant list reads",async()=>{
await withPanels(async context=>{
const {QuestionBankQuestionAction,button,seen,getListCalls,lookupCalls}=context;
await importOne(context);
context.setLookupRemaining(null);
let lookup;
try{
await act(async()=>lookup=create(React.createElement(QuestionBankQuestionAction,{
desktop:true,question:{title:"余量未知的普通习题"},
})));
await act(async()=>button(lookup,"题库查题").props.onClick());
const before=getListCalls(),signals=seen.length;
await act(async()=>button(lookup,"查询这道题").props.onClick());
assert.equal(lookupCalls.length,1);
assert.match(textOf(lookup.root),/参考答案(未核验)/);
assert.equal(seen.length,signals);
assert.equal(getListCalls(),before);
}finally{
if(lookup)await act(async()=>lookup.unmount());
}
});
});
Loading