Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(settings): retain explicit token clearing and edits made during Apply

Bingxi Zhao (Frank)a137fbd29d21
diff --git a/web/components/settings/MinerUEngineSettings.tsx b/web/components/settings/MinerUEngineSettings.tsx
index 38115b0f5..253f4612d 100644
--- a/web/components/settings/MinerUEngineSettings.tsx
+++ b/web/components/settings/MinerUEngineSettings.tsx
@@ -583,7 +583,7 @@ export function MinerUEngineSettings() {
value={tokenDraft}
onChange={(e) => {
const val = e.target.value.trim();
- patch({ api_token: val || undefined });
+ patch({ api_token: val });
}}
/>
<button
diff --git a/web/features/settings/store/SettingsStore.tsx b/web/features/settings/store/SettingsStore.tsx
index 9c743ce99..06aef62ac 100644
--- a/web/features/settings/store/SettingsStore.tsx
+++ b/web/features/settings/store/SettingsStore.tsx
@@ -735,10 +735,16 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
[],
);
- const clearPending = useCallback(() => {
- pendingRef.current.clear();
- for (const ext of extensionsRef.current.values()) {
- ext.dirty = false;
+ const clearPending = useCallback((applied?: Map<string, unknown>) => {
+ for (const [key, payload] of pendingRef.current) {
+ if (!applied || (applied.has(key) && applied.get(key) === payload)) {
+ pendingRef.current.delete(key);
+ }
+ }
+ for (const [key, ext] of extensionsRef.current) {
+ if (!applied || (applied.has(key) && applied.get(key) === ext.payload)) {
+ ext.dirty = false;
+ }
}
syncPendingKeys();
}, [syncPendingKeys]);
@@ -1727,6 +1733,12 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
/** Apply — move everything into the live files and clear the draft. */
const applyCatalog = useCallback(async () => {
setApplying(true);
+ // Save the payloads and callbacks represented by this Apply. Edits made
+ // during a request remain a new draft, including on the same page.
+ const applyingExtensions = Array.from(pendingRef.current, ([key, payload]) => {
+ const ext = extensionsRef.current.get(key);
+ return { key, payload, save: ext?.dirty ? ext.save : null };
+ });
try {
if (catalogEditable) {
for (const [service, bucket] of Object.entries(draft.services)) {
@@ -1756,10 +1768,8 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
// Pages still on screen save themselves — they refresh their own local
// state and surface their own errors. Everything else pending is
// written straight to the endpoint that owns it.
- const mounted = extensionsRef.current;
- for (const [key, payload] of Array.from(pendingRef.current.entries())) {
- const ext = mounted.get(key);
- if (ext?.dirty) await ext.save();
+ for (const { key, payload, save } of applyingExtensions) {
+ if (save) await save();
else await applyExtensionPayload(key, payload);
if (key === "ui") applyUi(payload as UiSettings);
}
@@ -1789,7 +1799,9 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
}
- clearPending();
+ clearPending(
+ new Map(applyingExtensions.map(({ key, payload }) => [key, payload])),
+ );
setStoredDraft(null);
setSavedSignature(null);
setDraftRevision((value) => value + 1);
diff --git a/web/locales/de/app.json b/web/locales/de/app.json
index 0c45dbde7..3f7df7d41 100644
--- a/web/locales/de/app.json
+++ b/web/locales/de/app.json
@@ -5331,5 +5331,7 @@
"Could not connect to the speech provider. Check the provider URL and network connection.": "Der Sprachanbieter konnte nicht erreicht werden. Prüfe die Anbieter-URL und Netzwerkverbindung.",
"Qwen-Audio TTS requires a Beijing API key. You can set a Beijing workspace URL in the provider connection; the speech endpoint is selected automatically.": "Qwen-Audio TTS erfordert einen API-Schlüssel für Peking. In der Anbieterverbindung kannst du eine Arbeitsbereichs-URL für Peking angeben; der Sprachendpunkt wird automatisch gewählt.",
"Speech was generated, but the audio download failed. Try again or check the network connection.": "Die Sprache wurde erzeugt, aber der Audiodownload ist fehlgeschlagen. Versuche es erneut oder prüfe die Netzwerkverbindung.",
- "Request timeout (seconds)": "Zeitlimit für Anfragen (Sekunden)"
+ "Request timeout (seconds)": "Zeitlimit für Anfragen (Sekunden)",
+ "Show API token": "API-Token anzeigen",
+ "Hide API token": "API-Token ausblenden"
}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 58d8ea050..d0c7bd50d 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -5331,5 +5331,7 @@
"Could not connect to the speech provider. Check the provider URL and network connection.": "Could not connect to the speech provider. Check the provider URL and network connection.",
"Qwen-Audio TTS requires a Beijing API key. You can set a Beijing workspace URL in the provider connection; the speech endpoint is selected automatically.": "Qwen-Audio TTS requires a Beijing API key. You can set a Beijing workspace URL in the provider connection; the speech endpoint is selected automatically.",
"Speech was generated, but the audio download failed. Try again or check the network connection.": "Speech was generated, but the audio download failed. Try again or check the network connection.",
- "Request timeout (seconds)": "Request timeout (seconds)"
+ "Request timeout (seconds)": "Request timeout (seconds)",
+ "Show API token": "Show API token",
+ "Hide API token": "Hide API token"
}
diff --git a/web/locales/fr/app.json b/web/locales/fr/app.json
index 1b43c1ee0..c8c6de687 100644
--- a/web/locales/fr/app.json
+++ b/web/locales/fr/app.json
@@ -5774,5 +5774,7 @@
"Qwen-Audio TTS speed must be between 0.5 and 2.": "La vitesse de Qwen-Audio TTS doit être comprise entre 0,5 et 2.",
"Qwen3 TTS uses voices such as Cherry and outputs WAV audio. Match the API key region to the provider URL.": "Qwen3 TTS utilise des voix comme Cherry et produit un audio WAV. Faites correspondre la région de la clé API à l’URL du fournisseur.",
"Qwen-Audio TTS requires a Beijing API key. You can set a Beijing workspace URL in the provider connection; the speech endpoint is selected automatically.": "Qwen-Audio TTS nécessite une clé API pour la région de Pékin. Vous pouvez définir une URL d’espace de travail de Pékin dans la connexion au fournisseur ; le point de terminaison vocal est sélectionné automatiquement.",
- "Fetching the model list does not test speech synthesis. Use Preview voice to test this model and voice.": "Récupérer la liste des modèles ne teste pas la synthèse vocale. Utilisez l’aperçu vocal pour tester ce modèle et cette voix."
+ "Fetching the model list does not test speech synthesis. Use Preview voice to test this model and voice.": "Récupérer la liste des modèles ne teste pas la synthèse vocale. Utilisez l’aperçu vocal pour tester ce modèle et cette voix.",
+ "Show API token": "Afficher le jeton API",
+ "Hide API token": "Masquer le jeton API"
}
diff --git a/web/locales/pl/app.json b/web/locales/pl/app.json
index 179332c73..97bacb07e 100644
--- a/web/locales/pl/app.json
+++ b/web/locales/pl/app.json
@@ -5347,5 +5347,7 @@
"Qwen-Audio TTS speed must be between 0.5 and 2.": "Prędkość Qwen-Audio TTS musi wynosić od 0,5 do 2.",
"Qwen3 TTS uses voices such as Cherry and outputs WAV audio. Match the API key region to the provider URL.": "Qwen3 TTS używa głosów takich jak Cherry i generuje audio WAV. Dopasuj region klucza API do adresu URL dostawcy.",
"Qwen-Audio TTS requires a Beijing API key. You can set a Beijing workspace URL in the provider connection; the speech endpoint is selected automatically.": "Qwen-Audio TTS wymaga klucza API z regionu Pekin. W połączeniu z dostawcą możesz ustawić adres URL przestrzeni roboczej z regionu Pekin; punkt końcowy mowy zostanie wybrany automatycznie.",
- "Fetching the model list does not test speech synthesis. Use Preview voice to test this model and voice.": "Pobranie listy modeli nie sprawdza syntezy mowy. Użyj podglądu głosu, aby przetestować model i głos."
+ "Fetching the model list does not test speech synthesis. Use Preview voice to test this model and voice.": "Pobranie listy modeli nie sprawdza syntezy mowy. Użyj podglądu głosu, aby przetestować model i głos.",
+ "Show API token": "Pokaż token API",
+ "Hide API token": "Ukryj token API"
}
diff --git a/web/locales/uk/app.json b/web/locales/uk/app.json
index d7d6e9ad7..99cc700fd 100644
--- a/web/locales/uk/app.json
+++ b/web/locales/uk/app.json
@@ -5347,5 +5347,7 @@
"Qwen-Audio TTS speed must be between 0.5 and 2.": "Швидкість Qwen-Audio TTS має бути від 0,5 до 2.",
"Qwen3 TTS uses voices such as Cherry and outputs WAV audio. Match the API key region to the provider URL.": "Qwen3 TTS використовує голоси на кшталт Cherry та створює аудіо WAV. Регіон ключа API має відповідати URL провайдера.",
"Qwen-Audio TTS requires a Beijing API key. You can set a Beijing workspace URL in the provider connection; the speech endpoint is selected automatically.": "Qwen-Audio TTS потребує ключа API для регіону Пекін. У підключенні провайдера можна задати URL робочого простору для регіону Пекін; кінцева точка мовлення вибирається автоматично.",
- "Fetching the model list does not test speech synthesis. Use Preview voice to test this model and voice.": "Отримання списку моделей не перевіряє синтез мовлення. Скористайтеся попереднім прослуховуванням голосу, щоб перевірити модель і голос."
+ "Fetching the model list does not test speech synthesis. Use Preview voice to test this model and voice.": "Отримання списку моделей не перевіряє синтез мовлення. Скористайтеся попереднім прослуховуванням голосу, щоб перевірити модель і голос.",
+ "Show API token": "Показати токен API",
+ "Hide API token": "Приховати токен API"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index ca15e5a14..115686cd8 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -5331,5 +5331,7 @@
"Could not connect to the speech provider. Check the provider URL and network connection.": "无法连接语音服务,请检查提供方 URL 和网络连接。",
"Qwen-Audio TTS requires a Beijing API key. You can set a Beijing workspace URL in the provider connection; the speech endpoint is selected automatically.": "Qwen-Audio TTS 需要北京地域的 API Key。可在提供方连接中填写北京业务空间 URL,系统会自动选择合成端点。",
"Speech was generated, but the audio download failed. Try again or check the network connection.": "语音已生成,但音频下载失败,请重试或检查网络连接。",
- "Request timeout (seconds)": "请求超时(秒)"
+ "Request timeout (seconds)": "请求超时(秒)",
+ "Show API token": "显示 API 令牌",
+ "Hide API token": "隐藏 API 令牌"
}
diff --git a/web/tests/settings-unified-draft.spec.tsx b/web/tests/settings-unified-draft.spec.tsx
index b35c9d0a2..84f31c6bd 100644
--- a/web/tests/settings-unified-draft.spec.tsx
+++ b/web/tests/settings-unified-draft.spec.tsx
@@ -459,3 +459,45 @@ it("allows incomplete model drafts but blocks Apply before writing any live sett
expect(writes("/api/settings/workspace")).toHaveLength(0);
expect(live.services.llm.profiles).toHaveLength(0);
});
+
+it("preserves the distinction between untouched and explicitly cleared MinerU tokens", async () => {
+ resources.mineru = {
+ settings: { mode: "cloud", api_base_url: "http://mineru" },
+ api_token_set: true,
+ };
+ render(<App page="mineru" />);
+ await ready();
+ const token = await screen.findByPlaceholderText("••••••••••••");
+ fireEvent.click(screen.getByRole("button", { name: "Show API token" }));
+ expect(token).toHaveAttribute("type", "text");
+ expect(settings.hasUnsavedChanges).toBe(false);
+ fireEvent.change(token, { target: { value: "replacement" } });
+ fireEvent.change(token, { target: { value: "" } });
+ expect(settings.hasUnsavedChanges).toBe(true);
+ await act(() => settings.applyCatalog());
+ expect(JSON.parse(String(writes("/api/settings/mineru")[0][1].body))).toHaveProperty("api_token", "");
+});
+
+it("keeps edits made while Apply is pending for the next Apply", async () => {
+ render(<App />);
+ await ready();
+ fireEvent.change(screen.getByLabelText("workspace"), { target: { value: "/first" } });
+ const implementation = mocks.fetch.getMockImplementation()!;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ mocks.fetch.mockImplementation(async (url, init) => {
+ if (url === "/api/settings/workspace" && init?.method === "PUT") await gate;
+ return implementation(url, init);
+ });
+ let applying!: Promise<void>;
+ act(() => { applying = settings.applyCatalog(); });
+ await waitFor(() => expect(writes("/api/settings/workspace")).toHaveLength(1));
+ fireEvent.change(screen.getByLabelText("workspace"), { target: { value: "/second" } });
+ await act(async () => { release(); await applying; });
+ expect(resources.workspace.path).toBe("/first");
+ expect(screen.getByLabelText("workspace")).toHaveValue("/second");
+ expect(settings.draftState).toBe("unsaved");
+ await act(() => settings.applyCatalog());
+ expect(resources.workspace.path).toBe("/second");
+ expect(settings.draftState).toBe("clean");
+});