Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(notes): summarise long recordings in parts when the local model cannot fit them (#2172)
Joshua23c28cadb2e2
diff --git a/preload.js b/preload.jsindex 1ce36bc1f..8c30b06c7 100644--- a/preload.js+++ b/preload.js@@ -667,6 +667,8 @@ contextBridge.exposeInMainWorld("electronAPI", {processLocalReasoning: (text, modelId, agentName, config) =>ipcRenderer.invoke("process-local-reasoning", text, modelId, agentName, config),checkLocalReasoningAvailable: () => ipcRenderer.invoke("check-local-reasoning-available"),+ getLocalContextBudget: (modelId) => ipcRenderer.invoke("get-local-context-budget", modelId),+ cancelLocalReasoning: (requestId) => ipcRenderer.invoke("cancel-local-reasoning", requestId),// Anthropic reasoningprocessAnthropicReasoning: (text, modelId, agentName, config) =>diff --git a/src/components/notes/ActionProcessingOverlay.tsx b/src/components/notes/ActionProcessingOverlay.tsxindex 23004f7a9..b35a805df 100644--- a/src/components/notes/ActionProcessingOverlay.tsx+++ b/src/components/notes/ActionProcessingOverlay.tsx@@ -2,19 +2,29 @@ import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";import { Check } from "../icons";import { cn } from "../lib/utils";+import { Button } from "../ui/button";import type { ActionProcessingState } from "../../hooks/useActionProcessing";+import type { NoteActionProgress } from "../../stores/actionProcessingStore";interface ActionProcessingOverlayProps {state: ActionProcessingState;actionName: string | null;+ /** Set while a long note is summarised in parts. */+ progress?: NoteActionProgress | null;+ /** Offered while processing: a run in parts takes minutes, and only quitting stopped it before. */+ onCancel?: () => void;}export default function ActionProcessingOverlay({state,actionName,+ progress = null,+ onCancel,}: ActionProcessingOverlayProps) {const { t } = useTranslation();- const [visible, setVisible] = useState(false);+ // A mount mid-run is a note switch (NoteEditor is keyed by note id); the+ // overlay must show without waiting for a state change that already happened.+ const [visible, setVisible] = useState(state !== "idle");const [prevState, setPrevState] = useState(state);if (state !== prevState) {@@ -87,6 +97,11 @@ export default function ActionProcessingOverlay({) : (<><span className="text-xs font-medium text-accent/70 tracking-tight">{actionName}</span>+ {progress ? (+ <span className="text-[11px] text-accent/50 tracking-tight">+ {t("notes.actions.chunkProgress", { step: progress.step, total: progress.total })}+ </span>+ ) : null}<div className="w-32 h-0.5 bg-accent/10 rounded-full overflow-hidden"><divclassName="h-full w-1/3 bg-accent/40 rounded-full"@@ -94,6 +109,17 @@ export default function ActionProcessingOverlay({data-scanner-progress=""/></div>+ {onCancel ? (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={onCancel}+ className="h-6 px-2 text-[11px] text-accent/60 hover:text-accent hover:bg-accent/8 dark:text-accent/60 dark:hover:text-accent dark:hover:bg-accent/8"+ >+ {t("common.cancel")}+ </Button>+ ) : null}</>)}</div>diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxindex 02122dd30..0341155bb 100644--- a/src/components/notes/NoteEditor.tsx+++ b/src/components/notes/NoteEditor.tsx@@ -62,6 +62,7 @@ import {} from "../ui/splitButton";import type { NoteItem, FolderItem } from "../../types/electron";import type { ActionProcessingState } from "../../hooks/useActionProcessing";+import type { NoteActionProgress } from "../../stores/actionProcessingStore";import ActionProcessingOverlay from "./ActionProcessingOverlay";import NoteBottomBar from "./NoteBottomBar";import NoteRecordControl, { RecordingWave } from "./NoteRecordControl";@@ -197,6 +198,8 @@ interface NoteEditorProps {onGenerateSummary?: () => void;actionProcessingState?: ActionProcessingState;actionName?: string | null;+ actionProgress?: NoteActionProgress | null;+ onCancelAction?: () => void;diarizationSessionId?: string | null;onLiveSpeakerLock?: (speakerId: string, displayName: string) => void;sessionDiarizationEnabled?: boolean;@@ -230,6 +233,8 @@ export default function NoteEditor({onGenerateSummary,actionProcessingState,actionName,+ actionProgress,+ onCancelAction,diarizationSessionId,onLiveSpeakerLock,sessionDiarizationEnabled,@@ -1224,6 +1229,8 @@ export default function NoteEditor({<ActionProcessingOverlaystate={actionProcessingState ?? "idle"}actionName={actionName ?? null}+ progress={actionProgress ?? null}+ onCancel={onCancelAction}/><divclassName="absolute bottom-0 left-0 right-0 h-20 pointer-events-none"diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex b0bf0dcbd..034a3902b 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -563,7 +563,9 @@ export default function PersonalNotesView({const {state: actionProcessingState,actionName,+ progress: actionProgress,runAction,+ cancel: cancelAction,} = useActionProcessing(activeNoteId ?? null);// Boolean flag so actions enable during recording without re-rendering on every transcript update.@@ -697,6 +699,13 @@ export default function PersonalNotesView({modelId: effectiveModelId,isMeetingNote,knownPeople,+ // The pieces, so a recording too long for a local model can be split+ // along the transcript rather than through the joined string.+ material: {+ notes: hasNotes ? noteContent : "",+ meetingContext,+ transcript: formattedTranscript,+ },allowTitleGeneration: isRegenerableNoteTitle(editorNote.title,[t("notes.list.untitledNote"), t("notes.list.newNote"), t("notes.sidebar.newNote")],@@ -793,6 +802,8 @@ export default function PersonalNotesView({onCancelPendingSaves={cancelPendingSaves}actionProcessingState={actionProcessingState}actionName={actionName}+ actionProgress={actionProgress}+ onCancelAction={cancelAction}onGenerateSummary={generateSummary}actionPicker={<ActionPickerdiff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 56b0fa2cc..f58c127d7 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -5256,6 +5256,30 @@ class IPCHandlers {}});+ ipcMain.handle("cancel-local-reasoning", (event, requestId) => {+ require("../services/localReasoningBridge").default.cancel(requestId);+ });++ // After a local refusal, the renderer plans a note's parts against this+ // number (#2142 part 3). It is the same ceiling runInference sizes against,+ // so a part the renderer judges to fit is one the main process will accept+ // without a restart it cannot afford.+ ipcMain.handle("get-local-context-budget", async (event, modelId) => {+ try {+ const modelManager = require("./modelManagerBridge").default;+ modelManager.ensureInitialized();+ const modelInfo = modelManager.findModelById(modelId);+ if (!modelInfo) {+ return { success: false, error: `Model "${modelId}" not found` };+ }+ const modelPath = require("path").join(modelManager.modelsDir, modelInfo.model.fileName);+ const { ceiling } = await modelManager.contextCeiling(modelInfo, modelPath);+ return { success: true, maxContextTokens: ceiling, modelName: modelInfo.model.name };+ } catch (error) {+ return { success: false, error: error.message };+ }+ });+ipcMain.handle("process-anthropic-reasoning",async (event, text, modelId, _agentName, config) => {diff --git a/src/helpers/llamaServer.js b/src/helpers/llamaServer.jsindex 61f4e5779..dae65d0cd 100644--- a/src/helpers/llamaServer.js+++ b/src/helpers/llamaServer.js@@ -73,6 +73,7 @@ class LlamaServerManager {this.process = null;this.port = null;this.ready = false;+ this.activeRequest = null;this.modelPath = null;// draftModelPath is the REQUESTED drafter (stable across identical requests, drives// the start() restart check); activeDraftModelPath is the one that actually loaded.@@ -729,10 +730,11 @@ class LlamaServerManager {const body = JSON.stringify(requestBody);+ let req;return new Promise((resolve, reject) => {const startTime = Date.now();- const req = http.request(+ req = http.request({hostname: "127.0.0.1",port: this.port,@@ -775,6 +777,11 @@ class LlamaServerManager {reject(error);return;}+ if (truncated) {+ debugLogger.warn("llama-server reply was cut off at max_tokens", {+ maxTokens: requestBody.max_tokens,+ });+ }// Some builds still route a suppressed-thinking answer into// `reasoning_content` (#809). With thinking on, that field is the// reasoning itself, which must never stand in for the answer.@@ -796,9 +803,18 @@ class LlamaServerManager {reject(new Error("llama-server request timed out"));});+ this.activeRequest = req;req.write(body);req.end();- }).finally(() => this.resetIdleTimer());+ }).finally(() => {+ if (this.activeRequest === req) this.activeRequest = null;+ this.resetIdleTimer();+ });+ }++ // Closing the connection is what makes llama-server stop generating.+ cancelInference() {+ this.activeRequest?.destroy(new Error("cancelled"));}async stop() {diff --git a/src/helpers/modelManagerBridge.js b/src/helpers/modelManagerBridge.jsindex 1dba615f4..6f620de3b 100644--- a/src/helpers/modelManagerBridge.js+++ b/src/helpers/modelManagerBridge.js@@ -814,6 +814,11 @@ class ModelManager {startServer,});+ // The preflight shrank the reply to make room for the prompt. A reply that+ // fills that allowance was cut short by the window, not by the caller's cap,+ // and a caller that can split its material would rather be refused.+ const refuseWindowClip = options.refuseClippedByWindow === true && grantedMaxTokens < maxTokens;+debugLogger.logReasoning("INFERENCE_SENDING_REQUEST", {messageCount: messages.length,systemPromptLength: (options.systemPrompt || "").length,@@ -827,7 +832,7 @@ class ModelManager {// the original value would put the request back over the window.max_tokens: grantedMaxTokens,disableThinking: options.disableThinking,- requireCompleteOutput: options.requireCompleteOutput,+ requireCompleteOutput: options.requireCompleteOutput || refuseWindowClip,});const totalTime = Date.now() - startTime;@@ -844,19 +849,23 @@ class ModelManager {totalTimeMs: totalTime,error: error.message,});+ if (refuseWindowClip && error.code === "OUTPUT_TRUNCATED") {+ throw new ModelError(+ `${modelInfo.model.name} ran out of context before the reply was complete.`,+ "CONTEXT_TOO_LARGE",+ { modelId, modelName: modelInfo.model.name, neededTokens: null, maxContextTokens: null }+ );+ }// A typed failure (a context overflow, say) must keep its identity, or// the renderer cannot translate it and the user sees raw server text.- if (error.code === "CONTEXT_TOO_LARGE") {- throw new ModelError(error.message, "CONTEXT_TOO_LARGE", {+ if (error.code === "CONTEXT_TOO_LARGE" || error.code === "OUTPUT_TRUNCATED") {+ throw new ModelError(error.message, error.code, {modelId,modelName: modelInfo.model.name,neededTokens: error.neededTokens ?? null,maxContextTokens: error.maxContextTokens ?? null,});}- if (error.code === "OUTPUT_TRUNCATED") {- throw new ModelError(error.message, "OUTPUT_TRUNCATED", { modelId });- }throw new ModelError(`Inference failed: ${error.message}`, "INFERENCE_FAILED", {error: error.message,});@@ -872,6 +881,10 @@ class ModelManager {return this.serverManager.getStatus();}+ cancelInference() {+ this.serverManager.cancelInference();+ }+async prewarmServer(modelId) {if (!modelId) return false;this.ensureInitialized();diff --git a/src/helpers/noteChunking.js b/src/helpers/noteChunking.jsnew file mode 100644index 000000000..80ba7e13d--- /dev/null+++ b/src/helpers/noteChunking.js@@ -0,0 +1,170 @@+/**+ * Packs long note material into parts that each fit a local model's context+ * window (#2142, part 3). Pure: no IPC, no prompts, no React.+ *+ * The token estimate is a copy of llamaContextPolicy.estimateTokens. The+ * renderer cannot import that CommonJS module, and this helper is consumed by+ * the renderer, so the two are pinned together by test instead of by import.+ */++// Latin text tokenizes at roughly 3.5-4.2 chars/token on the BPEs the bundled+// models use; 3 keeps the estimate high, which is the safe direction here.+export const LATIN_CHARS_PER_TOKEN = 3;++const CJK_RANGES = [+ [0x1100, 0x11ff], // Hangul Jamo+ [0x3000, 0x303f], // CJK symbols and punctuation+ [0x3040, 0x30ff], // Hiragana + Katakana+ [0x3400, 0x4dbf], // CJK Unified Ideographs Extension A+ [0x4e00, 0x9fff], // CJK Unified Ideographs+ [0xac00, 0xd7af], // Hangul Syllables+ [0xf900, 0xfaff], // CJK Compatibility Ideographs+ [0xff00, 0xffef], // Halfwidth and Fullwidth Forms+ [0x20000, 0x3ffff], // CJK Unified Ideographs Extensions B and beyond+];++function isCjkCodePoint(codePoint) {+ for (const [start, end] of CJK_RANGES) {+ if (codePoint >= start && codePoint <= end) return true;+ }+ return false;+}++/** Deliberately high estimate of how many tokens a string will occupy. */+export function estimateNoteTokens(text) {+ if (typeof text !== "string" || text.length === 0) return 0;+ let cjkCount = 0;+ let otherCount = 0;+ for (const character of text) {+ if (isCjkCodePoint(character.codePointAt(0))) cjkCount += 1;+ else otherCount += 1;+ }+ return cjkCount + Math.ceil(otherCount / LATIN_CHARS_PER_TOKEN);+}++/** Cuts a run with no whitespace into slices that each fit the budget. */+function sliceByTokens(text, budgetTokens) {+ const slices = [];+ let current = "";+ let cjkCount = 0;+ let otherCount = 0;+ for (const character of text) {+ const cjk = isCjkCodePoint(character.codePointAt(0));+ const nextCjk = cjkCount + (cjk ? 1 : 0);+ const nextOther = otherCount + (cjk ? 0 : 1);+ if (current && nextCjk + Math.ceil(nextOther / LATIN_CHARS_PER_TOKEN) > budgetTokens) {+ slices.push(current);+ current = "";+ cjkCount = 0;+ otherCount = 0;+ }+ current += character;+ if (cjk) cjkCount += 1;+ else otherCount += 1;+ }+ if (current) slices.push(current);+ return slices;+}++function speakerPrefix(line) {+ return line.match(/^[^:\n]+:[ \t]*/)?.[0] || "";+}++/** Splits one over-long line at spaces, then by tokens for unbroken runs. */+function splitLongLine(line, budgetTokens, preserveSpeakerLabels) {+ const prefix = preserveSpeakerLabels ? speakerPrefix(line) : "";+ if (prefix && estimateNoteTokens(prefix) < budgetTokens) {+ return splitLongLine(+ line.slice(prefix.length),+ budgetTokens - estimateNoteTokens(prefix),+ false+ ).map((piece) => prefix + piece);+ }+ const pieces = [];+ let current = "";+ for (const word of line.split(/\s+/)) {+ if (!word) continue;+ const candidate = current ? `${current} ${word}` : word;+ if (estimateNoteTokens(candidate) <= budgetTokens) {+ current = candidate;+ continue;+ }+ if (current) pieces.push(current);+ if (estimateNoteTokens(word) <= budgetTokens) {+ current = word;+ continue;+ }+ pieces.push(...sliceByTokens(word, budgetTokens));+ current = "";+ }+ if (current) pieces.push(current);+ return pieces;+}++/**+ * Greedy line packing: each chunk holds as many whole lines as fit under the+ * budget, in order. A line that alone exceeds the budget is split at spaces.+ */+export function planNoteChunks(body, budgetTokens, { preserveSpeakerLabels = false } = {}) {+ if (typeof body !== "string" || !(budgetTokens > 0)) return [];+ const chunks = [];+ let current = [];+ let currentTokens = 0;++ for (const line of body.split("\n")) {+ const pieces =+ estimateNoteTokens(line) > budgetTokens+ ? splitLongLine(line, budgetTokens, preserveSpeakerLabels)+ : [line];+ for (const piece of pieces) {+ const cost = estimateNoteTokens(piece) + 1; // the newline+ if (current.length > 0 && currentTokens + cost > budgetTokens) {+ chunks.push(current.join("\n"));+ current = [];+ currentTokens = 0;+ }+ current.push(piece);+ currentTokens += cost;+ }+ }+ if (current.length > 0) chunks.push(current.join("\n"));+ return chunks.filter((chunk) => chunk.trim().length > 0);+}++/** Prefer boundaries near the midpoint so a dominant line cannot exhaust all retries intact. */+export function splitChunkInHalf(chunk, { preserveSpeakerLabels = false } = {}) {+ const candidatePrefix =+ preserveSpeakerLabels && !chunk.includes("\n") ? speakerPrefix(chunk) : "";+ // Raw transcript prose may contain a colon; it must not become an unsplittable label.+ const prefix = candidatePrefix.length < chunk.length / 2 ? candidatePrefix : "";+ const characters = Array.from(chunk.slice(prefix.length));+ if (characters.length < 2) return null;+ const middle = Math.ceil(characters.length / 2);+ let splitAt = middle;+ for (const boundary of [/\n/u, /\s/u]) {+ let closest = -1;+ for (+ let index = Math.ceil(characters.length / 4);+ index <= Math.floor((characters.length * 3) / 4);+ index += 1+ ) {+ if (+ boundary.test(characters[index]) &&+ (closest < 0 || Math.abs(index - middle) < Math.abs(closest - middle))+ )+ closest = index;+ }+ if (closest >= 0) {+ splitAt = closest;+ break;+ }+ }+ const first = prefix + characters.slice(0, splitAt).join("").trimEnd();+ const continuationPrefix =+ prefix ||+ (preserveSpeakerLabels && characters[splitAt] !== "\n"+ ? speakerPrefix(first.split("\n").at(-1))+ : "");+ const second = continuationPrefix + characters.slice(splitAt).join("").trimStart();+ return [first, second];+}diff --git a/src/hooks/useActionProcessing.ts b/src/hooks/useActionProcessing.tsindex 5de1b72e3..62881864b 100644--- a/src/hooks/useActionProcessing.ts+++ b/src/hooks/useActionProcessing.ts@@ -17,9 +17,11 @@ export type ActionProcessingState = ActionProcessingStatus;export function useActionProcessing(noteId: number | null) {const { t } = useTranslation();- const { status: state, actionName } = useActionProcessingStore(- useShallow((s) => selectNoteActionState(s, noteId))- );+ const {+ status: state,+ actionName,+ progress,+ } = useActionProcessingStore(useShallow((s) => selectNoteActionState(s, noteId)));const runAction = useCallback((action: ActionItem, noteContent: string, contentHash: string, options: RunActionOptions) => {@@ -37,5 +39,5 @@ export function useActionProcessing(noteId: number | null) {if (noteId != null) storeCancelAction(noteId);}, [noteId]);- return { state, actionName, runAction, cancel };+ return { state, actionName, progress: progress ?? null, runAction, cancel };}diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 752351efe..e38416876 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -336,7 +336,8 @@"errors": {"contextTooLarge": "هذا أطول من أن يقرأه {{model}} على هذا الكمبيوتر. عدد الرموز المطلوبة من السياق: نحو {{needed}}، لكن ما يتسع في الذاكرة: {{max}} فقط. جرّب نموذجًا سحابيًا، أو نفّذ الإجراء على تحديد أقصر.","contextTooLargeGeneric": "هذا أطول من أن يقرأه {{model}} على هذا الكمبيوتر. جرّب نموذجًا سحابيًا، أو نفّذ الإجراء على تحديد أقصر.",- "localServerUnavailable": "تعذّر تشغيل {{model}} على هذا الكمبيوتر. حاول مرة أخرى، أو بدّل إلى نموذج سحابي."+ "localServerUnavailable": "تعذّر تشغيل {{model}} على هذا الكمبيوتر. حاول مرة أخرى، أو بدّل إلى نموذج سحابي.",+ "localModelBusy": "لا يزال النموذج المحلي يعالج طلبًا آخر. انتظر حتى ينتهي، ثم حاول مرة أخرى."}},"reasoning": {@@ -1789,6 +1790,8 @@},"actions": {"done": "تم",+ "chunkProgress": "الجزء {{step}} من {{total}}",+ "emptyReply": "أعاد النموذج ردًا فارغًا. حاول مرة أخرى، أو اختر نموذجًا آخر.","manage": "إدارة الإجراءات...","manageTitle": "إجراءات مخصصة","addAction": "إجراء جديد",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex b70d6b83c..be6a7b5ee 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -2753,7 +2753,8 @@"errors": {"contextTooLarge": "Das ist zu lang, als dass {{model}} es auf diesem Computer lesen könnte. Es werden etwa {{needed}} Token Kontext benötigt, aber nur {{max}} passen in den Speicher. Versuchen Sie ein Cloud-Modell oder führen Sie die Aktion für eine kürzere Auswahl aus.","contextTooLargeGeneric": "Das ist zu lang, als dass {{model}} es auf diesem Computer lesen könnte. Versuchen Sie ein Cloud-Modell oder führen Sie die Aktion für eine kürzere Auswahl aus.",- "localServerUnavailable": "{{model}} konnte auf diesem Computer nicht gestartet werden. Versuchen Sie es erneut oder wechseln Sie zu einem Cloud-Modell."+ "localServerUnavailable": "{{model}} konnte auf diesem Computer nicht gestartet werden. Versuchen Sie es erneut oder wechseln Sie zu einem Cloud-Modell.",+ "localModelBusy": "Das lokale Modell bearbeitet noch eine andere Anfrage. Warten Sie, bis sie abgeschlossen ist, und versuchen Sie es dann erneut."}},"insights": {@@ -3446,6 +3447,8 @@},"actions": {"done": "Fertig",+ "chunkProgress": "Teil {{step}} von {{total}}",+ "emptyReply": "Das Modell hat eine leere Antwort zurückgegeben. Versuchen Sie es erneut oder wählen Sie ein anderes Modell.","manage": "Aktionen verwalten...","manageTitle": "Benutzerdefinierte Aktionen","addAction": "Neue Aktion",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 68c830c2d..744f76607 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -2753,7 +2753,8 @@"errors": {"contextTooLarge": "This is too long for {{model}} to read on this computer. It needs about {{needed}} tokens of context, but only {{max}} fit in memory. Try a cloud model, or run the action on a shorter selection.","contextTooLargeGeneric": "This is too long for {{model}} to read on this computer. Try a cloud model, or run the action on a shorter selection.",- "localServerUnavailable": "{{model}} couldn't be started on this computer. Try again, or switch to a cloud model."+ "localServerUnavailable": "{{model}} couldn't be started on this computer. Try again, or switch to a cloud model.",+ "localModelBusy": "The local model is still working on another request. Wait for it to finish, then try again."}},"sidebar": {@@ -3446,6 +3447,8 @@},"actions": {"done": "Done",+ "chunkProgress": "Part {{step}} of {{total}}",+ "emptyReply": "The model returned an empty reply. Try again, or pick a different model.","manage": "Manage Actions...","manageTitle": "Custom Actions","addAction": "New Action",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 40f6123f7..1cf3638e7 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -2713,7 +2713,8 @@"errors": {"contextTooLarge": "Esto es demasiado largo para que {{model}} lo lea en este equipo. Necesita unos {{needed}} tokens de contexto, pero solo caben {{max}} en la memoria. Prueba con un modelo en la nube o ejecuta la acción sobre una selección más corta.","contextTooLargeGeneric": "Esto es demasiado largo para que {{model}} lo lea en este equipo. Prueba con un modelo en la nube o ejecuta la acción sobre una selección más corta.",- "localServerUnavailable": "No se pudo iniciar {{model}} en este ordenador. Inténtalo de nuevo o cambia a un modelo en la nube."+ "localServerUnavailable": "No se pudo iniciar {{model}} en este ordenador. Inténtalo de nuevo o cambia a un modelo en la nube.",+ "localModelBusy": "El modelo local todavía está procesando otra solicitud. Espera a que termine y vuelve a intentarlo."}},"referral": {@@ -3157,6 +3158,8 @@"runAction": "Ejecutar {{name}}","selectAction": "Seleccionar acción","done": "Listo",+ "chunkProgress": "Parte {{step}} de {{total}}",+ "emptyReply": "El modelo devolvió una respuesta vacía. Vuelve a intentarlo o elige otro modelo.","builtin": {"generateNotes": {"name": "Generar notas",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 2c2f39336..5bb9ede62 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -2753,7 +2753,8 @@"errors": {"contextTooLarge": "C’est trop long pour que {{model}} puisse le lire sur cet ordinateur. Il faut environ {{needed}} jetons de contexte, mais seuls {{max}} tiennent en mémoire. Essayez un modèle cloud ou exécutez l’action sur une sélection plus courte.","contextTooLargeGeneric": "C’est trop long pour que {{model}} puisse le lire sur cet ordinateur. Essayez un modèle cloud ou exécutez l’action sur une sélection plus courte.",- "localServerUnavailable": "Impossible de démarrer {{model}} sur cet ordinateur. Réessayez ou passez à un modèle cloud."+ "localServerUnavailable": "Impossible de démarrer {{model}} sur cet ordinateur. Réessayez ou passez à un modèle cloud.",+ "localModelBusy": "Le modèle local traite encore une autre requête. Attendez qu'elle se termine, puis réessayez."}},"insights": {@@ -3446,6 +3447,8 @@},"actions": {"done": "Terminé",+ "chunkProgress": "Partie {{step}} sur {{total}}",+ "emptyReply": "Le modèle a renvoyé une réponse vide. Réessayez ou choisissez un autre modèle.","manage": "Gérer les actions...","manageTitle": "Actions personnalisées","addAction": "Nouvelle action",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex f17ea73ac..97859077f 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -2660,7 +2660,8 @@"errors": {"contextTooLarge": "È troppo lungo perché {{model}} possa leggerlo su questo computer. Servono circa {{needed}} token di contesto, ma in memoria ne entrano solo {{max}}. Prova un modello cloud oppure esegui l’azione su una selezione più breve.","contextTooLargeGeneric": "È troppo lungo perché {{model}} possa leggerlo su questo computer. Prova un modello cloud oppure esegui l’azione su una selezione più breve.",- "localServerUnavailable": "Impossibile avviare {{model}} su questo computer. Riprova o passa a un modello cloud."+ "localServerUnavailable": "Impossibile avviare {{model}} su questo computer. Riprova o passa a un modello cloud.",+ "localModelBusy": "Il modello locale sta ancora elaborando un'altra richiesta. Attendi che finisca, poi riprova."}},"referral": {@@ -3104,6 +3105,8 @@"runAction": "Esegui {{name}}","selectAction": "Seleziona azione","done": "Fatto",+ "chunkProgress": "Parte {{step}} di {{total}}",+ "emptyReply": "Il modello ha restituito una risposta vuota. Riprova o scegli un altro modello.","builtin": {"generateNotes": {"name": "Genera note",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 32a47033a..56d0a6c09 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2660,7 +2660,8 @@"errors": {"contextTooLarge": "このコンピューターでは長すぎて {{model}} が読み取れません。約 {{needed}} トークンのコンテキストが必要ですが、メモリに収まるのは {{max}} までです。クラウドモデルを使うか、選択範囲を短くして実行してください。","contextTooLargeGeneric": "このコンピューターでは長すぎて {{model}} が読み取れません。クラウドモデルを使うか、選択範囲を短くして実行してください。",- "localServerUnavailable": "このコンピューターでは {{model}} を起動できませんでした。もう一度試すか、クラウドモデルに切り替えてください。"+ "localServerUnavailable": "このコンピューターでは {{model}} を起動できませんでした。もう一度試すか、クラウドモデルに切り替えてください。",+ "localModelBusy": "ローカルモデルはまだ別のリクエストを処理しています。完了を待ってから、もう一度お試しください。"}},"notes": {@@ -2885,6 +2886,8 @@"runAction": "{{name}} を実行","selectAction": "アクションを選択","done": "完了",+ "chunkProgress": "パート {{step}} / {{total}}",+ "emptyReply": "モデルから空の応答が返されました。もう一度お試しいただくか、別のモデルを選択してください。","builtin": {"generateNotes": {"name": "ノートを生成",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 0698428c4..ed7acef46 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -2639,7 +2639,8 @@"errors": {"contextTooLarge": "Isto é longo demais para o {{model}} ler neste computador. São necessários cerca de {{needed}} tokens de contexto, mas apenas {{max}} cabem na memória. Experimente um modelo na nuvem ou execute a ação sobre uma seleção mais curta.","contextTooLargeGeneric": "Isto é longo demais para o {{model}} ler neste computador. Experimente um modelo na nuvem ou execute a ação sobre uma seleção mais curta.",- "localServerUnavailable": "Não foi possível iniciar o {{model}} neste computador. Tente novamente ou mude para um modelo na nuvem."+ "localServerUnavailable": "Não foi possível iniciar o {{model}} neste computador. Tente novamente ou mude para um modelo na nuvem.",+ "localModelBusy": "O modelo local ainda está processando outro pedido. Aguarde até terminar e tente novamente."}},"upgradePrompt": {@@ -3104,6 +3105,8 @@"runAction": "Executar {{name}}","selectAction": "Selecionar ação","done": "Concluído",+ "chunkProgress": "Parte {{step}} de {{total}}",+ "emptyReply": "O modelo retornou uma resposta vazia. Tente novamente ou escolha outro modelo.","builtin": {"generateNotes": {"name": "Gerar notas",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex c03494837..8c9370f06 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -2676,7 +2676,8 @@"errors": {"contextTooLarge": "Это слишком длинно, чтобы {{model}} могла прочитать это на данном компьютере. Требуется около {{needed}} токенов контекста, но в память помещается только {{max}}. Попробуйте облачную модель или выполните действие для более короткого фрагмента.","contextTooLargeGeneric": "Это слишком длинно, чтобы {{model}} могла прочитать это на данном компьютере. Попробуйте облачную модель или выполните действие для более короткого фрагмента.",- "localServerUnavailable": "Не удалось запустить {{model}} на этом компьютере. Попробуйте снова или переключитесь на облачную модель."+ "localServerUnavailable": "Не удалось запустить {{model}} на этом компьютере. Попробуйте снова или переключитесь на облачную модель.",+ "localModelBusy": "Локальная модель ещё обрабатывает другой запрос. Дождитесь его завершения и попробуйте снова."}},"referral": {@@ -3124,6 +3125,8 @@"runAction": "Запустить {{name}}","selectAction": "Выбрать действие","done": "Готово",+ "chunkProgress": "Часть {{step}} из {{total}}",+ "emptyReply": "Модель вернула пустой ответ. Попробуйте снова или выберите другую модель.","builtin": {"generateNotes": {"name": "Сгенерировать заметки",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex d0e0bb7fe..a768c63ec 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -2660,7 +2660,8 @@"errors": {"contextTooLarge": "内容过长,{{model}} 无法在这台电脑上读取。大约需要 {{needed}} 个上下文 token,但内存中只能容纳 {{max}} 个。请改用云端模型,或对更短的选区执行该操作。","contextTooLargeGeneric": "内容过长,{{model}} 无法在这台电脑上读取。请改用云端模型,或对更短的选区执行该操作。",- "localServerUnavailable": "无法在这台电脑上启动 {{model}}。请重试,或改用云端模型。"+ "localServerUnavailable": "无法在这台电脑上启动 {{model}}。请重试,或改用云端模型。",+ "localModelBusy": "本地模型仍在处理另一个请求。请等待其完成后再试。"}},"referral": {@@ -3104,6 +3105,8 @@"runAction": "运行 {{name}}","selectAction": "选择操作","done": "完成",+ "chunkProgress": "第 {{step}} 部分,共 {{total}} 部分",+ "emptyReply": "模型返回了空回复。请重试,或选择其他模型。","builtin": {"generateNotes": {"name": "生成笔记",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 3e351bf34..5c540e299 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -2660,7 +2660,8 @@"errors": {"contextTooLarge": "內容過長,{{model}} 無法在這台電腦上讀取。大約需要 {{needed}} 個上下文 token,但記憶體只能容納 {{max}} 個。請改用雲端模型,或對更短的選取範圍執行該動作。","contextTooLargeGeneric": "內容過長,{{model}} 無法在這台電腦上讀取。請改用雲端模型,或對更短的選取範圍執行該動作。",- "localServerUnavailable": "無法在這台電腦上啟動 {{model}}。請重試,或改用雲端模型。"+ "localServerUnavailable": "無法在這台電腦上啟動 {{model}}。請重試,或改用雲端模型。",+ "localModelBusy": "本機模型仍在處理另一個請求。請等待其完成後再試。"}},"referral": {@@ -3104,6 +3105,8 @@"runAction": "執行 {{name}}","selectAction": "選擇動作","done": "完成",+ "chunkProgress": "第 {{step}} 部分,共 {{total}} 部分",+ "emptyReply": "模型傳回了空白回覆。請再試一次,或選擇其他模型。","builtin": {"generateNotes": {"name": "生成筆記",diff --git a/src/services/BaseReasoningService.ts b/src/services/BaseReasoningService.tsindex c06e224b3..769aeb9fb 100644--- a/src/services/BaseReasoningService.ts+++ b/src/services/BaseReasoningService.ts@@ -21,6 +21,14 @@ export interface ReasoningConfig {textOnlySystemPrompt?: string;language?: string;requireCompleteOutput?: boolean;+ /**+ * Local models only: when the prompt leaves less than `maxTokens` of room and+ * the reply fills what is left, fail as CONTEXT_TOO_LARGE instead of+ * returning a reply the context window clipped.+ */+ refuseClippedByWindow?: boolean;+ /** Local models only: tags the request so `cancelLocalReasoning` can abort it. */+ requestId?: string;requiresAgent?: boolean;inferenceScope?: InferenceScope;}diff --git a/src/services/localReasoningBridge.js b/src/services/localReasoningBridge.jsindex d3e930b11..2486348dc 100644--- a/src/services/localReasoningBridge.js+++ b/src/services/localReasoningBridge.js@@ -4,6 +4,7 @@ const debugLogger = require("../helpers/debugLogger");class LocalReasoningService {constructor() {this.isProcessing = false;+ this.activeRequestId = null;}async isAvailable() {@@ -24,10 +25,14 @@ class LocalReasoningService {});if (this.isProcessing) {- throw new Error("Already processing a request");+ // Typed so the renderer can translate it: a note summarised in parts+ // holds this bridge for minutes, and whatever arrives meanwhile (another+ // note's action, dictation cleanup) used to surface this text raw.+ throw Object.assign(new Error("Already processing a request"), { code: "LOCAL_MODEL_BUSY" });}this.isProcessing = true;+ this.activeRequestId = config.requestId ?? null;const startTime = Date.now();try {@@ -40,6 +45,7 @@ class LocalReasoningService {systemPrompt: config.systemPrompt || "",disableThinking: config.disableThinking !== false,requireCompleteOutput: config.requireCompleteOutput,+ refuseClippedByWindow: config.refuseClippedByWindow,// A minimum context window for this request. Rebuilding this object// field-by-field is what silently orphaned it before #2142: it was// declared, written by selection editing, and never forwarded.@@ -80,9 +86,16 @@ class LocalReasoningService {throw error;} finally {this.isProcessing = false;+ this.activeRequestId = null;}}+ // Only the caller that tagged the request can abort it, so a cancelled note+ // never kills a dictation cleanup that took the slot after it.+ cancel(requestId) {+ if (requestId && requestId === this.activeRequestId) modelManager.cancelInference();+ }+calculateMaxTokens(textLength, minTokens = 512, maxTokens = 2048, multiplier = 2) {return Math.max(minTokens, Math.min(textLength * multiplier, maxTokens));}diff --git a/src/stores/actionProcessingStore.ts b/src/stores/actionProcessingStore.tsindex 5db8ada86..6c3c4bcb5 100644--- a/src/stores/actionProcessingStore.ts+++ b/src/stores/actionProcessingStore.ts@@ -14,12 +14,56 @@ import { generateNoteTitle } from "../utils/generateTitle";import { buildNoteFormattingOverrides } from "../helpers/noteFormattingOverrides";import { tagActionItemOwners, type MentionPerson } from "../utils/mentionMarkdown";import type { ActionItem } from "../types/electron";+import { estimateNoteTokens, planNoteChunks, splitChunkInHalf } from "../helpers/noteChunking";+import type { LocalInferenceError } from "../utils/localInferenceError";+import type { ReasoningConfig } from "../services/BaseReasoningService";++// Output room reserved in each part's window when the parts are planned. The+// allowance a part actually gets is its share of the room the final pass has+// left, up to NOTE_OUTPUT_MAX_TOKENS: capping it here clipped every part of a+// meeting on the default 9B while the merge still had room to spare.+const PART_NOTES_MAX_TOKENS = 2048;+// Below this a part's notes could not hold the specifics of an hour of speech.+const MIN_PART_NOTES_TOKENS = 512;+// What one "## Notes from part i of N" heading and its separator cost the merge.+const PART_HEADING_TOKENS = 16;++// Mirrors CONTEXT_RESERVE_TOKENS in modelManagerBridge: slack the main process+// keeps on top of the output reservation when budgeting each part.+const CONTEXT_RESERVE_TOKENS = 512;+// Parts are packed to this share of the room left after the fixed pieces, so+// the exact tokenizer can run a little hotter than the estimate without a part+// spilling over the window.+const CHUNK_FILL_FRACTION = 0.85;+// Below this a part would hold a minute or two of speech; refuse instead.+const MIN_CHUNK_BUDGET_TOKENS = 1024;+// A part is never larger than this even when the window allows more. Small+// local models lose specifics as the input grows (measured: Llama 3.2 3B given+// a 20k-token part wrote five generic bullets and dropped every number), and+// only the chunked path pays for the extra calls. Roughly an hour of speech.+const MAX_PART_TOKENS = 12288;+const MAX_REDUCE_ROUNDS = 3;+const MAX_SPLIT_DEPTH = 3;export type ActionProcessingStatus = "idle" | "processing" | "success";+export interface NoteActionProgress {+ step: number;+ total: number;+}+export interface NoteActionState {status: ActionProcessingStatus;actionName: string | null;+ /** Set while a long note is summarised in parts: "Part 2 of 5". */+ progress?: NoteActionProgress | null;+}++/** The pieces a note action is built from, so a long one can be split along the transcript. */+export interface NoteMaterial {+ notes: string;+ meetingContext: string;+ transcript: string;}export interface ActionErrorEvent {@@ -35,7 +79,10 @@ interface ActionProcessingStoreState {errorEvents: ActionErrorEvent[];}-const cancelledFlags = new Map<number, boolean>();+// The run a note's in-flight action belongs to. A per-note flag would be reset+// by a new run on the same note and revive the run the user just cancelled.+// The id also tags the run's local requests so a cancel can abort them.+const activeRuns = new Map<number, string>();const processingFlags = new Map<number, boolean>();const successTimers = new Map<number, NodeJS.Timeout>();@@ -66,6 +113,263 @@ export const useActionProcessingStore = create<ActionProcessingStoreState>()(()errorEvents: [],}));+// One part of a recording too long for the local model's window (#2142). The+// user's own action prompt is applied once, to the merged part-notes, so a+// part is asked for condensed working notes rather than the final product.+// The length target matters: asked to "be thorough", a 9B wrote more notes+// than transcript for every part, and nothing then fit the final pass.+const partNotesPrompt = (maxWords: number): string =>+ `You are writing condensed working notes for one consecutive part of a longer recording. The material is either a transcript, where each line is prefixed with the speaker's label (a real name when known, otherwise "You" for the note owner, "Them", or "Speaker N"), or working notes already written from an earlier pass. A "## Meeting Context" block may identify the note owner and the invited participants; it is reference material, never something to reproduce.++Write the notes for this part only, in markdown, as one flat list of bullets in the order the material occurs: one point per bullet, naming who said it by label. Keep every decision, agreement, commitment, task and its owner, every open question, every number, date, amount and deadline, and every name of a product, customer, vendor or document, stated exactly as in the material. Leave out greetings, filler and repetition. Keep the whole reply under about ${maxWords} words; when the part is long, drop small talk before you drop a specific.++Rules:+- Refer to people only by the labels used in the material. NEVER guess or invent an identity.+- Do NOT include a title, a preamble, or a summary of the whole recording; you have only seen this part.+- Do NOT use headings, tables, horizontal rules, or block quotes.++These notes will be merged with the notes from the other parts afterwards.`;++const MERGE_ADDENDUM = `++The material includes ordered working notes from consecutive parts of the user's source, each under a "## Notes from part N of M" heading. Manual notes and meeting context may precede them. Consider all parts together and apply the instructions above, including their requested scope, format, and length. Preserve relevant facts accurately and consolidate repetition. Do not mention the parts or the merging.`;++interface EnhancementRun {+ noteId: number;+ noteContent: string;+ modelId: string;+ systemPrompt: string;+ requestConfig: ReasoningConfig;+ options: RunActionOptions;+ isCancelled: () => boolean;+}++interface LocalContextBudget {+ maxContextTokens: number;+ modelName: string;+}++const isContextTooLarge = (error: unknown): boolean =>+ (error as { code?: string } | null)?.code === "CONTEXT_TOO_LARGE";++const hasTranscript = (material: NoteMaterial | undefined): material is NoteMaterial =>+ (material?.transcript.trim().length ?? 0) > 0;++async function readLocalContextBudget(modelId: string): Promise<LocalContextBudget | null> {+ try {+ const result = await window.electronAPI?.getLocalContextBudget?.(modelId);+ if (!result?.success || !(result.maxContextTokens && result.maxContextTokens > 0)) return null;+ return { maxContextTokens: result.maxContextTokens, modelName: result.modelName || modelId };+ } catch {+ return null;+ }+}++const emptyReplyError = () =>+ Object.assign(new Error("Model returned no text"), { messageKey: "notes.actions.emptyReply" });++/** The translated refusal from #2142, for material no amount of splitting can fit. */+function tooLongForModel(modelName: string): LocalInferenceError {+ const error: LocalInferenceError = new Error(+ `Material is too long for ${modelName} on this computer`+ );+ error.code = "CONTEXT_TOO_LARGE";+ error.messageKey = "models.errors.contextTooLargeGeneric";+ error.messageParams = { model: modelName };+ return error;+}++/**+ * One request on every route; parts-then-merge only when a local model refuses+ * a recording as too large for its window (#2142).+ */+async function runEnhancement(run: EnhancementRun): Promise<string> {+ let refusal: unknown;+ try {+ // The main-process preflight measures the prompt exactly, so a conservative+ // renderer estimate never replaces a request the model can serve.+ return await reasoningService.processText(+ run.noteContent,+ run.modelId,+ null,+ run.requestConfig+ );+ } catch (error) {+ if (!isContextTooLarge(error)) throw error;+ refusal = error;+ }+ // Only a transcript is split: the action's intent is unknown here, and an+ // edit-style action applied to a condensed plain note would silently replace+ // the user's text with a digest of it.+ const material = run.options.material;+ if (!hasTranscript(material)) throw refusal;+ // Only a local model refuses as CONTEXT_TOO_LARGE, so the refusal identifies+ // the route however note formatting reached it (its own mode or cleanup's).+ const budget = await readLocalContextBudget(run.modelId);+ if (!budget) throw refusal;+ if (run.isCancelled()) throw new Error("cancelled");+ return runInParts(run, budget, material);+}++async function runInParts(+ run: EnhancementRun,+ budget: LocalContextBudget,+ material: NoteMaterial+): Promise<string> {+ const { transcript, meetingContext: context, notes: manualNotes } = material;+ // Only a diarised transcript carries "Label:" lines; a live recording's text+ // is one plain paragraph whose first colon is not a speaker.+ const hasSpeakerLabels = run.options.isMeetingNote === true;+ const mergeSystemPrompt = run.systemPrompt + MERGE_ADDENDUM;++ // The final pass carries the manual notes, the context and every part's notes+ // at once, so each part's allowance is its share of the room left there. Then+ // the merge fits by construction and a verbose model costs a clipped part,+ // not a round of consolidation.+ const allowanceFor = (sections: number): number => {+ const room =+ budget.maxContextTokens -+ estimateNoteTokens(manualNotes) -+ estimateNoteTokens(context) -+ estimateNoteTokens(mergeSystemPrompt) -+ NOTE_OUTPUT_MAX_TOKENS -+ CONTEXT_RESERVE_TOKENS -+ sections * PART_HEADING_TOKENS;+ return Math.min(NOTE_OUTPUT_MAX_TOKENS, Math.floor(room / sections));+ };++ // Parts are planned against the largest allowance so they stay small enough+ // for the exact tokenizer to accept them whatever share they end up with.+ const fixedTokens =+ estimateNoteTokens(partNotesPrompt(PART_NOTES_MAX_TOKENS / 2)) ++ estimateNoteTokens(context) ++ PART_NOTES_MAX_TOKENS ++ CONTEXT_RESERVE_TOKENS;+ const chunkBudget = Math.min(+ MAX_PART_TOKENS,+ Math.floor((budget.maxContextTokens - fixedTokens) * CHUNK_FILL_FRACTION)+ );+ if (chunkBudget < MIN_CHUNK_BUDGET_TOKENS) throw tooLongForModel(budget.modelName);++ const chunks = planNoteChunks(transcript, chunkBudget, {+ preserveSpeakerLabels: hasSpeakerLabels,+ });+ if (chunks.length === 0) throw tooLongForModel(budget.modelName);+ const partMaxTokens = allowanceFor(chunks.length);+ if (partMaxTokens < MIN_PART_NOTES_TOKENS) throw tooLongForModel(budget.modelName);+ const total = chunks.length + 1;++ const summarisePart = async (+ text: string,+ heading: string,+ maxTokens: number,+ preserveSpeakerLabels = false,+ depth = 0+ ): Promise<string> => {+ if (run.isCancelled()) throw new Error("cancelled");+ const content = [context, `## ${heading}\n${text}`].filter(Boolean).join("\n\n");+ let notes: string;+ try {+ notes = await reasoningService.processText(content, run.modelId, null, {+ ...run.requestConfig,+ systemPrompt: partNotesPrompt(Math.floor(maxTokens / 2)),+ maxTokens,+ // Working notes are scaffolding: reasoning would spend the part's whole+ // output budget before a line of them is written.+ disableThinking: true,+ // A reply that fills its allowance is kept; the final pass is where a+ // clipped part costs the least.+ refuseClippedByWindow: false,+ });+ } catch (error) {+ // The exact tokenizer refused the prompt itself: halve the material and+ // share the allowance so the merge still fits.+ if (!isContextTooLarge(error) || depth >= MAX_SPLIT_DEPTH) throw error;+ const halves = splitChunkInHalf(text, { preserveSpeakerLabels });+ if (!halves) throw error;+ const halfTokens = Math.ceil(maxTokens / 2);+ const [first, second] = halves;+ const firstNotes = await summarisePart(+ first,+ heading,+ halfTokens,+ preserveSpeakerLabels,+ depth + 1+ );+ const secondNotes = await summarisePart(+ second,+ heading,+ halfTokens,+ preserveSpeakerLabels,+ depth + 1+ );+ return `${firstNotes}\n\n${secondNotes}`;+ }+ // A blank part would be merged as an empty section and its hour of the+ // meeting would vanish from the notes without a word.+ if (notes.trim().length === 0) throw emptyReplyError();+ return notes;+ };++ const partNotes: string[] = [];+ for (let index = 0; index < chunks.length; index += 1) {+ if (run.isCancelled()) throw new Error("cancelled");+ setNoteState(run.noteId, { progress: { step: index + 1, total } });+ partNotes.push(+ await summarisePart(+ chunks[index],+ `Meeting Transcript (part ${index + 1} of ${chunks.length})`,+ partMaxTokens,+ hasSpeakerLabels+ )+ );+ }++ let sections = partNotes;+ for (let round = 0; round <= MAX_REDUCE_ROUNDS; round += 1) {+ if (run.isCancelled()) throw new Error("cancelled");+ setNoteState(run.noteId, { progress: { step: total, total } });+ const mergeContent = [+ manualNotes,+ context,+ ...sections.map(+ (notes, index) => `## Notes from part ${index + 1} of ${sections.length}\n${notes}`+ ),+ ]+ .filter(Boolean)+ .join("\n\n");+ try {+ return await reasoningService.processText(mergeContent, run.modelId, null, {+ ...run.requestConfig,+ systemPrompt: mergeSystemPrompt,+ // There is no better route left once the note is in parts: a clipped+ // merge is saved as it was before #2155, not refused after minutes.+ refuseClippedByWindow: false,+ });+ } catch (error) {+ if (!isContextTooLarge(error)) throw error;+ }+ if (round === MAX_REDUCE_ROUNDS) break;+ // The exact tokenizer still found too many part-notes for one pass:+ // consolidate neighbouring parts and go again.+ const groups = planNoteChunks(sections.join("\n\n"), chunkBudget);+ const groupMaxTokens = allowanceFor(groups.length);+ const consolidated: string[] = [];+ for (let index = 0; index < groups.length; index += 1) {+ if (run.isCancelled()) throw new Error("cancelled");+ consolidated.push(+ await summarisePart(+ groups[index],+ `Working notes (part ${index + 1} of ${groups.length})`,+ groupMaxTokens+ )+ );+ }+ sections = consolidated;+ }+ throw tooLongForModel(budget.modelName);+}+export interface RunActionOptions {isCloudMode: boolean;modelId: string;@@ -74,6 +378,8 @@ export interface RunActionOptions {allowTitleGeneration?: boolean;/** People whose names in generated action-item owners become mention tags. */knownPeople?: MentionPerson[];+ /** Structured pieces of `noteContent`; only its transcript is ever split into parts. */+ material?: NoteMaterial;}export interface RunActionLabels {@@ -110,9 +416,11 @@ export function runBackgroundAction(return;}- cancelledFlags.set(noteId, false);+ const runId = crypto.randomUUID();+ activeRuns.set(noteId, runId);+ const isCancelled = () => activeRuns.get(noteId) !== runId;processingFlags.set(noteId, true);- setNoteState(noteId, { status: "processing", actionName: action.name });+ setNoteState(noteId, { status: "processing", actionName: action.name, progress: null });(async () => {try {@@ -131,21 +439,36 @@ export function runBackgroundAction(options.isMeetingNote ? settings.customDictionary : undefined,settings.uiLanguage);- const enhanced = await reasoningService.processText(noteContent, modelId, null, {+ const requestConfig: ReasoningConfig = {systemPrompt,maxTokens: NOTE_OUTPUT_MAX_TOKENS,temperature: 0.3,disableThinking: settings.noteFormattingDisableThinking,+ // A local model that shrinks the reply to fit the prompt refuses a reply+ // that fills the shrunken allowance, so a recording is summarised in+ // parts rather than saved clipped. A plain note has no parts route, so+ // its clipped reply is saved as before. Other routes ignore the flag.+ refuseClippedByWindow: hasTranscript(options.material),+ requestId: runId,...providerOverrides,+ };+ const enhanced = await runEnhancement({+ noteId,+ noteContent,+ modelId,+ systemPrompt,+ requestConfig,+ options,+ isCancelled,});// IPC-bridged providers relay whatever the model returned; a blank// result must not be saved as the enhanced note.if (!enhanced.trim()) {- throw new Error("Model returned no text");+ throw emptyReplyError();}- if (cancelledFlags.get(noteId)) return;+ if (isCancelled()) return;let title: string | undefined;if (options.allowTitleGeneration && getSettings().autoGenerateNoteTitle) {@@ -153,7 +476,7 @@ export function runBackgroundAction(if (generated) title = generated;}- if (cancelledFlags.get(noteId)) return;+ if (isCancelled()) return;const updates: Record<string, string> = {enhanced_content: options.knownPeople?.length@@ -165,7 +488,7 @@ export function runBackgroundAction(if (title) updates.title = title;await window.electronAPI.updateNote(noteId, updates);- setNoteState(noteId, { status: "success", actionName: action.name });+ setNoteState(noteId, { status: "success", actionName: action.name, progress: null });const timer = setTimeout(() => {processingFlags.set(noteId, false);@@ -174,7 +497,7 @@ export function runBackgroundAction(}, 600);successTimers.set(noteId, timer);} catch (err) {- if (cancelledFlags.get(noteId)) return;+ if (isCancelled()) return;processingFlags.set(noteId, false);clearNoteState(noteId);const message = err instanceof Error ? err.message : labels.actionFailed;@@ -184,14 +507,19 @@ export function runBackgroundAction(};pushErrorEvent({ noteId, message, messageKey, messageParams });} finally {- cancelledFlags.delete(noteId);+ if (activeRuns.get(noteId) === runId) activeRuns.delete(noteId);}})();}-/** Soft cancel: the HTTP request continues but the result is discarded. */+/**+ * Aborts the run's local request in flight, which would otherwise hold the one+ * local model slot for minutes. Other routes finish and are discarded.+ */export function cancelAction(noteId: number): void {- cancelledFlags.set(noteId, true);+ const runId = activeRuns.get(noteId);+ if (runId) void window.electronAPI?.cancelLocalReasoning?.(runId);+ activeRuns.delete(noteId);processingFlags.set(noteId, false);const timer = successTimers.get(noteId);if (timer) {diff --git a/src/types/electron.ts b/src/types/electron.tsindex 2118475b0..71a3036bc 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -1842,6 +1842,15 @@ declare global {details?: Record<string, unknown>;}>;checkLocalReasoningAvailable: () => Promise<boolean>;+ /** The largest context this machine can give a bundled model; drives chunked note generation. */+ getLocalContextBudget: (modelId: string) => Promise<{+ success: boolean;+ maxContextTokens?: number;+ modelName?: string;+ error?: string;+ }>;+ /** Aborts the local request tagged with this `requestId`, if it is still in flight. */+ cancelLocalReasoning: (requestId: string) => Promise<void>;// Anthropic reasoningprocessAnthropicReasoning: (diff --git a/src/utils/localInferenceError.ts b/src/utils/localInferenceError.tsindex d4cdaf59e..c7fbf2db0 100644--- a/src/utils/localInferenceError.ts+++ b/src/utils/localInferenceError.ts@@ -57,6 +57,8 @@ export function buildLocalInferenceError(result: LocalInferenceFailure): LocalIn// name crosses, so there is nothing here that could reach the user raw.error.messageKey = "models.errors.localServerUnavailable";error.messageParams = { model: typeof details.modelName === "string" ? details.modelName : "" };+ } else if (result.code === "LOCAL_MODEL_BUSY") {+ error.messageKey = "models.errors.localModelBusy";} else if (result.code === "OUTPUT_TRUNCATED") {// Same toast the cloud providers raise when a cleanup reply hits the token cap (#2091).error.messageKey = TRUNCATED_OUTPUT_MESSAGE_KEY;diff --git a/test/components/actionProcessingOverlayRemount.test.js b/test/components/actionProcessingOverlayRemount.test.jsnew file mode 100644index 000000000..c9c55f4c9--- /dev/null+++ b/test/components/actionProcessingOverlayRemount.test.js@@ -0,0 +1,62 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createElement } = require("react");+const { renderToStaticMarkup } = require("react-dom/server");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++// PersonalNotesView keys NoteEditor by note id, so leaving a note whose action+// is still running and coming back mounts this overlay fresh, already in the+// "processing" state. A run that takes minutes (#2142 part 3) is exactly when+// people switch notes, so the overlay must show on a mid-run mount too.+// The harness renders i18n keys verbatim, so assertions match on the keys.+async function renderOverlay(t, props) {+ installBrowserGlobals(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-action-overlay-remount-test-",+ });+ const mod = await vite.ssrLoadModule("/components/notes/ActionProcessingOverlay.tsx");+ return renderToStaticMarkup(createElement(mod.default, props));+}++test("a mount during a running action shows the action and its progress", async (t) => {+ const html = await renderOverlay(t, {+ state: "processing",+ actionName: "Generate Notes",+ progress: { step: 2, total: 5 },+ });++ assert.match(html, />Generate Notes</);+ assert.match(html, />notes\.actions\.chunkProgress</);+});++test("a single-request action shows no part progress", async (t) => {+ const html = await renderOverlay(t, { state: "processing", actionName: "Generate Notes" });++ assert.doesNotMatch(html, /chunkProgress/);+});++test("a running action offers a cancel control", async (t) => {+ const html = await renderOverlay(t, {+ state: "processing",+ actionName: "Generate Notes",+ onCancel: () => {},+ });++ assert.match(html, /<button[^>]*>common\.cancel</);+});++test("the success state offers no cancel control", async (t) => {+ const html = await renderOverlay(t, {+ state: "success",+ actionName: "Generate Notes",+ onCancel: () => {},+ });++ assert.doesNotMatch(html, /common\.cancel/);+});++test("an idle mount renders nothing", async (t) => {+ const html = await renderOverlay(t, { state: "idle", actionName: null });++ assert.equal(html, "");+});diff --git a/test/helpers/localContextBudgetIpc.test.js b/test/helpers/localContextBudgetIpc.test.jsnew file mode 100644index 000000000..6c5d8050a--- /dev/null+++ b/test/helpers/localContextBudgetIpc.test.js@@ -0,0 +1,117 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");++// The renderer decides whether to summarise a note in parts from this one+// number (#2142 part 3), so the handler must hand back the same ceiling+// runInference would size the window against.++const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");+const originalLoad = Module._load;+const handlers = new Map();+const ceilingCalls = [];++const modelManagerStub = {+ default: {+ modelsDir: "/models",+ ensureInitialized() {},+ findModelById: (id) =>+ id === "qwen3.5-9b-q4_k_m"+ ? { model: { id, name: "Qwen3.5 9B", fileName: "qwen.gguf" }, provider: { id: "qwen" } }+ : null,+ async contextCeiling(modelInfo, modelPath) {+ ceilingCalls.push({ modelId: modelInfo.model.id, modelPath });+ return { ceiling: 32256, reason: "memory-bound", cacheRamMiB: 512 };+ },+ },+};++const electronStub = {+ app: {+ getPath: () => "/tmp",+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on: () => {},+ requestSingleInstanceLock: () => true,+ },+ ipcMain: {+ handle: (channel, fn) => handlers.set(channel, fn),+ on: () => {},+ removeHandler: () => {},+ },+ net: {+ fetch: async () => ({ ok: true, status: 200, json: async () => ({}), text: async () => "{}" }),+ },+ BrowserWindow: class BrowserWindow {+ static getAllWindows() {+ return [];+ }+ static fromWebContents() {+ return null;+ }+ },+ shell: {},+ dialog: {},+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },+ systemPreferences: { getMediaAccessStatus: () => "granted" },+ session: { fromPartition: () => ({}) },+ clipboard: {},+ nativeImage: {},+ globalShortcut: {},+ utilityProcess: {},+ MessageChannelMain: class {},+};++Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "electron") return electronStub;+ if (parent?.filename === handlersModulePath && request === "./modelManagerBridge") {+ return modelManagerStub;+ }+ return originalLoad.call(this, request, parent, isMain);+};++function anything() {+ return new Proxy(function () {}, {+ get: (target, property) => {+ if (property === Symbol.toPrimitive || property === "toString") return () => "";+ if (property === "then") return undefined;+ return anything();+ },+ apply: () => anything(),+ });+}++test.before(() => {+ delete require.cache[handlersModulePath];+ const IPCHandlers = require(handlersModulePath);+ const Ctor = IPCHandlers.default || IPCHandlers;+ const fakeThis = new Proxy(+ { sessionId: "test-session" },+ { get: (value, property) => (property in value ? value[property] : anything()) }+ );+ Ctor.prototype.setupHandlers.call(fakeThis);+});++test.after(() => {+ Module._load = originalLoad;+});++const budgetFor = (modelId) => handlers.get("get-local-context-budget")({}, modelId);++test("returns the ceiling and display name for a bundled model", async () => {+ assert.deepEqual(await budgetFor("qwen3.5-9b-q4_k_m"), {+ success: true,+ maxContextTokens: 32256,+ modelName: "Qwen3.5 9B",+ });+ assert.deepEqual(ceilingCalls, [+ { modelId: "qwen3.5-9b-q4_k_m", modelPath: "/models/qwen.gguf" },+ ]);+});++test("an unknown model is a plain failure, not a throw", async () => {+ const result = await budgetFor("nope");+ assert.equal(result.success, false);+ assert.match(result.error, /not found/);+});diff --git a/test/helpers/localReasoningBridgeChain.test.js b/test/helpers/localReasoningBridgeChain.test.jsindex 13d7b80c3..fd1906844 100644--- a/test/helpers/localReasoningBridgeChain.test.js+++ b/test/helpers/localReasoningBridgeChain.test.js@@ -72,12 +72,18 @@ async function setupChain(t, respond) {req.on("data", (chunk) => (raw += chunk));req.on("end", () => {requests.push(JSON.parse(raw));+ const reply = respond();+ // null leaves the request hanging, like a model still generating.+ if (reply === null) return;res.writeHead(200, { "Content-Type": "application/json" });- res.end(JSON.stringify(respond()));+ res.end(JSON.stringify(reply));});});await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));- t.after(() => new Promise((resolve) => server.close(resolve)));+ t.after(() => {+ server.closeAllConnections();+ return new Promise((resolve) => server.close(resolve));+ });const { bridge, modelManager } = loadChain();const model = modelRegistryData.localProviders[0].models[0];@@ -94,7 +100,7 @@ async function setupChain(t, respond) {modelManager.currentServerModelId = model.id;t.after(() => serverManager.clearIdleTimer());- return { bridge, modelId: model.id, requests, serverManager };+ return { bridge, modelManager, modelId: model.id, requests, serverManager };}const completion = (finishReason, content) => ({@@ -106,7 +112,11 @@ test("requireCompleteOutput rejects a truncated reply through the whole local chawait assert.rejects(() => bridge.processText("edit this", modelId, { requireCompleteOutput: true }),- /truncated/+ (error) => {+ assert.equal(error.code, "OUTPUT_TRUNCATED");+ assert.match(error.message, /truncated/);+ return true;+ });});@@ -151,3 +161,69 @@ test("a caller's contextSize reaches the server start (regression: it was droppeassert.deepEqual(started, [32768]);});++test("refuseClippedByWindow reaches runInference (the bridge rebuilds the config)", async (t) => {+ const { bridge, modelManager, modelId } = await setupChain(t, () => completion("stop", "ok"));+ const forwarded = [];+ const runInference = modelManager.runInference.bind(modelManager);+ modelManager.runInference = (id, text, options) => {+ forwarded.push(options);+ return runInference(id, text, options);+ };++ await bridge.processText("summarise this", modelId, { refuseClippedByWindow: true });++ assert.equal(forwarded.length, 1);+ assert.equal(forwarded[0].refuseClippedByWindow, true);+});++test("a second request while one is in flight is refused with a typed code", async (t) => {+ // A note summarised in parts holds the bridge for minutes; whatever arrives+ // meanwhile (another note's action, dictation cleanup) must fail with a code+ // the renderer can translate rather than the raw guard text.+ const { bridge, modelManager, modelId } = await setupChain(t, () => completion("stop", "ok"));+ let release;+ modelManager.runInference = () =>+ new Promise((resolve) => {+ release = () => resolve("first reply");+ });++ const first = bridge.processText("first", modelId, {});+ await new Promise((resolve) => setImmediate(resolve));+ await assert.rejects(bridge.processText("second", modelId, {}), (error) => {+ assert.equal(error.code, "LOCAL_MODEL_BUSY");+ return true;+ });++ release();+ assert.equal(await first, "first reply");+});++test("cancel aborts only the in-flight request carrying that id, and frees the slot", async (t) => {+ // A note cancelled mid-part used to hold the one local slot until the model+ // finished, so an immediate rerun (or dictation cleanup) was refused as busy.+ let hang = true;+ const { bridge, modelId, requests } = await setupChain(t, () =>+ hang ? null : completion("stop", "ok")+ );++ const pending = bridge.processText("long part", modelId, { requestId: "run-1" });+ const settled = pending.then(+ () => "resolved",+ (error) => error+ );+ while (requests.length === 0) await new Promise((resolve) => setTimeout(resolve, 5));++ bridge.cancel("run-2");+ const stillPending = await Promise.race([+ settled,+ new Promise((resolve) => setTimeout(() => resolve("pending"), 50)),+ ]);+ assert.equal(stillPending, "pending", "another caller's id must not abort this request");++ bridge.cancel("run-1");+ assert.ok((await settled) instanceof Error, "the tagged request is aborted");++ hang = false;+ assert.equal(await bridge.processText("next", modelId, {}), "ok");+});diff --git a/test/helpers/modelManagerContextSizing.test.js b/test/helpers/modelManagerContextSizing.test.jsindex af0c1aaed..4551b3dda 100644--- a/test/helpers/modelManagerContextSizing.test.js+++ b/test/helpers/modelManagerContextSizing.test.js@@ -326,6 +326,65 @@ test("a selection edit is refused rather than given a clipped answer", async (t)assert.equal(calls.completions, 0);});+test("a reply the window clipped is refused when the caller asks, so it can be split", async (t) => {+ // A long note trades output room for prompt room. A summary that then fills+ // the smaller allowance was cut short by the window, and a note action would+ // rather summarise in parts than save it (#2142).+ const { modelManager, modelId, calls, completionBody } = await setup(t, {+ tokenCount: 13000,+ totalMemoryBytes: 8 * GIB,+ finishReason: "length",+ });++ await assert.rejects(+ () =>+ modelManager.runInference(modelId, LONG_PROMPT, {+ systemPrompt: "Write meeting notes.",+ maxTokens: 4096,+ refuseClippedByWindow: true,+ }),+ (error) => {+ assert.equal(error.code, "CONTEXT_TOO_LARGE");+ assert.equal(error.details.modelId, modelId);+ return true;+ }+ );+ assert.equal(calls.completions, 1);+ assert.equal(completionBody().max_tokens, 16384 - 13000);+});++test("a trimmed reply that finishes is kept when the caller refuses window clips", async (t) => {+ const { modelManager, modelId } = await setup(t, {+ tokenCount: 13000,+ totalMemoryBytes: 8 * GIB,+ });++ const result = await modelManager.runInference(modelId, LONG_PROMPT, {+ systemPrompt: "Write meeting notes.",+ maxTokens: 4096,+ refuseClippedByWindow: true,+ });++ assert.equal(result, "done");+});++test("a reply cut off at the caller's own cap is kept when only window clips are refused", async (t) => {+ // A summary clipped at NOTE_OUTPUT_MAX_TOKENS is still worth keeping, so the+ // flag must not behave like requireCompleteOutput when the window had room.+ const { modelManager, modelId, completionBody } = await setup(t, {+ tokenCount: 40,+ finishReason: "length",+ });++ const result = await modelManager.runInference(modelId, SHORT_PROMPT, {+ maxTokens: 4096,+ refuseClippedByWindow: true,+ });++ assert.equal(result, "done");+ assert.equal(completionBody().max_tokens, 4096);+});+test("a grow that fails comes back at the window that was working", async (t) => {// start() stops the running server before it spawns the bigger one, so a// grow that dies takes a working window with it. Restoring it keeps localdiff --git a/test/helpers/noteChunking.test.js b/test/helpers/noteChunking.test.jsnew file mode 100644index 000000000..871a12d7a--- /dev/null+++ b/test/helpers/noteChunking.test.js@@ -0,0 +1,159 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const policy = require("../../src/helpers/llamaContextPolicy");++// Packs long material into parts that each fit the local model's window+// (#2142 part 3). The estimator is a deliberate copy of llamaContextPolicy's:+// the renderer cannot import that CommonJS module, so the last test pins the+// two together instead.++const load = () => import("../../src/helpers/noteChunking.js");++const normalise = (text) => text.replace(/\s+/g, " ").trim();++test("a body under budget is one chunk, untouched", async () => {+ const { planNoteChunks } = await load();+ const body = "Alice: hi\nBob: hello";+ assert.deepEqual(planNoteChunks(body, 1000), [body]);+});++test("chunks break only on line boundaries and lose no text", async () => {+ const { planNoteChunks, estimateNoteTokens } = await load();+ const lines = Array.from(+ { length: 200 },+ (_, i) => `Speaker ${i % 3}: line ${i} of the meeting about budgets.`+ );+ const body = lines.join("\n");+ const chunks = planNoteChunks(body, 120);+ assert.ok(chunks.length > 1);+ for (const chunk of chunks) {+ assert.ok(estimateNoteTokens(chunk) <= 120, `chunk over budget: ${estimateNoteTokens(chunk)}`);+ for (const line of chunk.split("\n"))+ assert.ok(lines.includes(line), `split mid-line: ${line}`);+ }+ assert.equal(normalise(chunks.join("\n")), normalise(body));+});++test("a single line longer than the budget is split at spaces, never dropped", async () => {+ const { planNoteChunks, estimateNoteTokens } = await load();+ const body = "Them: " + "word ".repeat(600).trim();+ const chunks = planNoteChunks(body, 50);+ assert.ok(chunks.length > 1);+ for (const chunk of chunks) assert.ok(estimateNoteTokens(chunk) <= 50);+ assert.equal(normalise(chunks.join(" ")), normalise(body));+});++test("an unbroken run (CJK, no spaces) longer than the budget is sliced by tokens", async () => {+ const { planNoteChunks, estimateNoteTokens } = await load();+ const body = "会議".repeat(300);+ const chunks = planNoteChunks(body, 100);+ assert.ok(chunks.length >= 6);+ for (const chunk of chunks) assert.ok(estimateNoteTokens(chunk) <= 100);+ assert.equal(chunks.join(""), body);+});++test("empty and whitespace-only bodies plan to no chunks", async () => {+ const { planNoteChunks } = await load();+ assert.deepEqual(planNoteChunks("", 100), []);+ assert.deepEqual(planNoteChunks("\n \n", 100), []);+});++test("transcript continuations retain their speaker within the token budget", async () => {+ const { planNoteChunks, estimateNoteTokens } = await load();+ const body = "Bob: " + "We discussed the rollout. ".repeat(100) + "I own the invoice.";+ const chunks = planNoteChunks(body, 100, { preserveSpeakerLabels: true });+ assert.ok(chunks.length > 1);+ for (const chunk of chunks) {+ assert.ok(chunk.startsWith("Bob: "));+ assert.ok(estimateNoteTokens(chunk) <= 100);+ }+ assert.equal(+ normalise(chunks.map((chunk) => chunk.replace(/^Bob: /, "")).join(" ")),+ normalise(body.slice(5))+ );+});++test("plain notes do not repeat colon-prefixed text as a speaker", async () => {+ const { planNoteChunks } = await load();+ const chunks = planNoteChunks("Agenda: " + "topic ".repeat(100), 100);+ assert.equal(chunks.filter((chunk) => chunk.includes("Agenda:")).length, 1);+});++test("a raw transcript's oversized colon prefix does not defeat chunking or retries", async () => {+ const { planNoteChunks, splitChunkInHalf, estimateNoteTokens } = await load();+ const body = "Background ".repeat(1000) + ": " + "Follow up ".repeat(20);+ const options = { preserveSpeakerLabels: true };+ const chunks = planNoteChunks(body, 1800, options);+ for (const chunk of chunks) assert.ok(estimateNoteTokens(chunk) <= 1800);+ assert.equal(normalise(chunks.join(" ")), normalise(body));+ for (const half of splitChunkInHalf(body, options)) {+ assert.ok(estimateNoteTokens(half) < estimateNoteTokens(body) * 0.75);+ }+});++test("halving a skewed chunk splits the dominant line instead of only its neighbours", async () => {+ const { splitChunkInHalf } = await load();+ const body = "🚀".repeat(3500) + "\n" + "short\n".repeat(16).trim();+ const halves = splitChunkInHalf(body);+ assert.equal(+ halves.map((half) => (half.match(/🚀/gu) || []).length).reduce((sum, count) => sum + count),+ 3500+ );+ for (const half of halves) {+ assert.ok((half.match(/🚀/gu) || []).length < 2500);+ assert.ok(half.isWellFormed());+ }+});++test("retry splits preserve the speaker of a divided turn", async () => {+ const { splitChunkInHalf } = await load();+ const body = "Bob: " + "word ".repeat(100) + "I own the invoice.";+ const halves = splitChunkInHalf(body, { preserveSpeakerLabels: true });+ assert.ok(halves.every((half) => half.startsWith("Bob: ")));+ assert.equal(normalise(halves.map((half) => half.slice(5)).join(" ")), normalise(body.slice(5)));+});++test("splitChunkInHalf prefers line boundaries, then word boundaries", async () => {+ const { splitChunkInHalf } = await load();+ assert.deepEqual(splitChunkInHalf("a\nb\nc\nd"), ["a\nb", "c\nd"]);+ assert.deepEqual(splitChunkInHalf("one two three four"), ["one two", "three four"]);+});++test("splitChunkInHalf splits unbroken runs without losing Unicode code points", async () => {+ const { splitChunkInHalf } = await load();+ for (const text of ["会議".repeat(300), "𠀀𠀁𠀂", "会🚀議", "single"]) {+ const halves = splitChunkInHalf(text);+ assert.ok(halves, `could not split ${text.slice(0, 20)}`);+ assert.equal(halves.join(""), text);+ assert.deepEqual(+ halves.map((half) => Array.from(half).length),+ [Math.ceil(Array.from(text).length / 2), Math.floor(Array.from(text).length / 2)]+ );+ for (const half of halves) assert.ok(half.isWellFormed());+ }+});++test("splitChunkInHalf gives up only on empty or single-code-point chunks", async () => {+ const { splitChunkInHalf } = await load();+ for (const text of ["", "a", "会", "𠀀", "🚀", " ", "\n"]) {+ assert.equal(splitChunkInHalf(text), null);+ }+});++test("the estimate agrees with llamaContextPolicy on Latin, CJK and mixed text", async () => {+ const { estimateNoteTokens } = await load();+ const fixtures = [+ "",+ "Alice: we agreed to ship on Friday.",+ "会議は金曜日に決まりました。",+ "Mixed 会議 text with ünïcödé and emoji 🚀.",+ "x".repeat(10000),+ ];+ for (const text of fixtures) {+ assert.equal(+ estimateNoteTokens(text),+ policy.estimateTokens(text),+ JSON.stringify(text.slice(0, 20))+ );+ }+});diff --git a/test/stores/actionProcessingChunked.test.js b/test/stores/actionProcessingChunked.test.jsnew file mode 100644index 000000000..083bd1fc2--- /dev/null+++ b/test/stores/actionProcessingChunked.test.js@@ -0,0 +1,774 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++// A note that does not fit the local model's window is summarised in parts and+// then merged (#2142 part 3). Everything that fits keeps today's single call.++const ACTION = { id: 1, name: "Generate Notes", prompt: "Summarize the meeting." };+const LABELS = { noModel: "no model", noEndpoint: "no endpoint", actionFailed: "failed" };+const LINE = "Alice: we agreed to ship the billing migration on Friday after QA.\n";+const BIG_BUDGET = { success: true, maxContextTokens: 131072, modelName: "Qwen3.5 9B" };+// 8192 leaves roughly 4,400 tokens per part after the part prompt and output reserve.+const SMALL_BUDGET = { success: true, maxContextTokens: 8192, modelName: "Qwen3.5 9B" };+// Parts may be allowed the same 4096 tokens as the whole note, so the prompt,+// not the allowance, tells a part request from the whole-note or merge request.+const isPart = (config) => /this part only/i.test(config.systemPrompt);++async function loadStore(+ t,+ { budget = SMALL_BUDGET, mode = "local", storage = {}, failFirst = false, processText } = {}+) {+ const updates = [];+ const budgetCalls = [];+ const cancelledRequests = [];+ installBrowserGlobals(t, {+ // The real settings store reads the route from storage at load time.+ initialStorage: { noteFormattingMode: mode, noteFormattingUseLocal: "true", ...storage },+ window: {+ electronAPI: {+ updateNote: async (noteId, payload) => {+ updates.push({ noteId, payload });+ return { success: true };+ },+ getLocalContextBudget: async (modelId) => {+ budgetCalls.push(modelId);+ if (budget instanceof Error) throw budget;+ return budget;+ },+ cancelLocalReasoning: async (requestId) => {+ cancelledRequests.push(requestId);+ },+ },+ },+ });++ const calls = [];+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-action-chunked-test-",+ mockModules: {+ "/services/ReasoningService": `+ export default {+ processText: async (text, model, agentName, config) => {+ const calls = globalThis.__processTextCalls;+ calls.push({ text, model, config });+ if (globalThis.__failFirst && calls.length === 1) {+ const error = new Error("too big");+ error.code = "CONTEXT_TOO_LARGE";+ throw error;+ }+ if (globalThis.__cancelAfter && calls.length === globalThis.__cancelAfter.after) {+ globalThis.__cancelAfter.cancel();+ }+ if (globalThis.__processTextResponse) {+ return globalThis.__processTextResponse(text, config);+ }+ return "# Part notes " + calls.length + "\\n- decided things";+ },+ };+ `,+ "/utils/generateTitle": `export const generateNoteTitle = async () => undefined;`,+ },+ });+ globalThis.__processTextCalls = calls;+ globalThis.__failFirst = failFirst;+ globalThis.__processTextResponse = processText;+ t.after(() => {+ delete globalThis.__processTextCalls;+ delete globalThis.__failFirst;+ delete globalThis.__processTextResponse;+ delete globalThis.__cancelAfter;+ });++ const store = await vite.ssrLoadModule("/stores/actionProcessingStore.ts");+ return { store, calls, updates, budgetCalls, cancelledRequests };+}++async function waitFor(predicate, label) {+ for (let attempt = 0; attempt < 500; attempt += 1) {+ if (predicate()) return;+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+ throw new Error(`timed out waiting for ${label}`);+}++const longMaterial = (lines) => ({+ notes: "My own note: watch the QA date.",+ meetingContext: "## Meeting Context\nThe user taking these notes is Alice.",+ transcript: LINE.repeat(lines).trim(),+});++const run = (store, noteId, material, options = {}, action = ACTION) =>+ store.runBackgroundAction(+ noteId,+ [material.notes, material.meetingContext, `## Meeting Transcript\n${material.transcript}`].join(+ "\n\n"+ ),+ "hash",+ action,+ { modelId: "qwen3.5-9b-q4_k_m", isCloudMode: false, isMeetingNote: true, material, ...options },+ LABELS+ );++test("material that fits is one request with today's prompt and no budget read", async (t) => {+ const { store, calls, updates, budgetCalls } = await loadStore(t, { budget: BIG_BUDGET });+ run(store, 1, longMaterial(20));+ await waitFor(() => updates.length > 0, "save");+ assert.equal(calls.length, 1);+ assert.deepEqual(budgetCalls, []);+ assert.ok(calls[0].text.includes("## Meeting Transcript"));+ assert.ok(calls[0].config.systemPrompt.endsWith("Summarize the meeting."));+ assert.equal(calls[0].config.maxTokens, 4096);+});++test("cloud mode never reads the budget and never chunks", async (t) => {+ const { store, calls, updates, budgetCalls } = await loadStore(t, { mode: "openwhispr" });+ run(store, 2, longMaterial(400), { isCloudMode: true });+ await waitFor(() => updates.length > 0, "save");+ assert.equal(calls.length, 1);+ assert.deepEqual(budgetCalls, []);+});++test("refused material is summarised in parts, then merged with the action prompt", async (t) => {+ const { store, calls, updates } = await loadStore(t, { failFirst: true });+ const material = longMaterial(400);+ run(store, 3, material);+ await waitFor(() => updates.length > 0, "save");++ const parts = calls.slice(1, -1);+ const final = calls[calls.length - 1];+ // 400 lines at the small budget pack into 3 parts at the 85% fill; 2 at 100%.+ assert.equal(parts.length, 3);+ parts.forEach((call, index) => {+ assert.ok(+ call.text.includes(material.meetingContext),+ "every part carries the meeting context"+ );+ assert.ok(+ call.text.includes(`part ${index + 1} of ${parts.length}`),+ `part ${index + 1} labelled`+ );+ assert.ok(!call.text.includes(material.notes), "manual notes are held for the final pass");+ assert.ok(+ /this part only/i.test(call.config.systemPrompt),+ "part prompt is the part-notes prompt"+ );+ assert.ok(call.config.maxTokens <= 2048);+ });+ assert.ok(+ final.config.systemPrompt.includes("Summarize the meeting."),+ "final pass uses the action prompt"+ );+ assert.ok(final.text.includes(material.notes), "final pass carries the manual notes");+ assert.ok(final.text.includes(material.meetingContext));+ for (let index = 1; index <= parts.length; index += 1) {+ assert.ok(+ final.text.includes(`## Notes from part ${index} of ${parts.length}`),+ `part ${index} notes present`+ );+ assert.ok(final.text.includes(`# Part notes ${index + 1}`));+ }+ assert.ok(!final.text.includes("Alice: we agreed"), "final pass never sees the raw transcript");+ assert.equal(+ updates[0].payload.enhanced_content,+ `# Part notes ${calls.length}\n- decided things`+ );+});++test("a refusal whose budget cannot be read is reported without splitting", async (t) => {+ const { store, calls, updates } = await loadStore(t, {+ budget: new Error("ipc down"),+ failFirst: true,+ });+ run(store, 4, longMaterial(400));+ await waitForResult(store, updates);+ assert.equal(updates.length, 0);+ assert.equal(calls.length, 1);+ assert.equal(store.consumeErrorEvents()[0].message, "too big");+});++test("a single request refused as CONTEXT_TOO_LARGE falls through to chunking", async (t) => {+ const { store, calls, updates } = await loadStore(t, { budget: BIG_BUDGET, failFirst: true });+ run(store, 5, longMaterial(20));+ await waitFor(() => updates.length > 0, "save");+ assert.ok(calls.length >= 3, `expected the refused call, parts and a merge, got ${calls.length}`);+ assert.ok(/this part only/i.test(calls[1].config.systemPrompt));+});++test("cancelling between parts stops further requests and saves nothing", async (t) => {+ const { store, calls, updates } = await loadStore(t, { failFirst: true });+ globalThis.__cancelAfter = { after: 2, cancel: () => store.cancelAction(6) };+ run(store, 6, longMaterial(400));+ await waitFor(() => calls.length >= 2, "first part");+ await new Promise((resolve) => setTimeout(resolve, 200));+ assert.equal(calls.length, 2);+ assert.equal(updates.length, 0);+ assert.equal(+ store.useActionProcessingStore.getState().noteStates[6],+ undefined,+ "the cancelled run writes no progress back into the cleared slot"+ );+});++test("cancelling aborts the run's local request in flight by its id", async (t) => {+ const { store, calls, cancelledRequests } = await loadStore(t, { failFirst: true });+ globalThis.__cancelAfter = { after: 2, cancel: () => store.cancelAction(29) };+ run(store, 29, longMaterial(400));+ await waitFor(() => cancelledRequests.length > 0, "the abort");+ const requestId = calls[1].config.requestId;+ assert.equal(typeof requestId, "string");+ assert.equal(calls[0].config.requestId, requestId, "every request of a run carries its id");+ assert.deepEqual(cancelledRequests, [requestId]);+});++test("progress advances once per part and ends on the final pass", async (t) => {+ const { store, calls, updates } = await loadStore(t, { failFirst: true });+ const seen = [];+ const unsubscribe = store.useActionProcessingStore.subscribe((state) => {+ const progress = state.noteStates[7]?.progress;+ const label = progress ? `${progress.step}/${progress.total}` : null;+ if (label && seen.at(-1) !== label) seen.push(label);+ });+ t.after(unsubscribe);+ run(store, 7, longMaterial(400));+ await waitFor(() => updates.length > 0, "save");+ const parts = calls.length - 2;+ assert.deepEqual(+ seen,+ Array.from({ length: parts + 1 }, (_, index) => `${index + 1}/${parts + 1}`)+ );+});++async function waitForResult(store, updates) {+ await waitFor(+ () => updates.length > 0 || store.useActionProcessingStore.getState().errorEvents.length > 0,+ "save or failure"+ );+}++const overflow = () => Object.assign(new Error("too big"), { code: "CONTEXT_TOO_LARGE" });+const FLOOR_BUDGET = { success: true, maxContextTokens: 16384, modelName: "Local model" };++// The main process only reports OUTPUT_TRUNCATED when asked for a complete+// reply; a part is never asked, so a verbose model costs one clipped part, not+// a cascade of halvings (measured: 26 part calls for 2 parts on a 9B).+test("a part whose reply fills its allowance is kept clipped, never split", async (t) => {+ const { store, calls, updates } = await loadStore(t, {+ failFirst: true,+ processText: (text, config) => {+ if (!isPart(config)) return "Final notes";+ if (config.requireCompleteOutput) {+ throw Object.assign(new Error("truncated"), { code: "OUTPUT_TRUNCATED" });+ }+ return "Clipped working notes";+ },+ });+ run(store, 17, longMaterial(400));+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ assert.deepEqual(store.consumeErrorEvents(), []);+ assert.equal(calls.length, 5, "the refused request, three parts, one merge");+ for (const part of calls.slice(1, -1)) {+ assert.equal(part.config.requireCompleteOutput, undefined);+ assert.equal(part.config.refuseClippedByWindow, false);+ }+ assert.ok(calls.at(-1).text.includes("Clipped working notes"));+});++test("a part cut short by the model is a plain failure, not a reason to split", async (t) => {+ // OUTPUT_TRUNCATED only arrives when a caller asked for a complete reply. A+ // part never asks, so seeing it means the request was not the store's own;+ // halving on it is what turned 2 parts into 26 calls on a verbose 9B.+ const { store, calls, updates } = await loadStore(t, {+ failFirst: true,+ processText: (text, config) => {+ if (!isPart(config)) return "Final notes";+ throw Object.assign(new Error("truncated"), { code: "OUTPUT_TRUNCATED" });+ },+ });+ run(store, 27, longMaterial(400));+ await waitForResult(store, updates);+ assert.equal(updates.length, 0);+ assert.equal(calls.length, 2, "the refused request and the one failed part");+ assert.equal(store.consumeErrorEvents()[0].message, "truncated");+});++test("part allowances are sized so every part's notes fit the final pass together", async (t) => {+ const { estimateNoteTokens } = await import("../../src/helpers/noteChunking.js");+ const { store, calls, updates } = await loadStore(t, { failFirst: true });+ const material = longMaterial(400);+ run(store, 18, material);+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ const parts = calls.slice(1, -1);+ const final = calls.at(-1);+ const allowances = parts.map((call) => call.config.maxTokens);+ assert.ok(+ allowances[0] < 2048,+ `the small budget must shrink the allowance, got ${allowances[0]}`+ );+ assert.ok(allowances.every((allowance) => allowance === allowances[0]));+ // Each part's share of what the final pass has left after its fixed pieces:+ // the merge prompt, manual notes, context, the 4096 reply, the main process's+ // 512-token reserve, and a "## Notes from part i of N" heading per part.+ const room =+ SMALL_BUDGET.maxContextTokens -+ estimateNoteTokens(final.config.systemPrompt) -+ estimateNoteTokens(material.notes) -+ estimateNoteTokens(material.meetingContext) -+ final.config.maxTokens -+ 512 -+ parts.length * 16;+ assert.equal(allowances[0], Math.floor(room / parts.length));+ for (const part of parts) {+ assert.match(+ part.config.systemPrompt,+ new RegExp(`about ${Math.floor(allowances[0] / 2)} words`),+ "the part prompt names the length the allowance leaves room for"+ );+ }+});++// A cap below the final pass's room clipped every part of a meeting on the+// default 9B, dropping whatever each part said last.+test("parts share the final pass's room up to a full note reply", async (t) => {+ const { store, calls, updates } = await loadStore(t, { budget: FLOOR_BUDGET, failFirst: true });+ run(store, 30, longMaterial(700));+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ const parts = calls.slice(1, -1);+ assert.ok(parts.length >= 2, `expected several parts, got ${parts.length}`);+ for (const part of parts) assert.equal(part.config.maxTokens, 4096);+});++test("material that would leave each part too small an allowance is refused before any part runs", async (t) => {+ const { store, calls, updates } = await loadStore(t, { failFirst: true });+ run(store, 25, longMaterial(4000));+ await waitForResult(store, updates);+ assert.equal(updates.length, 0);+ assert.equal(calls.length, 1);+ const [error] = store.consumeErrorEvents();+ assert.equal(error.messageKey, "models.errors.contextTooLargeGeneric");+});++test("an empty part reply fails the note instead of merging a blank section", async (t) => {+ let partCalls = 0;+ const { store, calls, updates } = await loadStore(t, {+ failFirst: true,+ processText: (text, config) => {+ if (!isPart(config)) return "Final notes";+ partCalls += 1;+ return partCalls === 2 ? " \n" : "Working notes";+ },+ });+ run(store, 26, longMaterial(400));+ await waitForResult(store, updates);+ assert.equal(updates.length, 0);+ assert.equal(calls.length, 3, "stops at the blank part; no merge");+ const [error] = store.consumeErrorEvents();+ assert.equal(error.message, "Model returned no text");+ assert.equal(error.messageKey, "notes.actions.emptyReply");+});++test("an empty whole-note reply fails with a translated message", async (t) => {+ const { store, updates } = await loadStore(t, { processText: () => " \n" });+ run(store, 31, longMaterial(3));+ await waitForResult(store, updates);+ assert.equal(updates.length, 0);+ assert.equal(store.consumeErrorEvents()[0].messageKey, "notes.actions.emptyReply");+});++test("cancelling a refused part prevents its first recursive retry", async (t) => {+ let partReturned = false;+ const { store, calls, updates } = await loadStore(t, {+ failFirst: true,+ processText: () => {+ store.cancelAction(19);+ partReturned = true;+ throw overflow();+ },+ });+ run(store, 19, longMaterial(20));+ await waitFor(() => partReturned, "cancelled part");+ await new Promise((resolve) => setTimeout(resolve, 50));+ assert.equal(calls.length, 2);+ assert.equal(updates.length, 0);+ assert.deepEqual(store.consumeErrorEvents(), []);+});++test("speaker attribution survives packing and an overflow retry", async (t) => {+ let refused = false;+ const { store, calls, updates } = await loadStore(t, {+ failFirst: true,+ processText: (text, config) => {+ if (isPart(config) && !refused) {+ refused = true;+ throw overflow();+ }+ return "Working notes";+ },+ });+ const transcript = "Bob: " + "We discussed the rollout. ".repeat(1500) + "I own the invoice.";+ run(store, 20, { notes: "", meetingContext: "", transcript });+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ for (const call of calls.slice(1, -1)) assert.match(call.text, /\nBob: /);+ // The halves share the refused part's allowance so the merge still fits.+ const refusedAllowance = calls[1].config.maxTokens;+ assert.equal(calls[2].config.maxTokens, Math.ceil(refusedAllowance / 2));+ assert.equal(calls[3].config.maxTokens, Math.ceil(refusedAllowance / 2));+});++test("a conservative overestimate preserves the original request when the model accepts it", async (t) => {+ const { store, calls, updates } = await loadStore(t, { budget: FLOOR_BUDGET });+ const material = { notes: LINE.repeat(600), meetingContext: "", transcript: "Alice: Hello." };+ run(store, 8, material);+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ assert.equal(calls.length, 1);+ assert.ok(calls[0].text.includes(material.notes));+ assert.equal(calls[0].config.maxTokens, 4096);+});++test("an exact-token overflow at the final merge reduces the existing part notes and saves", async (t) => {+ let reduced = false;+ const { store, calls, updates } = await loadStore(t, {+ budget: FLOOR_BUDGET,+ failFirst: true,+ processText: (text, config) => {+ if (text.includes("## Working notes")) {+ reduced = true;+ return "Alice owns QA; Bob owns release.";+ }+ if (!isPart(config)) {+ if (!reduced) throw overflow();+ return "- [ ] QA — Alice\n- [ ] Release — Bob";+ }+ return "Alice owns QA. Bob owns release.";+ },+ });+ run(store, 9, longMaterial(1400));+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ assert.equal(updates[0].payload.enhanced_content, "- [ ] QA — Alice\n- [ ] Release — Bob");+ assert.equal(calls.filter((call) => call.text.includes("## Working notes")).length, 1);+ assert.equal(calls.filter((call) => !isPart(call.config)).length, 3);+ assert.ok(calls.at(-1).text.includes("Alice owns QA; Bob owns release."));+});++test("a shorter consolidation is usable even when its section count stays the same", async (t) => {+ let reductions = 0;+ const { store, calls, updates } = await loadStore(t, {+ budget: FLOOR_BUDGET,+ failFirst: true,+ processText: (text, config) => {+ if (text.includes("## Working notes")) {+ reductions += 1;+ return reductions === 1 ? "detail ".repeat(750) : "Alice owns QA.";+ }+ if (!isPart(config)) {+ if (text.includes("detail")) throw overflow();+ return "- [ ] QA — Alice";+ }+ return "detail ".repeat(750);+ },+ });+ const material = {+ notes: "manual note ".repeat(2325),+ meetingContext: "",+ transcript: LINE.repeat(1400),+ };+ run(store, 10, material);+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ assert.equal(reductions, 2);+ assert.ok(calls.at(-1).text.includes(material.notes));+ assert.ok(calls.at(-1).text.includes("Alice owns QA."));+});++test("the last allowed consolidation still gets a final merge attempt", async (t) => {+ let reductions = 0;+ const { store, updates } = await loadStore(t, {+ failFirst: true,+ processText: (text, config) => {+ if (text.includes("## Working notes")) reductions += 1;+ if (!isPart(config)) {+ if (reductions < 3) throw overflow();+ return "Final notes";+ }+ return "Working notes";+ },+ });+ run(store, 11, longMaterial(20));+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ assert.equal(reductions, 3);+});++test("repeated merge overflows stop after three consolidations and name the model", async (t) => {+ let reductions = 0;+ const { store, calls, updates } = await loadStore(t, {+ failFirst: true,+ processText: (text, config) => {+ if (text.includes("## Working notes")) reductions += 1;+ if (!isPart(config)) throw overflow();+ return "Working notes";+ },+ });+ run(store, 12, longMaterial(20));+ await waitForResult(store, updates);+ assert.equal(updates.length, 0);+ assert.equal(reductions, 3);+ assert.equal(calls.filter((call) => !isPart(call.config)).length, 5);+ const [error] = store.consumeErrorEvents();+ assert.equal(error.messageKey, "models.errors.contextTooLargeGeneric");+ assert.deepEqual(error.messageParams, { model: "Qwen3.5 9B" });+});++test("a non-context merge error is reported without retrying", async (t) => {+ const { store, calls, updates } = await loadStore(t, {+ failFirst: true,+ processText: (text, config) => {+ if (!isPart(config)) throw new Error("model unavailable");+ return "Working notes";+ },+ });+ run(store, 13, longMaterial(20));+ await waitForResult(store, updates);+ assert.equal(updates.length, 0);+ assert.equal(store.consumeErrorEvents()[0].message, "model unavailable");+ assert.equal(+ calls.some((call) => call.text.includes("## Working notes")),+ false+ );+});++test("cancelling a failed merge prevents further consolidation and saving", async (t) => {+ const { store, calls, updates } = await loadStore(t, {+ failFirst: true,+ processText: (text, config) => {+ if (!isPart(config)) {+ store.cancelAction(14);+ throw overflow();+ }+ return "Working notes";+ },+ });+ run(store, 14, longMaterial(20));+ await waitFor(() => calls.length === 3, "failed merge");+ await new Promise((resolve) => setTimeout(resolve, 50));+ assert.equal(updates.length, 0);+ assert.equal(calls.length, 3);+ assert.deepEqual(store.consumeErrorEvents(), []);+});++test("an unbroken CJK part rejected by the tokenizer is split and merged without losing text", async (t) => {+ const accepted = [];+ const { store, updates } = await loadStore(t, {+ budget: FLOOR_BUDGET,+ failFirst: true,+ processText: (text, config) => {+ if (!isPart(config)) return "Final notes";+ const characters = (text.match(/𠀀/gu) || []).join("");+ if ([...characters].length > 7000) throw overflow();+ accepted.push(characters);+ return "Working notes";+ },+ });+ const body = "𠀀".repeat(14000);+ run(store, 15, { notes: "", meetingContext: "", transcript: body }, { isMeetingNote: false });+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ assert.equal(accepted.join(""), body);+});++test("the merge preserves a follow-up email action without imposing exhaustive notes", async (t) => {+ const { BUILTIN_ACTIONS } = await import("../../src/helpers/builtinActions.js");+ const email = BUILTIN_ACTIONS.find(+ (action) => action.translationKey === "notes.actions.builtin.followUpEmail"+ );+ const { store, calls, updates } = await loadStore(t, { failFirst: true });+ run(+ store,+ 16,+ longMaterial(20),+ {},+ {+ id: 2,+ name: email.name,+ prompt: email.prompt,+ translation_key: email.translationKey,+ }+ );+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ const prompt = calls.at(-1).config.systemPrompt;+ assert.ok(prompt.includes(email.prompt));+ assert.doesNotMatch(prompt, /Completeness outranks brevity|as long as that requires/);+});++test("a local model reached through dictation cleanup is summarised in parts too", async (t) => {+ // Note formatting on its default mode follows dictation cleanup when the user+ // is not on OpenWhispr Cloud, so a local cleanup model answers the request.+ const { store, calls, updates, budgetCalls } = await loadStore(t, {+ mode: "openwhispr",+ failFirst: true,+ });+ run(store, 22, longMaterial(400));+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ assert.deepEqual(budgetCalls, ["qwen3.5-9b-q4_k_m"]);+ const parts = calls.slice(1, -1);+ assert.ok(parts.length >= 2, `expected several parts, got ${parts.length}`);+ for (const part of parts) assert.match(part.config.systemPrompt, /this part only/i);+});++test("re-running a note right after cancelling it never revives the cancelled run", async (t) => {+ const { store, calls, updates } = await loadStore(t, {+ failFirst: true,+ // The second run's reply lands after the cancelled run has unwound, so a+ // cancelled run that cleared the note's slot would stop the new one saving.+ processText: (text) =>+ text.includes("Bob: the second run")+ ? new Promise((resolve) => setTimeout(() => resolve("Second run notes"), 50))+ : "Working notes",+ });+ globalThis.__cancelAfter = {+ after: 2,+ cancel: () => {+ store.cancelAction(21);+ run(store, 21, { notes: "", meetingContext: "", transcript: "Bob: the second run." });+ },+ };+ run(store, 21, longMaterial(400));+ await waitFor(() => updates.length > 0, "the second run's save");+ await new Promise((resolve) => setTimeout(resolve, 200));+ assert.deepEqual(+ updates.map((update) => update.payload.enhanced_content),+ ["Second run notes"]+ );+ assert.equal(+ calls.filter((call) => call.text.includes("Alice: we agreed")).length,+ 2,+ "the cancelled run sends nothing after the part already in flight"+ );+});++// Only the whole-note request may trade a clipped reply for the parts route.+// Once the note is in parts there is no better route left, so a clipped merge+// is saved as it was before #2155 rather than refused after minutes of work.+test("only the whole-note request refuses a reply the window clipped", async (t) => {+ const { store, calls, updates } = await loadStore(t, { failFirst: true });+ run(store, 23, longMaterial(400));+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ assert.equal(calls[0].config.refuseClippedByWindow, true);+ for (const call of calls.slice(1)) assert.equal(call.config.refuseClippedByWindow, false);+ assert.equal(calls.at(-1).config.maxTokens, 4096);+});++test("a transcript without speaker labels is packed without a prose prefix", async (t) => {+ const { store, calls, updates } = await loadStore(t, { failFirst: true });+ // A note summarised while it is still recording carries the live transcript:+ // one space-joined paragraph, no "Label:" lines, and a colon in the first clause.+ const transcript =+ "Meeting at 10:30 we discussed the rollout plan. " ++ "Then we covered the budget and the hiring plan. ".repeat(600).trim();+ run(store, 21, { notes: "", meetingContext: "", transcript }, { isMeetingNote: false });+ await waitForResult(store, updates);+ assert.deepEqual(store.consumeErrorEvents(), []);+ assert.equal(updates.length, 1);+ const parts = calls.slice(1, -1);+ assert.ok(parts.length > 1);+ assert.equal(+ parts+ .map((call) => call.text)+ .join("")+ .split("Meeting at 10:").length - 1,+ 1+ );+});++test("parts never spend their output budget on thinking", async (t) => {+ const { store, calls, updates } = await loadStore(t, {+ failFirst: true,+ storage: { noteFormattingDisableThinking: "false" },+ });+ run(store, 22, longMaterial(400));+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ assert.equal(calls[0].config.disableThinking, false);+ assert.equal(calls.at(-1).config.disableThinking, false);+ for (const call of calls.slice(1, -1)) assert.equal(call.config.disableThinking, true);+});++test("manual notes that cannot fit the final pass are refused before any part runs", async (t) => {+ const { store, calls, updates } = await loadStore(t, {+ budget: FLOOR_BUDGET,+ failFirst: true,+ processText: (text, config) => {+ if (!isPart(config)) throw overflow();+ return "Working notes";+ },+ });+ const material = {+ notes: "manual note ".repeat(6000),+ meetingContext: "",+ transcript: LINE.repeat(400),+ };+ run(store, 23, material);+ await waitForResult(store, updates);+ assert.equal(updates.length, 0);+ assert.equal(calls.length, 1);+ const [error] = store.consumeErrorEvents();+ assert.equal(error.messageKey, "models.errors.contextTooLargeGeneric");+});++// A plain note has no parts route, so the trade the whole-note request makes+// for a recording (refuse a reply the window clipped, summarise in parts) would+// only turn a clipped save into a refusal. It keeps main's behaviour instead.+test("a plain note saves a reply the window clipped rather than refusing it", async (t) => {+ const { store, calls, updates } = await loadStore(t, { budget: BIG_BUDGET });+ const notes = "The proposal argues that the migration should wait for the audit.\n".repeat(60);+ store.runBackgroundAction(+ 28,+ notes,+ "hash",+ ACTION,+ {+ modelId: "qwen3.5-9b-q4_k_m",+ isCloudMode: false,+ material: { notes, meetingContext: "", transcript: "" },+ },+ LABELS+ );+ await waitForResult(store, updates);+ assert.equal(updates.length, 1);+ assert.equal(calls.length, 1);+ assert.equal(calls[0].config.refuseClippedByWindow, false);+});++// The store cannot tell "summarise" from "fix the grammar"; condensing a plain+// note into working notes and then applying an edit-style action to those+// would silently replace the user's text with a digest of it.+test("a long plain note keeps the translated refusal instead of being condensed", async (t) => {+ const { store, calls, updates, budgetCalls } = await loadStore(t, { failFirst: true });+ const notes = "The proposal argues that the migration should wait for the audit.\n".repeat(600);+ store.runBackgroundAction(+ 24,+ notes,+ "hash",+ ACTION,+ {+ modelId: "qwen3.5-9b-q4_k_m",+ isCloudMode: false,+ material: { notes, meetingContext: "", transcript: "" },+ },+ LABELS+ );+ await waitForResult(store, updates);+ assert.equal(updates.length, 0);+ assert.equal(calls.length, 1);+ assert.deepEqual(budgetCalls, []);+ assert.equal(store.consumeErrorEvents()[0].message, "too big");+});diff --git a/test/utils/localInferenceError.test.js b/test/utils/localInferenceError.test.jsindex 7836c6cfa..5c0c2b1c5 100644--- a/test/utils/localInferenceError.test.js+++ b/test/utils/localInferenceError.test.js@@ -98,3 +98,16 @@ test("a reply cut off at the token cap gets the cleanup truncation message", ()assert.equal(error.messageKey, "hooks.audioRecording.errorDescriptions.cleanupTruncated");assert.equal(error.messageParams, undefined);});++test("a model busy with another request gets a translatable message, not the raw guard text", () => {+ // The bridge serves one request at a time; a note summarised in parts holds+ // it for minutes, so a second caller must get copy the UI can translate.+ const error = errors.buildLocalInferenceError({+ error: "Already processing a request",+ code: "LOCAL_MODEL_BUSY",+ });++ assert.equal(error.code, "LOCAL_MODEL_BUSY");+ assert.equal(error.messageKey, "models.errors.localModelBusy");+ assert.equal(error.messageParams, undefined);+});