Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(mobile): keep On-Device cleanup and meeting notes under Apple Intelligence's output cap (#2775)

Chad Pihad40bb098876d
diff --git a/openwhispr-mobile/modules/apple-llm/ios/AppleLLMModule.swift b/openwhispr-mobile/modules/apple-llm/ios/AppleLLMModule.swift
index 93f1c8bda..839a969a8 100644
--- a/openwhispr-mobile/modules/apple-llm/ios/AppleLLMModule.swift
+++ b/openwhispr-mobile/modules/apple-llm/ios/AppleLLMModule.swift
@@ -248,12 +248,51 @@ public class AppleLLMModule: Module {
return
}
+ #if compiler(>=6.4)
+ // iOS 27 deprecates GenerationError for these types. Swift 6.4 is the first compiler with
+ // the iOS 27 SDK.
+ if #available(iOS 27.0, *) {
+ if error is GeneratedContent.ParsingError {
+ promise.reject("APPLE_LLM_OUTPUT_LIMIT", error.localizedDescription)
+ return
+ }
+ if let modelError = error as? LanguageModelError {
+ switch modelError {
+ case .contextSizeExceeded(_):
+ promise.reject("APPLE_LLM_CONTEXT_LIMIT", modelError.localizedDescription)
+ case .guardrailViolation(_), .refusal(_):
+ promise.reject("APPLE_LLM_GUARDRAIL", modelError.localizedDescription)
+ case .rateLimited(_):
+ promise.reject("APPLE_LLM_RATE_LIMITED", modelError.localizedDescription)
+ case .unsupportedLanguageOrLocale(_):
+ promise.reject("APPLE_LLM_UNAVAILABLE", modelError.localizedDescription)
+ default:
+ promise.reject("APPLE_LLM_FAILED", modelError.localizedDescription)
+ }
+ return
+ }
+ // GenerationError's assetsUnavailable and concurrentRequests moved to these two types.
+ if error is SystemLanguageModel.Error {
+ promise.reject("APPLE_LLM_UNAVAILABLE", error.localizedDescription)
+ return
+ }
+ if let sessionError = error as? LanguageModelSession.Error, sessionError == .concurrentRequests {
+ promise.reject("APPLE_LLM_RATE_LIMITED", sessionError.localizedDescription)
+ return
+ }
+ }
+ #endif
+
if let generationError = error as? LanguageModelSession.GenerationError {
switch generationError {
case .guardrailViolation(_), .refusal(_, _):
promise.reject("APPLE_LLM_GUARDRAIL", generationError.localizedDescription)
case .exceededContextWindowSize(_):
promise.reject("APPLE_LLM_CONTEXT_LIMIT", generationError.localizedDescription)
+ case .decodingFailure(_):
+ // Structured output that can't be decoded, most often because maximumResponseTokens cut it
+ // off. JS treats it as an output limit and retries on smaller input.
+ promise.reject("APPLE_LLM_OUTPUT_LIMIT", generationError.localizedDescription)
case .rateLimited(_), .concurrentRequests(_):
promise.reject("APPLE_LLM_RATE_LIMITED", generationError.localizedDescription)
case .assetsUnavailable(_), .unsupportedLanguageOrLocale(_):
diff --git a/openwhispr-mobile/src/lib/__tests__/cleanupTranscript.onDevice.test.ts b/openwhispr-mobile/src/lib/__tests__/cleanupTranscript.onDevice.test.ts
index 8c59207be..880f3076c 100644
--- a/openwhispr-mobile/src/lib/__tests__/cleanupTranscript.onDevice.test.ts
+++ b/openwhispr-mobile/src/lib/__tests__/cleanupTranscript.onDevice.test.ts
@@ -128,6 +128,7 @@ describe('a long transcript', () => {
it.each([
['APPLE_LLM_RATE_LIMITED', 'Apple Intelligence was busy.'],
+ ['APPLE_LLM_CONTEXT_LIMIT', 'This transcript is too long for On-Device cleanup.'],
['APPLE_LLM_GUARDRAIL', 'Cleanup failed.'],
['APPLE_LLM_FAILED', 'Cleanup failed.'],
])('pastes the raw transcript after one %s attempt', async (code, reason) => {
@@ -142,6 +143,24 @@ it.each([
expect(onSkipped).toHaveBeenCalledWith(`${reason} Your raw transcript is saved.`);
});
+// The skip before the run counts once; ReasoningService counts again for the context and the
+// output cap, and a higher second count refuses the run as too long.
+it('names a too-long transcript when ReasoningService refuses it', async () => {
+ mockNative.countTokens
+ .mockResolvedValueOnce(600)
+ .mockResolvedValueOnce(800)
+ .mockResolvedValueOnce(2_000);
+ const onSkipped = jest.fn();
+
+ await expect(
+ cleanupTranscript('um hello there', { inferenceRoute: onDeviceRoute, onSkipped }),
+ ).resolves.toBe('um hello there');
+ expect(mockNative.generateText).not.toHaveBeenCalled();
+ expect(onSkipped).toHaveBeenCalledWith(
+ 'This transcript is too long for On-Device cleanup. Your raw transcript is saved.',
+ );
+});
+
it('returns the cleaned text when the model answers in time', async () => {
mockNative.generateText.mockResolvedValue({
text: 'Hello there.',
diff --git a/openwhispr-mobile/src/lib/__tests__/localReasoning.test.ts b/openwhispr-mobile/src/lib/__tests__/localReasoning.test.ts
index 65a09ce2b..a63b9ade8 100644
--- a/openwhispr-mobile/src/lib/__tests__/localReasoning.test.ts
+++ b/openwhispr-mobile/src/lib/__tests__/localReasoning.test.ts
@@ -26,8 +26,11 @@ jest.mock('@/store/useConfigStore', () => ({
import {
canRunLocalReasoning,
clearLocalReasoningReadinessCache,
+ countLocalInputTokens,
+ fitsLocalCleanupOutput,
getLocalReasoningReadiness,
getLocalReasoningUnavailableMessage,
+ isLocalOutputLimitError,
isLocalReasoningUnsupported,
shouldUseLocalReasoning,
toLocalReasoningError,
@@ -35,6 +38,7 @@ import {
import { AppleLLM } from '@/lib/appleLLM';
const mockAppleAvailability = AppleLLM.getAvailability as jest.Mock;
+const mockCountTokens = AppleLLM.countTokens as jest.Mock;
beforeEach(() => {
jest.clearAllMocks();
@@ -165,13 +169,63 @@ describe('toLocalReasoningError', () => {
expect(toLocalReasoningError(cancelled)).toMatchObject({ code: 'APPLE_LLM_CANCELLED' });
});
- it.each(['APPLE_LLM_GUARDRAIL', 'APPLE_LLM_RATE_LIMITED', 'APPLE_LLM_CONTEXT_LIMIT'])(
- 'marks %s as not worth retrying',
- (code) => {
- expect(toLocalReasoningError(Object.assign(new Error('x'), { code }))).toMatchObject({
- code,
- retryable: false,
- });
- },
+ it.each([
+ 'APPLE_LLM_GUARDRAIL',
+ 'APPLE_LLM_RATE_LIMITED',
+ 'APPLE_LLM_CONTEXT_LIMIT',
+ 'APPLE_LLM_OUTPUT_LIMIT',
+ ])('marks %s as not worth retrying', (code) => {
+ expect(toLocalReasoningError(Object.assign(new Error('x'), { code }))).toMatchObject({
+ code,
+ retryable: false,
+ });
+ });
+});
+
+it('reads the native output-limit code as an output limit, and nothing else', () => {
+ const outputLimit = toLocalReasoningError(
+ Object.assign(new Error('decodingFailure'), { code: 'APPLE_LLM_OUTPUT_LIMIT' }),
);
+ expect(isLocalOutputLimitError(outputLimit)).toBe(true);
+ expect(
+ isLocalOutputLimitError(Object.assign(new Error('x'), { code: 'APPLE_LLM_CONTEXT_LIMIT' })),
+ ).toBe(false);
+ expect(isLocalOutputLimitError(new Error('x'))).toBe(false);
+});
+
+describe('countLocalInputTokens', () => {
+ it('counts on the device, and estimates instructions and prompt together without it', async () => {
+ mockCountTokens.mockResolvedValueOnce(42);
+ await expect(countLocalInputTokens({ instructions: 'rules', prompt: 'text' })).resolves.toBe(
+ 42,
+ );
+ expect(mockCountTokens).toHaveBeenCalledWith({ instructions: 'rules', prompt: 'text' });
+
+ mockCountTokens.mockResolvedValueOnce(null);
+ await expect(
+ countLocalInputTokens({ instructions: 'a'.repeat(33), prompt: 'b'.repeat(33) }),
+ ).resolves.toBe(20);
+ });
+});
+
+describe('fitsLocalCleanupOutput', () => {
+ // A 2,000-word dictation fits a 4,096-token context, but its cleaned copy can't fit the
+ // 900-token output cap.
+ it('refuses a transcript whose cleaned copy would run past the output cap', async () => {
+ mockCountTokens.mockResolvedValueOnce(2_060);
+ await expect(fitsLocalCleanupOutput('long dictation')).resolves.toBe(false);
+ expect(mockCountTokens).toHaveBeenCalledWith({ prompt: 'long dictation' });
+ });
+
+ it('accepts a transcript that leaves room for punctuation under the cap', async () => {
+ mockCountTokens.mockResolvedValueOnce(720);
+ await expect(fitsLocalCleanupOutput('short dictation')).resolves.toBe(true);
+ });
+
+ it('estimates from length where iOS cannot count tokens', async () => {
+ mockCountTokens.mockResolvedValueOnce(null);
+ await expect(fitsLocalCleanupOutput('word '.repeat(600))).resolves.toBe(false);
+ mockCountTokens.mockResolvedValueOnce(null);
+ await expect(fitsLocalCleanupOutput('word '.repeat(100))).resolves.toBe(true);
+ });
});
diff --git a/openwhispr-mobile/src/lib/cleanupTranscript.ts b/openwhispr-mobile/src/lib/cleanupTranscript.ts
index 6c8550373..d8aab0b7e 100644
--- a/openwhispr-mobile/src/lib/cleanupTranscript.ts
+++ b/openwhispr-mobile/src/lib/cleanupTranscript.ts
@@ -13,7 +13,7 @@ import {
} from './dictationAgent';
import { buildDictationHints } from './dictationHints';
import {
- LOCAL_OUTPUT_TOKEN_RESERVE,
+ LOCAL_CLEANUP_MAX_TRANSCRIPT_TOKENS,
countLocalReasoningTokens,
estimateLocalTokens,
getLocalReasoningReadiness,
@@ -49,11 +49,6 @@ function createTimeoutSignal(timeoutMs: number): { signal: AbortSignal; cancel:
};
}
-// Apple Intelligence stops at LOCAL_OUTPUT_TOKEN_RESERVE without an error, so a transcript
-// whose cleaned copy might not fit would come back cut short. The margin covers the
-// punctuation and capitals cleanup adds.
-const LOCAL_CLEANUP_MAX_TRANSCRIPT_TOKENS = Math.floor(LOCAL_OUTPUT_TOKEN_RESERVE * 0.8);
-
// Apple Intelligence writes a cleaned copy about as long as the transcript, at roughly 30 tokens a
// second on an iPhone 15 Pro (Apple's figure), so a long one can't finish in Cloud's 12 s. The rate
// here is lower so a slower or busier iPhone still finishes; the [reasoning] dev log reports the
@@ -68,6 +63,8 @@ function localCleanupTimeoutMs(transcriptTokens: number): number {
);
}
+const TOO_LONG_FOR_ON_DEVICE = 'This transcript is too long for On-Device cleanup.';
+
// Why an on-device pass can't run, or, for cleanup, the transcript's length in tokens.
async function prepareLocalRun(
text: string,
@@ -82,16 +79,19 @@ async function prepareLocalRun(
if (scope !== 'cleanup') return {};
const tokens = (await countLocalReasoningTokens({ prompt: text })) ?? estimateLocalTokens(text);
return tokens > LOCAL_CLEANUP_MAX_TRANSCRIPT_TOKENS
- ? { skipReason: 'This transcript is too long for On-Device cleanup.' }
+ ? { skipReason: TOO_LONG_FOR_ON_DEVICE }
: { tokens };
}
-// Apple Intelligence's two common failures say what happened. The only signal a cleanup run gets
-// is its timeout, so a cancelled one took too long.
+// Apple Intelligence's common failures say what happened. The only signal a cleanup run gets is
+// its timeout, so a cancelled one took too long.
function cleanupFailureReason(error: unknown): string {
if (error instanceof LocalReasoningError) {
if (error.code === 'APPLE_LLM_CANCELLED') return 'Apple Intelligence took too long.';
if (error.code === 'APPLE_LLM_RATE_LIMITED') return 'Apple Intelligence was busy.';
+ if (error.code === 'LOCAL_CONTEXT_LIMIT' || error.code === 'APPLE_LLM_CONTEXT_LIMIT') {
+ return TOO_LONG_FOR_ON_DEVICE;
+ }
}
return 'Cleanup failed.';
}
diff --git a/openwhispr-mobile/src/lib/localReasoning.ts b/openwhispr-mobile/src/lib/localReasoning.ts
index 69f5087bc..1251bb365 100644
--- a/openwhispr-mobile/src/lib/localReasoning.ts
+++ b/openwhispr-mobile/src/lib/localReasoning.ts
@@ -12,6 +12,13 @@ export const LOCAL_OUTPUT_TOKEN_RESERVE = 900;
export const LOCAL_CONTEXT_SAFETY_TOKENS = 300;
export const LOCAL_TOKEN_CHAR_RATIO = 3.5;
+// Local requests pass LOCAL_OUTPUT_TOKEN_RESERVE as maximumResponseTokens, and Apple Intelligence
+// stops there without an error. A larger context (iOS 27's 8,192) grows the input budget, not this
+// reserve. Cleanup writes back about as many tokens as it reads, so a transcript whose cleaned copy
+// might not fit would come back cut short. The margin covers the punctuation and capitals cleanup
+// adds.
+export const LOCAL_CLEANUP_MAX_TRANSCRIPT_TOKENS = Math.floor(LOCAL_OUTPUT_TOKEN_RESERVE * 0.8);
+
let cachedReadiness: Promise<LocalReasoningReadiness> | null = null;
export class LocalReasoningError extends Error {
@@ -161,6 +168,16 @@ export async function countLocalReasoningTokens(input: {
}
}
+export async function countLocalInputTokens(input: {
+ instructions?: string;
+ prompt: string;
+}): Promise<number> {
+ return (
+ (await countLocalReasoningTokens(input)) ??
+ estimateLocalTokens([input.instructions, input.prompt].filter(Boolean).join('\n\n'))
+ );
+}
+
export async function fitsLocalReasoningBudget(input: {
instructions?: string;
prompt: string;
@@ -168,16 +185,18 @@ export async function fitsLocalReasoningBudget(input: {
budget?: number;
}): Promise<boolean> {
const budget = input.budget ?? getLocalInputTokenBudget(input.readiness);
- const nativeCount = await countLocalReasoningTokens({
+ const count = await countLocalInputTokens({
instructions: input.instructions,
prompt: input.prompt,
});
- const count =
- nativeCount ??
- estimateLocalTokens([input.instructions, input.prompt].filter(Boolean).join('\n\n'));
return count < budget;
}
+export async function fitsLocalCleanupOutput(text: string): Promise<boolean> {
+ const tokens = (await countLocalReasoningTokens({ prompt: text })) ?? estimateLocalTokens(text);
+ return tokens <= LOCAL_CLEANUP_MAX_TRANSCRIPT_TOKENS;
+}
+
// This iPhone runs Apple Intelligence, even if it is turned off in Settings or still preparing
// its model. Disabled in AI Models or unavailable says nothing about the device either way.
export function canRunLocalReasoning(readiness?: LocalReasoningReadiness | null): boolean {
@@ -225,6 +244,7 @@ export function toLocalReasoningError(error: unknown): LocalReasoningError {
switch (code) {
case 'APPLE_LLM_GUARDRAIL':
case 'APPLE_LLM_CONTEXT_LIMIT':
+ case 'APPLE_LLM_OUTPUT_LIMIT':
case 'APPLE_LLM_RATE_LIMITED':
case 'APPLE_LLM_UNAVAILABLE':
case 'APPLE_LLM_FAILED':
@@ -246,3 +266,15 @@ export function isLocalContextLimitError(error: unknown): boolean {
(error as { code?: unknown }).code === 'APPLE_LLM_CONTEXT_LIMIT'
);
}
+
+// FoundationModels throws decodingFailure (a ParsingError on iOS 27) when guided generation's
+// output can't be decoded. That is most often the output cap cutting it off mid-structure, but
+// malformed output reads the same; either way, less material per run is what helps.
+export function isLocalOutputLimitError(error: unknown): boolean {
+ return (
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ (error as { code?: unknown }).code === 'APPLE_LLM_OUTPUT_LIMIT'
+ );
+}
diff --git a/openwhispr-mobile/src/lib/notes/__tests__/localMeetingNotes.test.ts b/openwhispr-mobile/src/lib/notes/__tests__/localMeetingNotes.test.ts
index 1fecd176b..d02c569fc 100644
--- a/openwhispr-mobile/src/lib/notes/__tests__/localMeetingNotes.test.ts
+++ b/openwhispr-mobile/src/lib/notes/__tests__/localMeetingNotes.test.ts
@@ -15,8 +15,9 @@ jest.mock('@/data', () => ({
jest.mock('@/lib/localReasoning', () => ({
LOCAL_OUTPUT_TOKEN_RESERVE: 900,
+ countLocalInputTokens: jest.fn(async () => 700),
fitsLocalReasoningBudget: jest.fn(async () => true),
- getLocalInputTokenBudget: () => 2896,
+ getLocalInputTokenBudget: jest.fn(() => 2896),
getLocalReasoningReadiness: jest.fn(async () => ({
status: 'ready',
contextSize: 4096,
@@ -27,6 +28,11 @@ jest.mock('@/lib/localReasoning', () => ({
error !== null &&
'code' in error &&
(error as { code?: unknown }).code === 'APPLE_LLM_CONTEXT_LIMIT',
+ isLocalOutputLimitError: (error: unknown) =>
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ (error as { code?: unknown }).code === 'APPLE_LLM_OUTPUT_LIMIT',
toLocalReasoningError: (error: unknown) => error,
}));
@@ -36,12 +42,43 @@ import {
} from '../localMeetingNotes';
import { AppleLLM } from '@/lib/appleLLM';
import { notesRepository } from '@/data';
+import {
+ countLocalInputTokens,
+ fitsLocalReasoningBudget,
+ getLocalInputTokenBudget,
+} from '@/lib/localReasoning';
const mockGenerateMeetingNotes = AppleLLM.generateMeetingNotes as jest.Mock;
const mockGetNoteById = notesRepository.getNoteById as jest.Mock;
const mockGetSegments = notesRepository.getSegments as jest.Mock;
const mockGetSpeakers = notesRepository.getSpeakers as jest.Mock;
const mockGetActions = notesRepository.getActions as jest.Mock;
+const mockFitsBudget = fitsLocalReasoningBudget as jest.Mock;
+const mockGetInputBudget = getLocalInputTokenBudget as jest.Mock;
+const mockCountInputTokens = countLocalInputTokens as jest.Mock;
+
+const outputLimit = (): Error =>
+ Object.assign(new Error('decodingFailure'), { code: 'APPLE_LLM_OUTPUT_LIMIT' });
+
+const partialNotes = (summary: string, decisions: string[] = []) => ({
+ summary,
+ keyDiscussionPoints: [],
+ decisions,
+ actionItems: [],
+ followUps: [],
+});
+
+const segmentsOf = (count: number) =>
+ Array.from({ length: count }, (_, index) => ({
+ id: 100 + index,
+ noteId: 7,
+ startMs: index * 60_000,
+ endMs: index * 60_000 + 2000,
+ text: `Line ${index} about the launch plan.`,
+ // Alternating speakers, since one speaker's consecutive segments read as one line.
+ speakerLabel: `speaker_${index % 2}`,
+ sortOrder: index,
+ }));
const meetingNote = {
id: 7,
@@ -65,6 +102,10 @@ const speaker = {
beforeEach(() => {
jest.clearAllMocks();
+ mockGenerateMeetingNotes.mockReset();
+ mockFitsBudget.mockResolvedValue(true);
+ mockGetInputBudget.mockReturnValue(2896);
+ mockCountInputTokens.mockResolvedValue(700);
mockGetNoteById.mockReturnValue(meetingNote);
mockGetSegments.mockReturnValue([
{
@@ -165,4 +206,140 @@ describe('local meeting notes', () => {
);
expect(mockGenerateMeetingNotes.mock.calls[0][0].prompt).not.toContain('Unknown speaker');
});
+
+ // Guided generation cut off by the output cap can't be decoded (FoundationModels'
+ // decodingFailure), which the native module reports as APPLE_LLM_OUTPUT_LIMIT.
+ it('halves a chunk whose notes run past the output cap and retries it', async () => {
+ mockGetSegments.mockReturnValue(segmentsOf(2));
+ mockGenerateMeetingNotes
+ .mockRejectedValueOnce(outputLimit())
+ .mockResolvedValueOnce(partialNotes('First half'))
+ .mockResolvedValueOnce(partialNotes('Second half'))
+ .mockResolvedValueOnce(partialNotes('Merged summary'));
+
+ await expect(generateLocalMeetingNotes(7)).resolves.toContain('Merged summary');
+ expect(mockGenerateMeetingNotes).toHaveBeenCalledTimes(4);
+ expect(mockGenerateMeetingNotes.mock.calls[1][0].prompt).toContain('Line 0');
+ expect(mockGenerateMeetingNotes.mock.calls[1][0].prompt).not.toContain('Line 1');
+ expect(mockGenerateMeetingNotes.mock.calls[2][0].prompt).toContain('Line 1');
+ });
+
+ it('does not split one line by words when its notes run past the output cap', async () => {
+ mockGenerateMeetingNotes.mockRejectedValue(outputLimit());
+
+ await expect(generateLocalMeetingNotes(7)).rejects.toMatchObject({
+ code: 'APPLE_LLM_OUTPUT_LIMIT',
+ });
+ expect(mockGenerateMeetingNotes).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops halving a chunk whose notes keep running past the output cap', async () => {
+ mockGetSegments.mockReturnValue(segmentsOf(8));
+ mockGenerateMeetingNotes.mockRejectedValue(outputLimit());
+
+ await expect(generateLocalMeetingNotes(7)).rejects.toMatchObject({
+ code: 'APPLE_LLM_OUTPUT_LIMIT',
+ });
+ // The chunk, its first half, then that half's first quarter, which ends the note.
+ expect(mockGenerateMeetingNotes).toHaveBeenCalledTimes(3);
+ });
+
+ it('merges partial notes by hand when the merged notes run past the output cap', async () => {
+ mockGetSegments.mockReturnValue(segmentsOf(2));
+ mockFitsBudget.mockImplementation(
+ async ({ prompt }: { prompt: string }) =>
+ // One line per chunk, so the transcript maps in two runs; the merge prompt fits.
+ prompt.includes('Merge these') || !(prompt.includes('Line 0') && prompt.includes('Line 1')),
+ );
+ mockGenerateMeetingNotes
+ .mockResolvedValueOnce(partialNotes('First chunk.', ['Ship Friday.']))
+ .mockResolvedValueOnce(partialNotes('Second chunk.', ['Alice owns QA.']))
+ .mockRejectedValueOnce(outputLimit());
+
+ const markdown = await generateLocalMeetingNotes(7);
+
+ expect(mockGenerateMeetingNotes).toHaveBeenCalledTimes(3);
+ expect(markdown).toContain('First chunk. Second chunk.');
+ expect(markdown).toContain('- Ship Friday.\n- Alice owns QA.');
+ });
+
+ it.each([
+ [2896, 2896],
+ [6992, 2896],
+ ])("caps a merge at iOS 26's input budget (budget %i)", async (inputBudget, mergeBudget) => {
+ mockGetInputBudget.mockReturnValue(inputBudget);
+ mockGetSegments.mockReturnValue(segmentsOf(2));
+ mockFitsBudget.mockImplementation(
+ async ({ prompt }: { prompt: string }) =>
+ prompt.includes('Merge these') || !(prompt.includes('Line 0') && prompt.includes('Line 1')),
+ );
+ mockGenerateMeetingNotes.mockResolvedValue(partialNotes('Notes'));
+
+ await generateLocalMeetingNotes(7);
+
+ expect(mockFitsBudget).toHaveBeenCalledWith(
+ expect.objectContaining({
+ prompt: expect.stringContaining('Merge these'),
+ budget: mergeBudget,
+ }),
+ );
+ });
+
+ it.each([
+ // The default instructions leave a chunk of about 2,000 tokens, whatever the context.
+ [2896, 700, 2000],
+ [6992, 700, 2000],
+ // Long raw notes repeat in every chunk, so they don't take the transcript's room.
+ [6992, 1600, 2900],
+ // The input budget still caps a chunk.
+ [2896, 2000, 2896],
+ ])(
+ 'limits each chunk to the transcript the output cap allows (budget %i, overhead %i)',
+ async (inputBudget, overhead, chunkBudget) => {
+ mockGetInputBudget.mockReturnValue(inputBudget);
+ mockCountInputTokens.mockResolvedValue(overhead);
+ mockGenerateMeetingNotes.mockResolvedValue(partialNotes('Notes'));
+
+ await generateLocalMeetingNotes(7);
+
+ expect(mockCountInputTokens).toHaveBeenCalledWith({
+ instructions: expect.any(String),
+ prompt: '',
+ });
+ expect(mockFitsBudget).toHaveBeenCalledWith(expect.objectContaining({ budget: chunkBudget }));
+ },
+ );
+
+ it('keeps lines whole when the instructions and raw notes alone fill a chunk', async () => {
+ mockGetSegments.mockReturnValue([
+ { ...segmentsOf(1)[0], text: Array.from({ length: 40 }, (_, i) => `w${i}`).join(' ') },
+ ]);
+ mockCountInputTokens.mockResolvedValue(3000);
+ mockFitsBudget.mockResolvedValue(false);
+ mockGenerateMeetingNotes.mockResolvedValue(partialNotes('Notes'));
+
+ await generateLocalMeetingNotes(7);
+
+ expect(mockGenerateMeetingNotes).toHaveBeenCalledTimes(1);
+ expect(mockGenerateMeetingNotes.mock.calls[0][0].prompt).toContain('w0 w1');
+ });
+
+ // One speaker's consecutive segments are one line, so a long monologue is a single line.
+ it('splits one line too long for a chunk by words', async () => {
+ const words = Array.from({ length: 40 }, (_, index) => `w${index}`);
+ mockGetSegments.mockReturnValue([{ ...segmentsOf(1)[0], text: words.join(' ') }]);
+ const wordsIn = (prompt: string): string[] => prompt.match(/\bw\d+\b/g) ?? [];
+ mockFitsBudget.mockImplementation(
+ async ({ prompt }: { prompt: string }) => wordsIn(prompt).length <= 10,
+ );
+ mockGenerateMeetingNotes.mockResolvedValue(partialNotes('Notes'));
+
+ await generateLocalMeetingNotes(7);
+
+ const mapPrompts = mockGenerateMeetingNotes.mock.calls
+ .map(([request]) => request.prompt as string)
+ .filter((prompt) => !prompt.includes('Merge these'));
+ expect(mapPrompts).toHaveLength(4);
+ expect(mapPrompts.flatMap(wordsIn)).toEqual(words);
+ });
});
diff --git a/openwhispr-mobile/src/lib/notes/localMeetingNotes.ts b/openwhispr-mobile/src/lib/notes/localMeetingNotes.ts
index e597fa70d..2d4cd76a1 100644
--- a/openwhispr-mobile/src/lib/notes/localMeetingNotes.ts
+++ b/openwhispr-mobile/src/lib/notes/localMeetingNotes.ts
@@ -2,10 +2,12 @@ import { AppleLLM } from '@/lib/appleLLM';
import { notesRepository } from '@/data';
import type { Note, Segment, Speaker } from '@/data/types';
import {
+ countLocalInputTokens,
fitsLocalReasoningBudget,
getLocalInputTokenBudget,
getLocalReasoningReadiness,
isLocalContextLimitError,
+ isLocalOutputLimitError,
LOCAL_OUTPUT_TOKEN_RESERVE,
toLocalReasoningError,
} from '@/lib/localReasoning';
@@ -21,6 +23,23 @@ import type { StructuredMeetingNotes } from '@/types';
const DEFAULT_LOCAL_MEETING_ACTION_PROMPT =
'Transform this meeting transcript into concise, actionable meeting notes.';
+// Each chunk's notes have to fit LOCAL_OUTPUT_TOKEN_RESERVE, the maximumResponseTokens these runs
+// pass, which a larger context (iOS 27's 8,192) doesn't grow. Chunks the size of iOS 26's whole
+// input budget already ran past it. Notes grow with the transcript they cover, so the limit is on
+// transcript, not on the instructions and raw notes every chunk repeats; with the default
+// instructions, a full chunk is about 2,000 tokens.
+const LOCAL_MEETING_CHUNK_MAX_TRANSCRIPT_TOKENS = 1_300;
+
+// A chunk whose notes still run past the cap is halved, and each half can be halved again, at most
+// this many times in a row: up to 7 runs for one chunk, so a model that keeps looping can't turn it
+// into dozens of slow runs. A piece that still overflows fails the note.
+const MAX_OUTPUT_LIMIT_SPLITS = 2;
+
+// Merged notes have to fit LOCAL_OUTPUT_TOKEN_RESERVE too, so a merge reads at most iOS 26's whole
+// input budget (4,096 - 900 - 300), the size merges run at there, however large the context. A
+// bigger merge is more likely to run to the cap, a full slow run before the hand merge.
+const LOCAL_MEETING_MERGE_MAX_INPUT_TOKENS = 2_896;
+
const emptyMeetingNotes = (): StructuredMeetingNotes => ({
summary: '',
keyDiscussionPoints: [],
@@ -134,11 +153,13 @@ async function buildTranscriptChunks(input: {
meetingContext?: MeetingNotesContext;
instructions: string;
budget: number;
+ overhead: number;
}): Promise<string[][]> {
const chunks: string[][] = [];
let current: string[] = [];
+ const pending = [...input.lines];
- for (const line of input.lines) {
+ for (let line = pending.shift(); line !== undefined; line = pending.shift()) {
const candidate = [...current, line];
const prompt = buildChunkInput({
note: input.note,
@@ -151,11 +172,19 @@ async function buildTranscriptChunks(input: {
budget: input.budget,
});
- if (!fits && current.length > 0) {
+ if (fits) {
+ current = candidate;
+ } else if (current.length > 0) {
chunks.push(current);
- current = [line];
+ current = [];
+ pending.unshift(line);
} else {
- current = candidate;
+ // One speaker's consecutive segments are one line, so a long stretch by one speaker can
+ // outgrow a chunk by itself. It is split by words; a single word is kept as it is, and so is
+ // every line when the instructions and raw notes alone fill a chunk.
+ const halves = input.overhead < input.budget ? splitTranscriptLine(line) : null;
+ if (halves) pending.unshift(...halves);
+ else current = [line];
}
}
@@ -212,7 +241,9 @@ async function mapChunkWithRetry(input: {
meetingContext?: MeetingNotesContext;
instructions: string;
previousSummary?: string;
+ outputLimitSplitsLeft?: number;
}): Promise<StructuredMeetingNotes[]> {
+ const outputLimitSplitsLeft = input.outputLimitSplitsLeft ?? MAX_OUTPUT_LIMIT_SPLITS;
const chunkInput = buildChunkInput({
note: input.note,
lines: input.lines,
@@ -230,25 +261,37 @@ async function mapChunkWithRetry(input: {
}),
];
} catch (error) {
- if (!isLocalContextLimitError(error)) throw error;
+ const outputLimit = isLocalOutputLimitError(error);
+ if (!isLocalContextLimitError(error) && !(outputLimit && outputLimitSplitsLeft > 0)) {
+ throw error;
+ }
+ // Notes too long for the output cap come from too much material, so fewer lines fix them.
+ // Chunking already split any line longer than a chunk's transcript limit, so one line's notes
+ // overflowing means the model is looping, and half a line won't help.
const split =
input.lines.length > 1
? [
input.lines.slice(0, Math.ceil(input.lines.length / 2)),
input.lines.slice(Math.ceil(input.lines.length / 2)),
]
- : splitTranscriptLine(input.lines[0])?.map((line) => [line]);
+ : outputLimit
+ ? null
+ : splitTranscriptLine(input.lines[0])?.map((line) => [line]);
if (!split) throw error;
- const left = await mapChunkWithRetry({
+ const next = {
...input,
+ outputLimitSplitsLeft: outputLimit ? outputLimitSplitsLeft - 1 : outputLimitSplitsLeft,
+ };
+ const left = await mapChunkWithRetry({
+ ...next,
lines: split[0],
});
const nextSummary = left[left.length - 1]?.summary || input.previousSummary;
const right = await mapChunkWithRetry({
- ...input,
+ ...next,
lines: split[1],
previousSummary: nextSummary,
});
@@ -279,10 +322,15 @@ async function reduceStructuredNotes(input: {
budget: input.budget,
})
) {
- return generateStructuredNotes({
- instructions: input.instructions,
- prompt,
- });
+ try {
+ return await generateStructuredNotes({
+ instructions: input.instructions,
+ prompt,
+ });
+ } catch (error) {
+ // Merged notes too long for the output cap are merged like ones too long to read.
+ if (!isLocalOutputLimitError(error)) throw error;
+ }
}
if (input.notes.length === 2) {
@@ -327,13 +375,19 @@ export async function generateLocalMeetingNotes(
const readiness = await getLocalReasoningReadiness();
const budget = getLocalInputTokenBudget(readiness);
const meetingContext = resolveMeetingContext(note);
+ const chunkOverhead = await countLocalInputTokens({
+ instructions,
+ prompt: buildChunkInput({ note, lines: [], meetingContext }),
+ });
+ const chunkBudget = Math.min(budget, chunkOverhead + LOCAL_MEETING_CHUNK_MAX_TRANSCRIPT_TOKENS);
const lines = transcriptLines(segments, notesRepository.getSpeakers(noteId));
const chunks = await buildTranscriptChunks({
note,
lines,
meetingContext,
instructions,
- budget,
+ budget: chunkBudget,
+ overhead: chunkOverhead,
});
const mapped: StructuredMeetingNotes[] = [];
@@ -353,7 +407,7 @@ export async function generateLocalMeetingNotes(
const reduced = await reduceStructuredNotes({
notes: mapped,
instructions,
- budget,
+ budget: Math.min(budget, LOCAL_MEETING_MERGE_MAX_INPUT_TOKENS),
});
const markdown = renderStructuredMeetingNotesToMarkdown(reduced);
diff --git a/openwhispr-mobile/src/services/reasoning/ReasoningService.ts b/openwhispr-mobile/src/services/reasoning/ReasoningService.ts
index 0fd8fda9f..c956a05e8 100644
--- a/openwhispr-mobile/src/services/reasoning/ReasoningService.ts
+++ b/openwhispr-mobile/src/services/reasoning/ReasoningService.ts
@@ -3,6 +3,7 @@ import { buildProviderPrompt, stripThinkingTags } from './buildProviderPrompt';
import { api } from '../../lib/apiClient';
import { buildChatOverNotePayload, type ChatOverNoteRequest } from '../../lib/notes/chatOverNote';
import {
+ fitsLocalCleanupOutput,
fitsLocalReasoningBudget,
getLocalReasoningReadiness,
getLocalReasoningUnavailableMessage,
@@ -164,11 +165,16 @@ export class ReasoningService {
const readiness = await getLocalReasoningReadiness();
if (readiness.status === 'ready') {
const instructions = buildLocalReasoningInstructions(localRequest);
- const fits = await fitsLocalReasoningBudget({
- instructions,
- prompt: localRequest.text,
- readiness,
- });
+ const fits =
+ (await fitsLocalReasoningBudget({
+ instructions,
+ prompt: localRequest.text,
+ readiness,
+ })) &&
+ // The input fitting the context isn't enough for cleanup: its reply is as long as the
+ // transcript, and Apple Intelligence cuts it off at LOCAL_OUTPUT_TOKEN_RESERVE without an
+ // error.
+ (scope !== 'cleanup' || (await fitsLocalCleanupOutput(text)));
if (!fits) {
if (!allowCloudFallback) {
diff --git a/openwhispr-mobile/src/services/reasoning/__tests__/ReasoningService.localInstructions.test.ts b/openwhispr-mobile/src/services/reasoning/__tests__/ReasoningService.localInstructions.test.ts
index 4eb0c337b..33c014e21 100644
--- a/openwhispr-mobile/src/services/reasoning/__tests__/ReasoningService.localInstructions.test.ts
+++ b/openwhispr-mobile/src/services/reasoning/__tests__/ReasoningService.localInstructions.test.ts
@@ -16,6 +16,7 @@ jest.mock('@/lib/localReasoning', () => ({
options.isPrivateNote === true,
getLocalReasoningReadiness: async (): Promise<{ status: string }> => ({ status: 'ready' }),
fitsLocalReasoningBudget: async (): Promise<boolean> => true,
+ fitsLocalCleanupOutput: async (): Promise<boolean> => true,
getLocalReasoningUnavailableMessage: (): string => 'Local unavailable',
LocalReasoningError: class extends Error {
constructor(_code: string, message: string) {
diff --git a/openwhispr-mobile/src/services/reasoning/__tests__/ReasoningService.localRouting.test.ts b/openwhispr-mobile/src/services/reasoning/__tests__/ReasoningService.localRouting.test.ts
index ee21c26c6..e769fa0ad 100644
--- a/openwhispr-mobile/src/services/reasoning/__tests__/ReasoningService.localRouting.test.ts
+++ b/openwhispr-mobile/src/services/reasoning/__tests__/ReasoningService.localRouting.test.ts
@@ -12,6 +12,7 @@ jest.mock('@/lib/apiClient', () => ({
}));
jest.mock('@/lib/localReasoning', () => ({
+ fitsLocalCleanupOutput: jest.fn(),
fitsLocalReasoningBudget: jest.fn(),
getLocalReasoningReadiness: jest.fn(),
getLocalReasoningUnavailableMessage: () => 'Local unavailable',
@@ -36,6 +37,7 @@ jest.mock('@/services/reasoning/LocalReasoningService', () => ({
import { ReasoningService } from '../ReasoningService';
import { api } from '@/lib/apiClient';
import {
+ fitsLocalCleanupOutput,
fitsLocalReasoningBudget,
getLocalReasoningReadiness,
isLocalReasoningRequired,
@@ -46,6 +48,7 @@ const mockPost = api.post as jest.Mock;
const mockIsLocalRequired = isLocalReasoningRequired as jest.Mock;
const mockGetReadiness = getLocalReasoningReadiness as jest.Mock;
const mockFitsBudget = fitsLocalReasoningBudget as jest.Mock;
+const mockFitsCleanupOutput = fitsLocalCleanupOutput as jest.Mock;
const mockLocalProcessText = LocalReasoningService.processText as jest.Mock;
beforeEach(() => {
@@ -57,6 +60,7 @@ beforeEach(() => {
tokenCounting: true,
});
mockFitsBudget.mockResolvedValue(true);
+ mockFitsCleanupOutput.mockResolvedValue(true);
mockLocalProcessText.mockResolvedValue({ text: 'local result', model: 'apple-fm' });
});
@@ -172,3 +176,61 @@ it('fails On-Device note chat rather than falling back to Cloud when the device
).rejects.toThrow();
expect(mockPost).not.toHaveBeenCalled();
});
+
+describe('On-Device cleanup output cap', () => {
+ const localCleanup = {
+ text: 'a dictation of about two thousand words',
+ inferenceScope: 'cleanup' as const,
+ inferenceRoute: { mode: 'local' as const, scope: 'cleanup' as const },
+ };
+
+ // The transcript fits the context, but its cleaned copy is as long and Apple Intelligence
+ // would cut it off at the output cap without an error.
+ it('refuses a cleanup whose reply would run past the output cap', async () => {
+ mockFitsCleanupOutput.mockResolvedValue(false);
+
+ await expect(ReasoningService.processText(localCleanup)).rejects.toMatchObject({
+ code: 'LOCAL_CONTEXT_LIMIT',
+ });
+
+ expect(mockFitsCleanupOutput).toHaveBeenCalledWith(localCleanup.text);
+ expect(mockLocalProcessText).not.toHaveBeenCalled();
+ expect(mockPost).not.toHaveBeenCalled();
+ });
+
+ it('cleans on the device when the reply fits', async () => {
+ await expect(ReasoningService.processText(localCleanup)).resolves.toEqual({
+ text: 'local result',
+ model: 'apple-fm',
+ });
+ });
+
+ it('goes to Cloud instead when the caller allowed it', async () => {
+ mockFitsCleanupOutput.mockResolvedValue(false);
+
+ await expect(
+ ReasoningService.processText({
+ text: 'long private note',
+ systemPrompt: 'clean this',
+ inferenceScope: 'cleanup',
+ routing: { isPrivateNote: true, allowCloudFallback: true },
+ }),
+ ).resolves.toEqual({ text: 'cloud result', model: 'cloud-model' });
+
+ expect(mockLocalProcessText).not.toHaveBeenCalled();
+ });
+
+ it('leaves notes, whose reply is shorter than what they read, to the context check', async () => {
+ mockFitsCleanupOutput.mockResolvedValue(false);
+
+ await ReasoningService.processText({
+ text: 'long private note',
+ systemPrompt: 'summarize this',
+ inferenceScope: 'notes',
+ routing: { isPrivateNote: true },
+ });
+
+ expect(mockFitsCleanupOutput).not.toHaveBeenCalled();
+ expect(mockLocalProcessText).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/openwhispr-mobile/src/types/index.ts b/openwhispr-mobile/src/types/index.ts
index 244cfbc2b..de12a779c 100644
--- a/openwhispr-mobile/src/types/index.ts
+++ b/openwhispr-mobile/src/types/index.ts
@@ -155,6 +155,7 @@ export interface LocalReasoningReadiness {
export type LocalReasoningErrorCode =
| 'APPLE_LLM_GUARDRAIL'
| 'APPLE_LLM_CONTEXT_LIMIT'
+ | 'APPLE_LLM_OUTPUT_LIMIT'
| 'APPLE_LLM_RATE_LIMITED'
| 'APPLE_LLM_UNAVAILABLE'
| 'APPLE_LLM_FAILED'